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 }) })
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
mockClear() does, and also removes any mocked return values or implementations. This is useful when you want to completely reset a mock back to its initial state. (Note that resetting a spy will result in a function with no return value).
To properly make mock throw an error in Jest, we call the mockImplementation method and throw an error in the callback we call the method with. it("should throw error if email not found", async () => { callMethod . mockImplementation(() => { throw new Error("User not found [403]"); }) .
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With