简介
Jest有以下的特点:
- 高速和沙盒。Jest以最大化性能并行化的测试运行。控制台消息都是缓冲并输出测试结果。沙盒测试文件和自动全局状态将为每个测试重置,因此测试代码间不会冲突。
- 内置代码覆盖率报告。使用--coverage可以创建代码覆盖报告。不需要其他额外的库。
- 无需配置。在使用create-react-app或者react-native init创建Native项目的时候,Jest已经配置好并可以使用了。
- 拥有功能强大的模拟库。
- 与Typescript一起使用
安装
安装jest依赖包
npm install --save-dev jest
新建一个sum.js文件,作为测试的示例:
function sum(a, b) {
return a + b;
}
module.exports = sum;
新建sum.test.js文件,写关于测试sum.js代码:
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
为了便于启动可以在package.json中配置命令:
{
"scripts": {
"test": "jest"
}
}
最后,执行命令:
npm run test
常用匹配器
匹配器是为了去测试输入输出的值是否符合预期。
普通匹配器
toBe()
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
toBe用的是JavaScript中的Object.is(),属于ES6中的特性,所以不能检测对象,如果要检测对象的值的话,需要用到toEqual。toEquel递归检查对象或者数组中的每个字段。
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
Truthiness
当需要区分undefined、null和false时:
- toBeNull只匹配null
- toBeUndefined只匹配undefined
- toBeDefine与toBeUndefined相反
- toBeTruthy匹配任何if语句为真
- toBeFalsy匹配任何if语句为假
数字匹配器
大多数的比较数字有等价的匹配器。
- 大于。toBeGreaterThan()
- 大于或者等于。toBeGreaterThanOrEqual()
- 小于。toBeLessThan()
- 小于或等于。toBeLessThanOrEqual()
- toBe和toEqual同样适用于数字
注意:对比两个浮点数是否相等的时候,使用toBeCloseTo而不是toEqual
例子如下:
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
如果使用toBe就会产生以下结果:
test('两个浮点数字相加', () => {
const value = 0.1 + 0.2;
<!-- expect(value).toBe(0.3); 这句会报错,因为浮点数有舍入误差 -->
expect(value).toBeCloseTo(0.3); // 这句可以运行
});
字符串
使用toMatch()测试字符串,传递的参数是正则表达式。
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
数组
如何检测数组中是否包含特定某一项?可以使用toContain()
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
test('(shopping list)里面有(diapers)', () => {
expect(shoppingList).toContain('beer');
});
网友评论