Jest 提供了丰富的断言方法,主要通过 expect() 函数配合匹配器(matchers)使用:
常用匹配器:
相等性匹配器:
toBe(value):严格相等(使用===)toEqual(value):深度相等(递归比较对象和数组)toMatchObject(object):部分匹配对象属性toStrictEqual(value):严格深度相等(包括 undefined 属性)
真值匹配器:
toBeNull():只匹配 nulltoBeUndefined():只匹配 undefinedtoBeDefined():非 undefinedtoBeTruthy():真值(非 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 失败
示例:
javascriptexpect(2 + 2).toBe(4); expect({ name: 'John' }).toEqual({ name: 'John' }); expect(null).toBeNull(); expect(10).toBeGreaterThan(5); expect('hello').toMatch(/ell/);