Understanding state in jest tests that use spyOn

jest.spyOn() returns a jest mock function and you want to store the returned mock function in a variable so that you can make assertions.

If you don’t store the mock function returned by jest.mock(), then how will you make assertions? All the methods, provided by jest, that can be called on a mock function, can’t be called without having a reference to the mock function.

If you just want to mock a return value and not make any assertions on the mocked function, then you don’t need to save the reference. Generally, when you mock a function, you want to make assertions like how many times it was called, what arguments it was called with, etc.

Will the “someMethod” function, part of “someObject”, not be retained as a mock across other tests from other files?

someMethod will only be mocked in the test file where you mock it. It won’t affect the other test files.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top