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

dw1jzc5e  于 8个月前  发布在  Jest
关注(0)|答案(5)|浏览(85)

我有一个间谍,用于跨套件中的多个测试的多个Assert。
我如何清除或重置间谍,以便在每个测试中,间谍拦截的方法被认为没有被调用?
例如,如何使'does not run method'中的Assert为true?

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
  })
})

字符串

hiz5n14c

hiz5n14c1#

感谢@sdgluck的回答,虽然我想补充这个答案,在我的情况下,我想在每次测试后都有一个清晰的状态,因为我有多个测试使用相同的间谍。所以,而不是在以前的测试中调用mockClear(),我把它移动到afterEach()(或者你可以使用它与beforeEach)如下所示:

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

字符串
最后,我的测试工作正常,没有从以前的测试调用间谍。

选项二

如果您希望从全局级别执行此操作,则还可以更新jest.config.js(或从package.json

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


你可以阅读Jest文档

zi8p0yeb

zi8p0yeb2#

Jest spies与mock有相同的API。mock的文档是here,并指定了一个方法mockClear,该方法:
重置存储在mockFn.mock.callsmockFn.mock.instances阵列中的所有信息。
当您想要清除两个Assert之间的mock使用数据时,这通常很有用。

  • (强调我自己)*

因此,我们可以使用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
  })
})

字符串
Here is an example in CodeSandbox的一个。

c3frrgcw

c3frrgcw3#

如果您想恢复以前添加到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();

字符串

w9apscun

w9apscun4#

进一步迭代@ghiscoding的答案,您可以在Jest配置中指定clearMocks,这相当于在每个测试之间调用jest.clearAllMocks()

{
...
    clearMocks: true,
...
}

字符串
看这里的docs。

y4ekin9u

y4ekin9u5#

编辑:在jest.jm.js中添加resetMocks -而不是clearMocks,因为这不会删除测试之间的任何mock实现(即resetMocks是更谨慎的选择,它会删除测试之间的实现-在我看来,考虑到每个测试都应该是隔离的,这是正确的做法)。
参考:https://jestjs.io/docs/configuration#resetmocks-boolean

{
...
    resetMocks: true,
...
}

字符串
此外,您还可以在beforeEachafterEach中调用jest.resetAllMocks()

相关问题