How to clear spies from mock functions in Jest? jest.restoreAllMocks()
works perfectly fine if original function isn't a jest.fn()
. How to correctly clear all spies from jest.fn()
? This question might be a duplicate of How to change mock implementation on a per single test basis [Jestjs] although my question describes a bit simpler scenario where multiple modules are not involved.
describe('Mock', () => {
const mock = {
method1: jest.fn().mockReturnValue(false),
};
afterEach(() => {
// none of these clear the spy
jest.clearAllMocks();
jest.resetAllMocks();
jest.restoreAllMocks();
});
it('returns false by default', () => {
expect(mock.method1()).toEqual(false);
});
it('changes return value after applying spy implementation', () => {
jest.spyOn(mock, 'method1').mockReturnValue(true);
expect(mock.method1()).toEqual(true);
});
// this test fails
it('resets to original value after each test', () => {
expect(mock.method1()).toEqual(false);
});
});