我是Jest的新手,我试着用它来测试函数是否被调用。我注意到mock.calls.length并不是为每个测试重置,而是在积累。我怎样才能在每次考试前达到0?我不希望我的下一个测试取决于以前的结果。
我知道Jest中有beforeEach -我应该使用它吗?重置mock.calls.length的最佳方法是什么?谢谢。
代码示例:
Sum.js:
import local from 'api/local';
export default {
addNumbers(a, b) {
if (a + b <= 10) {
local.getData();
}
return a + b;
},
};Sum.test.js
import sum from 'api/sum';
import local from 'api/local';
jest.mock('api/local');
// For current implementation, there is a difference
// if I put test 1 before test 2. I want it to be no difference
// test 1
test('should not to call local if sum is more than 10', () => {
expect(sum.addNumbers(5, 10)).toBe(15);
expect(local.getData.mock.calls.length).toBe(0);
});
// test 2
test('should call local if sum <= 10', () => {
expect(sum.addNumbers(1, 4)).toBe(5);
expect(local.getData.mock.calls.length).toBe(1);
});发布于 2017-12-14 16:32:49
我找到了一种处理它的方法:每次测试之后清除模拟函数:
要向Sum.test.js添加以下内容:
afterEach(() => {
local.getData.mockClear();
});如果要在每次测试后清除所有模拟函数,请使用clearAllMocks
afterEach(() => {
jest.clearAllMocks();
});发布于 2019-08-23 14:48:39
正如@AlexEfremov在评论中指出的那样。您可能希望在每次测试之后使用clearAllMocks:
afterEach(() => {
jest.clearAllMocks();
});记住,这将清除每个模拟函数的调用计数,但这可能是正确的方法。
发布于 2020-06-13 13:24:19
您可以将Jest配置为在每次测试后重置或清除模拟,方法是将这些参数中的一个放入jest.config.js中
module.exports = {
resetMocks: true,
};或
module.exports = {
clearMocks: true,
};以下是文件:
https://jestjs.io/docs/en/configuration#resetmocks-boolean
resetMocks布尔 缺省值: false 每次测试前自动重置模拟状态。相当于在每个测试之前调用jest.resetAllMocks()。这将导致任何模拟的假实现被删除,但不会恢复它们的初始实现。
https://jestjs.io/docs/configuration#clearmocks-boolean
clearMocks布尔 缺省值: false 在每次测试之前自动清除模拟调用、实例和结果。相当于在每个测试之前调用jest.clearAllMocks()。这并不会删除任何可能已经提供的模拟实现。
https://stackoverflow.com/questions/47812801
复制相似问题