Skip to content

单元测试

如何 编写快, isolated 单元测试那个 pinpoint failures in individual 函数.

你将学到

  • 什么制作好 单元测试: 快, isolated, repeatable, self-验证
  • 排列-Act-Assert (AAA) 结构
  • 如何 isolate 单元通过 replacing 它的 dependencies
  • Naming 约定那个制作 failures self-explanatory

概念讲解

What Is a Unit?

A unit is the smallest piece of code that has a single, well-defined responsibility — typically one pure function or one method of a class. The defining trait of a unit test is isolation: the unit under test must not reach out to the network, the filesystem, the database, or the clock. Any such dependency is replaced with a test double so the test exercises only the unit's own logic.

Properties of a Good Unit Test

A good unit test follows the FIRST principles: Fast (runs in milliseconds), Isolated (independent of other tests and of order), Repeatable (gives the same result every time), Self-verifying (passes or fails automatically without manual inspection), and Timely (written close to the code it tests). A suite of thousands of FIRST unit tests can run in a few seconds and give you a precise map of what is broken.

Arrange-Act-Assert

The AAA pattern keeps tests readable. Arrange sets up the inputs and any fakes. Act calls the unit under test exactly once. Assert checks the result (and, if needed, that the fakes were called correctly). Keeping these three phases visually separated — often with a blank line — makes the test's intent obvious and failures easy to diagnose.

Naming

A test name should describe the scenario and the expected outcome, not the implementation. Names like 添加_discount_for_premium_customer or throws_when_quantity_is_negative turn a failing test list into a readable spec. Avoid generic names like test1 or 工作 — they tell you nothing when they break.

In Practice

When you sit down to write a unit test, start by identifying the smallest piece of behavior worth verifying. Arrange the inputs as plainly as possible, call the function once, and assert on the return value. If the function has a dependency that reaches outside — a database, the network, the clock — replace that dependency with a stub so the test stays fast and deterministic. Keep each test focused on one assertion concept; if you find yourself checking the return value and a side effect in the same test, split it into two named cases. Run the suite constantly while coding — the sub-second feedback is where the productivity gain comes from. Over time, a folder of well-named unit tests becomes a precise, readable specification of what your module does and how it should behave at its edges.

示例代码

              // Code under test
export function calculateTotal(items: { price: number; qty: number }[]): number {
  return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}

// Unit test (Vitest)
import { describe, it, expect } from "vitest";
import { calculateTotal } from "./cart";

describe("calculateTotal", () => {
  it("sums price * qty for every item", () => {
    const items = [
      { price: 10, qty: 2 },
      { price: 5, qty: 4 },
    ];
    expect(calculateTotal(items)).toBe(40);
  });

  it("returns 0 for an empty cart", () => {
    expect(calculateTotal([])).toBe(0);
  });
});
            

calculateTotal 是 pure 函数使用否 边副作用, 制作它 ideal for 单元测试. 每个测试 follows 排列-Act-Assert and names 描述 expected behavior.

动手试一试

  • Code Diff

    Compare expected and 实际值 当单元测试失败.

  • JSON Formatter

    Pretty-print 数据结构你的 assertions compare.

常见错误

错误写法

测试多个 things in one 测试

正确做法

One 测试, one assertion 概念. 如果测试检查两者都返回值 and 边副作用, 拆分它 到 two named 测试.

错误写法

Depending on current date or random 值

正确做法

Inject clock or random 源所以测试 controls 值. 非-determinism 制作测试 flaky and erodes trust.

练习 单元测试

3 个练习

练习 单元测试

查阅不认识的术语

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

查看术语表

动手做项目

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

查看项目

解读错误信息

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

查看错误