如何在Jest中重置或清除间谍?

2022-08-30 04:05:19

我有一个间谍,用于套件中多个测试的多个断言。

如何清除或重置间谍,以便在每次测试中都认为间谍拦截的方法未被调用?

例如,如何使断言为真?'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
  })
})

答案 1

感谢@sdgluck的答案,尽管我想在这个答案中添加一个答案,在我的情况下,我希望在每次测试后都有一个明确的状态,因为我对同一间谍进行了多次测试。因此,我没有在以前的测试中调用,而是将其移动到(或者您可以使用它)中,如下所示:mockClear()afterEach()beforeEach

afterEach(() => {    
  jest.clearAllMocks();
});

最后,我的测试正在像他们应该的那样工作,而没有从以前的测试中调用间谍。您也可以阅读他们的文档

备选案文2

如果您希望从全局级别执行此操作,也可以更新您的(或从jest.config.jspackage.json)

module.exports = {
  clearMocks: true,
  // ...
}

你可以阅读关于它的Jest文档


答案 2

开玩笑的间谍与模拟具有相同的API。模拟的文档在这里,并指定了一个方法:mockClear

重置存储在 mockFn.mock.callsmockFn.mock.instance 数组中的所有信息。

通常,当您想要在两个断言之间清理模拟的使用数据时,这很有用。

(强调我自己的)

因此,我们可以使用“重置”间谍。使用您的示例: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
  })
})

下面是 CodeSandbox 中的一个示例