Jest 入门二,常用expect方法
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);
});
还可以用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);
对于number,toBe()和toEqual()两者在大部分时候都是等价的
4.比较string
使用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/);
});
5.比较Arrays
使用toContain()
方法
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
test('the shopping list', () => {
expect(shoppingList).toContain('beer');
expect(shoppingList).not.toContain('pork');
});
6.更多expect用法
请查询Jest官方文档,链接官方文档