我有一个间谍在测试套件中的多个测试中被用于多个断言。
我该如何清除或重置该间谍,以便在每个测试中拦截的方法都被视为未被调用?
例如,如何使 '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
})
})
jest.restoreAllMocks();
! - ZorleQrestoreMocks: true
来自动调用restoreAllMocks()
,以便在每个测试后恢复所有mocks。个人而言,我从来没有让mocks在任何两个测试之间保持不变的理由,因此我喜欢在每个测试之间盲目地重置它们,而无需在afterEach()
块中编写它们作为清理项。 - user2490003jest.clearAllMocks();
。这对于将所有针对单个方法的测试分组到一个测试套件下,但希望断言不记住其先前值的情况非常有用。 - NadavafterEach(jest.clearAllMocks)
。 - trevorgk