Skip to content

测试最佳实践

原则 for trustworthy 测试: FAST, 单个-assertion, behavior-focused, and DRY.

你将学到

  • FIRST 原则: 快, Isolated, Repeatable, Self-验证, Timely
  • 测试 behavior over implementation 到 keep 测试 resilient
  • Balancing DRY 使用 DAMP 到 avoid brittle 测试设置
  • Keeping suite trustworthy, 快, and maintainable

概念讲解

FIRST Principles

A trustworthy test suite follows FIRST. Fast: thousands of unit tests run in seconds so developers run them constantly. Isolated: no test depends on another or on order; each can run alone. Repeatable: the same result every time, no random or network. Self-verifying: pass or fail automatically with a clear signal, no manual inspection. Timely: written close to the code, ideally before it (TDD). Violating any of these erodes trust.

Behavior over Implementation

Tests should assert what the code does, not how it does it. A test that checks result.internalCache.大小 breaks when you rename the cache; a test that checks result.总计() survives refactors. Query by visible output, assert on public return values, and avoid asserting on private state, call counts to your own methods, or CSS classes. Behavior-focused tests let you refactor freely; implementation-coupled tests fight every change.

DRY vs DAMP

In production code, DRY (Don't Repeat Yourself) is king. In tests, a little repetition is healthy: each test should read top-to-bottom without jumping to shared helpers. Use DAMP (Descriptive And Meaningful Phrases) — extract setup into helpers when it is truly identical, but inline the parts that vary so each test tells its own story. Over-abstracted test setup is the leading cause of tests no one understands.

Trustworthy Suites

A suite is only valuable if the team trusts it. Keep it green: fix or remove failing tests immediately. Keep it fast: a suite that takes ten minutes is one nobody runs. Keep it meaningful: prune tests that assert nothing or duplicate others. Review tests in code review with the same rigor as production code. A trustworthy suite is a safety net; an untrustworthy one is dead weight that everyone ignores.

In Practice

Adopt these habits incrementally so they stick. Start by making the suite green and keeping it green — a red suite trains the team to ignore failures. Add a CI gate that blocks merges on red, and a coverage threshold that prevents silent drops. In code review, read the test changes as carefully as the production changes: ask whether the test would fail if the code broke, whether the name describes the behavior, and whether the setup is readable. Periodically run a "测试 review" session: delete tests that duplicate or assert nothing, consolidate overlapping setup, and fix or quarantine flaky tests. Treat the test suite as a product with users (your teammates) — its speed, clarity, and trustworthiness determine whether it protects you or slows you down.

示例代码

              import { describe, it, expect } from "vitest";
import { formatPrice } from "./format";

describe("formatPrice", () => {
  // Behavior-focused, isolated, self-verifying, repeatable
  it("formats a whole dollar amount with two decimals", () => {
    expect(formatPrice(10)).toBe("$10.00");
  });
  it("rounds to two decimal places", () => {
    expect(formatPrice(10.005)).toBe("$10.01");
  });
  it("handles zero", () => {
    expect(formatPrice(0)).toBe("$0.00");
  });
  it("formats negative amounts with a minus sign", () => {
    expect(formatPrice(-5)).toBe("-$5.00");
  });
});
            

每个测试是 independent, asserts one behavior, and 会失败如果 formatPrice broke. 否 implementation details leak in, 所以 refactors 是 safe.

动手试一试

  • Code Diff

    Review 测试更改 in 拉取请求使用 rigor 的 prod code.

  • JSON Formatter

    Inspect structured 输出你的 behavior assertions 检查.

常见错误

错误写法

Asserting on implementation details 如私有字段

正确做法

Assert on 公共 behavior and 可见输出. Implementation-coupled 测试 break on 每个 refactor and fight 更改相反的 启用它.

错误写法

Letting suite stay red '只是 for 现在'

正确做法

red suite 是 ignored. Fix failures immediately, or quarantine 使用 ticket. Trust 是困难到 rebuild 一次 team 学习到 ignore 测试.

练习 测试最佳实践

10 个练习

练习 测试最佳实践

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误