javascripttestingjestjs

How to reset or clear a spy in Jest?


I have a spy that is used in multiple assertions across multiple tests in a suite.

How do I clear or reset the spy so that in each test the method that the spy intercepts is considered not to have been invoked?

For example, how to make the assertion in 'does not run method' be 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
  })
})

Solution

  • Thanks to @sdgluck for the answer, though I would like to add to this answer that in my case, I wanted a clear state after each tests since I have multiple tests with the same spy. So instead of calling the mockClear() in previous test(s), I moved it into the afterEach() (or you can use it with beforeEach) like so:

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

    And finally, my tests are working like they should without the spy being called from previous test. You can also read their documentation about this feature.

    Option 2

    If you wish to do it at a global level, you could also update your jest.config.js (or from package.json) which will clear the spy on each tests but without having to call jest.clearAllMocks() in every tests.

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

    You can read Jest documentation about this feature.