Jest测试之匹配器
运行Jest
- 安装jest
- yarn安装1 yarn add --dev jest 
- npm 安装1 npm install --save-dev jest 
- 添加运行脚本
在package.json中添加运行脚本创建测试文件名字的格式1 
 2
 3"scripts": { 
 "test":"jest --watchAll"
 }*.test.js,比如:index.test.js
toBe
toBe选择器是严格匹配的,对象的引用地址不同是会报错的。
- 简单的例子1 
 2
 3test('toBe 简单的例子', () => { 
 expect(1+1).toBe(2);
 });
- 使用对象时
 错误例子正确的例子1 
 2
 3
 4test('toBe 对象的错误例子', () => { 
 let obj = { a: 1 }
 expect(obj).toBe({ a: 1 }); // 报错,因为引用地址不一样
 });1 
 2
 3
 4
 5test('toBe 对象的正确例子', () => { 
 let obj = { a: 1 };
 let newObj = obj;
 expect(obj).toBe(newObj);
 });
toEqual
和toBe类似,但不同的是对于对象的判断处理。toEqual不会要求对象的引用地址不一样。
| 1 | test('toEqual', () => { | 
toBeNull
测试是否为null
| 1 | test('toBeNull', () => { | 
toBeUndefined
测试是否为undefined
| 1 | test('toBeUndefined', () => { | 
toBeTruthy
测试是否为true
| 1 | test('toBeTruthy', () => { | 
toBeFalsy
测试是否为false
| 1 | test('toBeFalsy', () => { | 
toHaveBeenCalled
函数是否被调用
| 1 | function drinkAll(callback, drink) { | 
toHaveBeenCalled
函数是否被调用的次数
| 1 | function drinkAll(callback, drink) { | 
toHaveBeenCalledWith
函数被调用时的所有参数
| 1 | function drinkAll(callback, drink) { | 
数字相关的匹配器
- toBeGreaterThan(number | bigint) 
 等价符号- >- 1 
 2
 3- test('toBeGreaterThan', () => { 
 expect(1).toBeGreaterThan(0); // 通过
 });
- toBeGreaterThanOrEqual(number | bigint) 
 等价符号- >=- 1 
 2
 3
 4- test('toBeGreaterThanOrEqual', () => { 
 expect(1).toBeGreaterThanOrEqual(1); // 通过
 expect(1).toBeGreaterThanOrEqual(0); // 通过
 });
- toBeLessThan(number | bigint) 
 等价符号- <- 1 
 2
 3- test('toBeLessThan', () => { 
 expect(1).toBeLessThan(2); // 通过
 });
- toBeLessThanOrEqual(number | bigint) 
 等价符号- <=- 1 
 2
 3
 4- test('toBeLessThanOrEqual', () => { 
 expect(1).toBeLessThanOrEqual(2); // 通过
 expect(1).toBeLessThanOrEqual(1); // 通过
 });
toContain(item)
测试是否存在数组中,相当于 ===
| 1 | test('toContain', () => { | 
toContainEqual(item)
当要测试数组中的对象是否存在时,需要用到toContainEqual
| 1 | test('toContainEqual', () => { | 
参考Jest官方文档
相关博客
  - 
        2021-03-17
- 
        2020-05-28
- 
        2022-03-15
- 
        2020-08-02