Jest 是 Facebook 开源的一款 JS 单元测试框架,有以下能力:断言、 Mock 功能,快照测试、实时监控模式、覆盖度报告等。
断言是比较基础的测试能力,官方提供的expect覆盖了很多场景(https://jestjs.io/docs/en/expect),但业务中难免出现触发官方expect无法断言的场景,那么久需要我们对断言库进行扩充。
官方给出说明: https://jestjs.io/docs/en/expect#expectvalue,示例如下
expect.extend({
toBeWithinRange(received, floor, ceiling) {
const pass = received >= floor && received <= ceiling;
if (pass) {
return {
message: () =>
`expected ${received} not to be within range ${floor} - ${ceiling}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${received} to be within range ${floor} - ${ceiling}`,
pass: false,
};
}
},
});
test('numeric ranges', () => {
expect(100).toBeWithinRange(90, 110);
expect(101).not.toBeWithinRange(0, 100);
expect({apples: 6, bananas: 3}).toEqual({
apples: expect.toBeWithinRange(1, 10),
bananas: expect.not.toBeWithinRange(11, 20),
});
});