乐闻世界logo
搜索文章和话题

Jest 中常用的断言方法有哪些?如何使用 expect 和匹配器?

2月21日 15:57

Jest 提供了丰富的断言方法,主要通过 expect() 函数配合匹配器(matchers)使用:

常用匹配器:

相等性匹配器:

  • toBe(value):严格相等(使用 ===
  • toEqual(value):深度相等(递归比较对象和数组)
  • toMatchObject(object):部分匹配对象属性
  • toStrictEqual(value):严格深度相等(包括 undefined 属性)

真值匹配器:

  • toBeNull():只匹配 null
  • toBeUndefined():只匹配 undefined
  • toBeDefined():非 undefined
  • toBeTruthy():真值(非 false、0、""、null、undefined、NaN)
  • toBeFalsy():假值

数字匹配器:

  • toBeGreaterThan(number):大于
  • toBeGreaterThanOrEqual(number):大于等于
  • toBeLessThan(number):小于
  • toBeLessThanOrEqual(number):小于等于
  • toBeCloseTo(number, precision):浮点数近似相等

字符串匹配器:

  • toMatch(regexp | string):匹配正则或字符串
  • toContain(item):包含元素

异步匹配器:

  • resolves:Promise 成功
  • rejects:Promise 失败

示例:

javascript
expect(2 + 2).toBe(4); expect({ name: 'John' }).toEqual({ name: 'John' }); expect(null).toBeNull(); expect(10).toBeGreaterThan(5); expect('hello').toMatch(/ell/);
标签:Jest