一、基本语法(匹配器matchers)
1.基础语法
test('two plus two is four', () => { expect(2 + 2).toBe(4); }); |
expect()返回被称作“expectation”的对象。toBe()被称作matcher。Jest会对两者进行比较并输出测试结果。
相应的,expect()和toBe()还可以调用被测的function
test('two plus two is four', () => { const add = 2+2; const value =4; expect(add).toBe(value); }); 12345 |
还可以用not.toBe():
expect(add).not.toBe(value); |
2.比较null,undefined,true,false
expect(n).toBeNull(); // 比较是否为null expect(n).toBeDefined(); // 比较是否为defined expect(n).not.toBeUndefined(); // 比较是否为undefined expect(n).not.toBeTruthy(); // 比较是否为true expect(n).toBeFalsy(); // 比较是否为false |
3.比较number
expect(value).toBe(4); expect(value).toEqual(4); expect(value).toBeGreaterThan(11); // value比较是否大于11 expect(value).toBeLessThan(11); // value比较是否小于11 expect(value).toBeGreaterThanOrEqual(11); // value比较是否大于等于11 expect(value).toBeLessThanOrEqual(11); // value比较是否小于等于11 expect(0.1 + 0.2).toBeCloseTo(0.3); // 浮点数比较 |
对于number,toBe()和toEqual()两者在大部分时候都是等价的
4.比较string
使用toMatch()方法
test('there is no I in team', () => { expect('team').not.toMatch(/I/); // 是否不包含I字符串(可以直接写字符串) }); test('but there is a "stop" in Christoph', () => { expect('Christoph').toMatch(/stop/); // 是否包含stop字符串(可以直接写字符串) }); |
5.比较Arrays,Set
使用toContain()方法
const shoppingList = [ 'diapers', 'kleenex', 'trash bags', 'paper towels', 'beer', ]; test('the shopping list', () => { expect(shoppingList).toContain('beer'); // 数组中包含beer expect(shoppingList).not.toContain('pork'); // 数组中不包含pork }); |
6.匹配引用类型
test('引用类型', () => { const a = {one: 1}; expect(a).toEqual({one: 1}); }); |
7.异常
const throwNewErrorFunc = () => { throw new Error('this is a new error') } test('toThrow', () => { expect(throwNewErrorFunc).toThrow() // 是否抛出异常 expect(throwNewErrorFunc).toThrow('this is a new error') // 是否抛出异常并且异常为'this is a new error' expect(throwNewErrorFunc).not.toThrow() // 是否不抛出异常 }) |
8.更多expect用法
请查询Jest官方文档。
二、测试覆盖率
生成测试覆盖率
// Jest 运行 npx jest --coverage |
// umi 运行 run test --coverage |
会在项目根目录生成coverage文件夹可以查看生成的测试用例覆盖率。
热重载测试用例
命令
npm run jest --watchAll |
A模式当有测试用例改变时会自动重新执行所有测试用例
请在文本框输入文字 |
默认为o模式。o 模式只会执行更改测试用例的文件
f模式只会对之前没有通过的测试用例测试。
t模式根据测试用例的名字匹配,只会执行匹配到的测试用例。(可以只写名字的部分可以过滤到)
p模式根据测试文件名匹配,只会执行匹配到的测试文件中的测试用例。
q退出测试监控。
Enter重新执行测试用例。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理