Ale*_*mov 49 javascript unit-testing jestjs
我是Jest的新手,我正在尝试使用它来测试函数是否被调用.我注意到mock.calls.length没有为每个测试重置但是累积.如何在每次测试前将其设为0?我不希望我的下一次测试取决于之前的结果.
我知道在Jest之前有一个 - 我应该使用它吗?重置mock.calls.length的最佳方法是什么?谢谢.
一个代码示例:
Sum.js:
import local from 'api/local';
export default {
addNumbers(a, b) {
if (a + b <= 10) {
local.getData();
}
return a + b;
},
};
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
Ale*_*mov 50
我发现处理它的一种方法:在每次测试后清除模拟函数:
要添加到Sum.test.js:
afterEach(() => {
local.getData.mockClear();
});
Run Code Online (Sandbox Code Playgroud)
小智 18
jest.clearAllMocks()实际上并没有为我清除所有的嘲笑。
afterEach(() => {
jest.restoreAllMocks();
});
Run Code Online (Sandbox Code Playgroud)
帮我终于清除了笑话中的间谍
And*_*gin 17
您可以将 Jest 配置为在每次测试后重置模拟,方法是将其放入您的jest.config.js:
module.exports = {
resetMocks: true,
};
Run Code Online (Sandbox Code Playgroud)
这是此配置参数的文档:https : //jestjs.io/docs/en/configuration#resetmocks-boolean
resetMocks [布尔值]
默认值:假
每次测试前自动重置模拟状态。相当于在每次测试之前调用 jest.resetAllMocks()。这将导致任何模拟删除其虚假实现,但不会恢复其初始实现。
正如@AlexEfremov在评论中指出的那样。您可能希望clearAllMocks在每次测试后使用:
afterEach(() => {
jest.clearAllMocks();
});
Run Code Online (Sandbox Code Playgroud)
请记住,这将清除您拥有的每个模拟函数的调用计数,但这可能是正确的方法。
| 归档时间: |
|
| 查看次数: |
18898 次 |
| 最近记录: |