Skip to content

Matcher

一句话解释

matcher 是方法那个定义如何 compare 值 in assertion, e.g., toBe for equality, toContain for membership.

用大白话说

Matchers 是 vocabulary 的 assertions. 当你 编写 expect(值).toBe(5), toBe 部分是 matcher. 它定义 HOW comparison 是做.

Different matchers 检查不同 things:

  • toBe — strict equality (===)
  • toEqual — deep equality (for 对象/数组)
  • toContain — 检查如果数组/字符串包含值
  • toBeTruthy / toBeFalsy — 检查 truthiness
  • toThrow — 检查如果函数 throws
  • toMatch — regex matching

Choosing 正确 matcher 是重要. Using toBe for 对象检查引用 equality (通常错误); using toEqual 检查 deep equality (通常正确).

示例

javascript
expect(5).toBe(5);                    // strict equality
expect({a: 1}).toEqual({a: 1});        // deep equality
expect('hello').toMatch(/ell/);        // regex
expect([1,2,3]).toHaveLength(3);       // length

每个 matcher 检查值 in 不同方式.

相关术语

相关资源

相关课程

解读错误信息

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

查看错误

← 返回术语表