一、基本语法(匹配器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 sh