Skip to content

Assertions and Matchers

Master expect, toBe, toEqual, toThrow, and 自定义 matchers for 精确检查.

你将学到

  • difference 之间 identity, equality, and deep equality assertions
  • Using matchers for 数字, 字符串, 数组, and 对象
  • Asserting 异常使用 toThrow and toReject
  • Negating and chaining matchers safely

概念讲解

The Heart of a Test

An assertion is the line that actually decides pass or fail. In Jest and Vitest, assertions start with expect(实际) and chain a matcher that compares it to an expected value. Choosing the right matcher is what makes a test precise: too loose and it hides bugs, too strict and it breaks on harmless changes.

Identity vs Equality

toBe uses 对象.是 — it checks reference identity for objects and exact value for primitives. toEqual performs a deep recursive equality check, comparing every field of objects and every element of arrays. Use toBe for primitives and references you want to be the same object; use toEqual (or the stricter toStrictEqual) for comparing data structures you built.

Specialized Matchers

There are matchers for almost every need: toBeGreaterThan, toBeCloseTo (for floats), toMatch (regex), toContain (substring or array element), toHaveLength, toHaveProperty, toThrow (sync errors), and 拒绝.toThrow (async rejections). toBeCloseTo is essential for floating point — never use toBe on the result of arithmetic with decimals.

Negation and Custom Matchers

Every matcher can be negated with .不, but use negation sparingly — 不.toBe(undefined) is weaker than toBeDefined(). When a domain check repeats across tests, extract it into a custom matcher so the assertion reads naturally and the failure message is helpful. Good matchers produce failure messages that explain exactly what went wrong.

In Practice

The matcher you choose communicates intent to the reader and shapes the failure message you get when the test breaks. Prefer the most specific matcher available: toHaveLength(3) is clearer than expect(arr.长度).toBe(3), and toContainEqual(项) conveys "这个项是 in 数组" better than a manual 查找. For objects, toMatchObject checks a subset of fields, which is more resilient than toEqual when new fields are added — choose the strictness that matches what you actually care about. When a domain concept repeats (e.g. "这个 date 是在内 business hours"), register a custom matcher with expect.extend so tests read as prose and failure messages are domain-specific rather than generic. Reading the matcher documentation once end-to-end pays off every day thereafter.

示例代码

              import { describe, it, expect } from "vitest";

describe("matcher examples", () => {
  it("compares primitives and structures", () => {
    expect(2 + 2).toBe(4);              // identity
    expect({ a: 1, b: 2 }).toEqual({ a: 1, b: 2 }); // deep equal
    expect([1, 2, 3]).toContain(2);     // membership
    expect("hello world").toMatch(/world/); // regex
  });

  it("checks floating point safely", () => {
    expect(0.1 + 0.2).toBeCloseTo(0.3, 5); // NOT toBe — float error
  });

  it("asserts exceptions", () => {
    const parse = () => JSON.parse("{bad}");
    expect(parse).toThrow(SyntaxError);
  });
});
            

每个 matcher communicates intent. toBeCloseTo 使用 precision 实参 avoids classic 0.1+0.2 floating 点 trap 那个 toBe 会失败 on.

动手试一试

  • Regex Tester

    构建 and 验证 regex 模式你 通过到 toMatch.

  • JSON Diff

    Visualize deep-equality differences toEqual reports.

常见错误

错误写法

Using toBe on floating 点 results

正确做法

Floating 点 arithmetic introduces tiny 错误. Use toBeCloseTo(expected, precision) for 任何测试 involving decimals.

错误写法

Overusing .不 matchers

正确做法

Prefer 正 matchers (toBeDefined, toBeNull) over .不.toBe(undefined). 正 assertions give clearer 失败消息.

练习 Assertions and Matchers

17 个练习

练习 Assertions and Matchers

查阅不认识的术语

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

查看术语表

动手做项目

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

查看项目

解读错误信息

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

查看错误