(四)Jest匹配器
学习jest匹配器之前先要修改配置文件,打开package.json文件:
"scripts": {
"test": "jest --watchAll",
"coverage": "jest --coverage"
},
让Jest监听所有测试(test.js)文件的变化,如果有变化就自动跑测试用例。
一、比较结果匹配器
1> toBe
test('测试加法 3+7', () => {
toBe为匹配器 matchers
expect(10).toBe(10);
//toBe相当于js中的 object.is ===
});
2> toEqual
test('测试加法 3+7', () => {
//toEqual为匹配器
const a = { one : 1 };
expect(a).toEqual({ one : 1 });
});
3> toBeNull
test('测试加法 3+7', () => {
const a = null;
expect(a).toBeNull();
});
二、真假有关的匹配器
1> toBeUndefined
2> toBeDEfined
3> toBeTruthy
4> toBeFalsy
三、数字相关匹配器
1> toBeGreaterThan
test('toBeGreaterThan', () => {
const count = 10;
expect(count).toBeGreaterThan(3);
});
2> toBeLessThan
test('toBeLessThan', () => {
const count = 10;
expect(count).toBeLessThan(13);
});
3> toBeGreaterThanOrEqual
test('toBeGreaterThanOrEqual',()=>{
const a= 5
expect(a).toBeGreaterThanOrEqual(5)
})
4> toBeCloseTo 主要用于带有浮点小数时使用
test('toBeCloseTo',()=>{
const a= 5.1
expect(a).toBeCloseTo(5.1)
})
四、String匹配器
1> toMatch
test('toMatch', () => {
const str = 'http://www.dell-lee.com';
expect(str).toMatch(/dell-lee/);
});
2> toContain 主要用于数组
test('toContain', () => {
const arr = ['dell','lee','imooc'];
const data = new Set(arr);
expect(data).toContain('dell');
});
3> toThrow 抛出异常
const throwNewErrorFunc = () => {
throw new Error('this is a new error');
}
test('toThrow', () => {
// expect(throwNewErrorFunc).not.toThrow('this is a new error');
expect(throwNewErrorFunc).not.toThrow(/this is a new error/);
});
//两处的error信息要一致,否则报错