1. 最简单基础的实例

test('测试项描述', () => {
    expect(getHello()).toBe("hello")//测试getHello方法的返回值是否全等于"hello"
})

常用的匹配器

1. 相等判断

  • .toBe() 等同于全等于
  • .toEqual()
  • .not 与相等匹配器进行搭配, 表示不等于
    • .not.toBe()

2. 特殊值判断

  • .toBeNull()
  • .toBeDefined()
  • .toBeUndefined()
  • .toBeTruthy()
  • .toBeFalsy()

3. 数值比较

  • toBeCloseTo(), 因为计算机存储数字经常有精度丢失, 所以可以用该api判断是否在误差范围内
  • toBeLessThanOrEqual()
  • toBeLessThan()
  • toBeGreaterThanOrEqual()
  • toBeGreaterThan()

4. 字符串

  • .toMatch(正则表达式)

5. 普通对象

  • .toMatchObject()

6. 可迭代对象

  • .toContain()

7. 异常判断

  • .toThrow(Error对象 | 字符串 | 正则表达式)

8. 原文

Using Matchers · Jest 中文文档 | Jest 中文网