前端jest测试
常用匹配器
- toBe 判断测试的值是否精确匹配 expect(1 + 1).toBe(2);
- toEqual 对象、数组里面的 key/value 依次判断是否一致
- toMatch 正则匹配字符串
- not 测试相反的用例 expect(1+1).not.toBe(3)
布尔值匹配器
- toBeNull 只匹配 null
- toBeUndefined 只匹配 undefined
- toBeDefined 与 toBeUndefined 相反,等于 not.toBeUndefined
- toBeTruthy 匹配任何 expect 语句为真
- toBeFalsy 匹配任何 expect 语句为假
数字匹配器
- .toBeGreaterThan() - 大于
- .toBeGreaterThanOrEqual() 大于等于
- .toBeLessThan() - 小于
- .toBeLessThanOrEqual() - 小于等于
- .toBeCloseTo() - 浮点数比较
数组匹配器
- .toContain(item) - 判断数组是否包含特定子项
- .toContainEqual(item) - 判断数组中是否包含一个特定对象
对象匹配器
- .toMatchObject(object) - 判断一个对象嵌套的 key 下面的 value 类型
- .toHaveProperty(keyPath, value) - 判断在指定的 path 下是否有这个属性
自定义匹配器
- 使用expect.extend将自己的匹配器添加到Jest。自定义匹配器需要返回一个包含两个key 的对象
断言函数:
exspect(运行结果).toBe(期望的结果);
//常见断言方法
expect({a:1}).toBe({a:1})//判断两个对象是否相等
expect(1).not.toBe(2)//判断不等
expect({ a: 1, foo: { b: 2 } }).toEqual({ a: 1, foo: { b: 2 } })
expect(n).toBeNull(); //判断是否为null
expect(n).toBeUndefined(); //判断是否为undefined
expect(n).toBeDefined(); //判断结果与toBeUndefined相反
expect(n).toBeTruthy(); //判断结果为true
expect(n).toBeFalsy(); //判断结果为false
expect(value).toBeGreaterThan(3); //大于3
expect(value).toBeGreaterThanOrEqual(3.5); //大于等于3.5
expect(value).toBeLessThan(5); //小于5
expect(value).toBeLessThanOrEqual(4.5); //小于等于4.5
expect(value).toBeCloseTo(0.3); // 浮点数判断相等
expect('Christoph').toMatch(/stop/); //正则表达式判断
expect(['one','two']).toContain('one'); //不解释
参考文献