簡體   English   中英

如何在 Jest 中重置或清除間諜?

[英]How to reset or clear a spy in Jest?

我有一個間諜,它在一個套件中的多個測試的多個斷言中使用。

如何清除或重置間諜,以便在每次測試中都認為間諜攔截的方法未被調用?

例如,如何使'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
  })
})

感謝@sdgluck 的回答,盡管我想補充一點,在我的情況下,我希望每次測試后都有一個清晰的狀態,因為我對同一個間諜進行了多次測試。 因此,我沒有在之前的測試中調用mockClear() ,而是將其移動到afterEach() (或者您可以將它與beforeEach一起beforeEach ),如下所示:

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

最后,我的測試工作正常,沒有從之前的測試中調用間諜。

Jest spies 與 mocks 具有相同的 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
  })
})

這是 CodeSandbox 中的一個示例

如果要恢復先前添加到 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();

進一步迭代@ghiscoding 的答案,您可以在 Jest 配置中指定clearMocks ,這相當於在每次測試之間調用jest.clearAllMocks()

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

請參閱此處的文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM