sdg*_*uck 21 javascript testing jestjs
我有一个间谍,它在一个套件的多个测试中的多个断言中使用。
如何清除或重置间谍,以便在每次测试中都认为间谍未拦截间谍方法?
例如,如何使断言'does not run method'为真?
const methods = {
run: () => {}
}
const spy = jest.spyOn(methods, 'run')
describe('spy', () => {
it('runs method', () => {
methods.run()
expect(spy).toHaveBeenCalled() //=> true
})
it('does not run method', () => {
// how to make this true?
expect(spy).not.toHaveBeenCalled() //=> false
})
})
Run Code Online (Sandbox Code Playgroud)
sdg*_*uck 22
玩笑间谍具有与模拟相同的API。模拟文档在这里,并指定一种方法mockClear:
重置存储在
mockFn.mock.calls和mockFn.mock.instances数组中的所有信息。当您要清理两个断言之间的模拟使用数据时,这通常很有用。
(强调我自己)
因此我们可以mockClear用来“重置”间谍。使用您的示例:
const methods = {
run: () => {}
}
const spy = jest.spyOn(methods, 'run')
describe('spy', () => {
it('runs method', () => {
methods.run()
expect(spy).toHaveBeenCalled() //=> true
/* clean up the spy so future assertions
are unaffected by invocations of the method
in this test */
spy.mockClear()
})
it('does not run method', () => {
expect(spy).not.toHaveBeenCalled() //=> true
})
})
Run Code Online (Sandbox Code Playgroud)
ghi*_*ing 19
感谢@sdgluck给出的答案,尽管我想在这个答案中补充一点,在我的情况下,我希望每次测试后都有清晰的状态,因为我有多个使用相同间谍的测试。因此mockClear(),我没有afterEach()像以前的测试中那样调用,而是将其移至类似的位置:
afterEach(() => {
jest.clearAllMocks();
});
Run Code Online (Sandbox Code Playgroud)
最后,我的测试正在按应有的方式工作,而无需从先前的测试中调用间谍。
Dan*_*tas 13
如果要恢复先前添加到 spy 的方法的原始行为,可以使用 mockRestore 方法。
看看下面的例子:
class MyClass {
get myBooleanMethod(): boolean {
return true;
}
}
const myObject = new MyClass();
const mockMyBooleanMethod = jest.spyOn(myObject, 'myBooleanMethod', 'get');
// mock myBooleanMethod to return false
mockMyBooleanMethod.mockReturnValue(false);
// restore myBooleanMethod to its original behavior
mockMyBooleanMethod.mockRestore();
Run Code Online (Sandbox Code Playgroud)
Jam*_*win 12
进一步迭代@ghiscoding 的答案,您可以clearMocks在 Jest 配置中指定,这相当于jest.clearAllMocks()在每个测试之间调用:
{
...
clearMocks: true,
...
}
Run Code Online (Sandbox Code Playgroud)
请参阅此处的文档。
| 归档时间: |
|
| 查看次数: |
10009 次 |
| 最近记录: |