Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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   }) }) 
like image 212
sdgluck Avatar asked Nov 17 '18 10:11

sdgluck


People also ask

How do you spyOn a function in Jest?

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.

Is useful when you want to completely restore a mock back to its initial state?

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

How do you mock a Jest error?

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]"); }) .


1 Answers

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.

like image 187
ghiscoding Avatar answered Sep 30 '22 17:09

ghiscoding