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

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.callsmockFn.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)

  • 可能想更新这个。截至今天,使用 Jasmine ~2.8.6 和 jest 24.0.9,这是不正确的。`类型'Spy'上不存在属性'mockClear'。` (5认同)
  • ...那么...我想我只是想在开玩笑的那天让它发挥作用。这并不是图书馆第一次决定变得困难并且不能按预期工作。 (2认同)

ghi*_*ing 19

感谢@sdgluck给出的答案,尽管我想在这个答案中补充一点,在我的情况下,我希望每次测试后都有清晰的状态,因为我有多个使用相同间谍的测试。因此mockClear(),我没有afterEach()像以前的测试中那样调用,而是将其移至类似的位置:

afterEach(() => {    
  jest.clearAllMocks();
});
Run Code Online (Sandbox Code Playgroud)

最后,我的测试正在按应有的方式工作,而无需从先前的测试中调用间谍。

  • 如果您想将模拟函数恢复为其原始实现,还有“jest.restoreAllMocks();”! (31认同)
  • 您还可以将 `restoreMocks: true` 添加到您的 Jest 配置中,以便在每次测试后自动调用 `restoreAllMocks()`。就我个人而言,我没有理由让模拟在任何两个测试之间持续存在,所以我喜欢在每个测试之间盲目地重置它们,而不必将其作为清理项写在“afterEach()”块中。 (6认同)

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)

请参阅此处的文档。