Javascript 如何重置或清除开玩笑的间谍?
我有一个间谍,在一个套件的多个测试中用于多个断言 如何清除或重置spy,以便在每次测试中都认为spy拦截的方法未被调用 例如,如何使Javascript 如何重置或清除开玩笑的间谍?,javascript,testing,jestjs,Javascript,Testing,Jestjs,我有一个间谍,在一个套件的多个测试中用于多个断言 如何清除或重置spy,以便在每次测试中都认为spy拦截的方法未被调用 例如,如何使“不运行方法”中的断言为真 const methods = { run: () => {} } const spy = jest.spyOn(methods, 'run') describe('spy', () => { it('runs method', () => { methods.run() expect(spy
“不运行方法”
中的断言为真
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
})
})
玩笑间谍和模拟间谍有相同的API。模拟的文档是并指定了一种方法
mockClear
,该方法:
重置存储在和数组中的所有信息
当您想清理两个断言之间的模拟使用数据时,这通常很有用
(强调我自己)
因此,我们可以使用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
})
})
.感谢@sdgluck给出的答案,不过我想补充一点,在我的情况下,我希望在每次测试后都有一个清晰的状态,因为我有多个测试使用同一间谍。因此,在前面的测试中,我没有调用
mockClear()
,而是将其移动到afterEach()
(或者可以将其与beforeach
一起使用),如下所示:
最后,我的测试工作正常,不会从以前的测试调用spy。进一步迭代@Ghicoding的答案,您可以在Jest配置中指定
clearMocks
,这相当于在每个测试之间调用Jest.clearAllMocks()
:
{
...
clearMocks: true,
...
}
请参阅文档。如果要恢复以前添加到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();
可能要更新此。到目前为止,使用Jasmine~2.8.6和jest 24.0.9是不正确的<代码>属性“mockClear”在类型“Spy”上不存在。@Bardicer此方法在最新的Jest中仍然有效,并且根据Jest文档是正确的。请看我在答案末尾的链接,它演示了如何在CodeSandbox中工作……那么。。。我想我只是想让它在玩笑开始的那天起作用。这不是第一次一个库决定变得困难,不能像预期的那样工作代码>如果要将模拟函数还原回其原始实现!您还可以将
restoreMocks:true
添加到Jest配置中,以便在每次测试后自动调用restoreAllMocks()
。就我个人而言,我没有任何理由让mock在任何两个测试之间持续存在,因此我喜欢在每个测试之间盲目地重置它们,而不必将它们作为清理项写入afterEach()
块。
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();