0

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);
  });
});

  • Why _are_ you spying on what's already a mock? – jonrsharpe Sep 28 '21 at 21:35
  • @jonrsharpe I wanted to change the return value of specific mock function inside each test to test different scenarios. I guess it's fine to change mockReturnValue in each test, but then I guess method1 shouldn't be a jest.fn() from the start? I've used jest.fn() so that I can get to calls of method1 and check call arguments without having to create extra spies just for checking that. – Michał Terczyński SM Oct 03 '21 at 20:09

1 Answers1

0

To clear spies from mock functions in Jest, we can use the jest.clearAllMocks() command.

imekinox
  • 819
  • 1
  • 7
  • 10