jest.restoreAllMocks() for use with afterEach and beforeEach

Created on 21 Feb 2017  路  7Comments  路  Source: facebook/jest


Do you want to request a feature or report a bug?
Feature

What is the current behavior?
To restore a mock to it's original implementation, you need to add spy.mockRestore() within each test.

What is the desired behavior?

afterEach(() => {
  jest.restoreAllMocks();
});

Expect does this now: https://github.com/mjackson/expect#restorespies

Jasmine's spyOn behavior automatically does this between tests.

Most helpful comment

I just came across this issue and found out that jest.restoreAllMocks() is now implemented. Might help someone in the future :)

For more information, see: https://github.com/facebook/jest/pull/4045

All 7 comments

Have you tried jest.clearAllMocks?

const video = {
  play: function () {
    return true;
  }
};

describe('video', () => {
  afterEach(() => {
    // jest.clearAllMocks(); // Does not remove mockImplementation between tests

    // jest.restoreAllMocks(); // What I want to do.
  });

  test('plays video', () => {
    const spy = jest.spyOn(video, 'play').mockImplementation(() => {
      return 42;
    });
    const isPlaying = video.play();

    expect(spy).toHaveBeenCalled();
    expect(isPlaying).toBe(42);

    spy.mockRestore(); // What I have to do [to completely remove the spy].
  });

  test('plays video', () => {
    const isPlaying = video.play();

    expect(spy).toHaveBeenCalled();
    expect(isPlaying).toBe(true); // Fails without "mockRestore". isPlaying will be 42.
  });
});

I recommend setting up your spy and resetting it in beforeEach every time.

That makes sense for this simple example. But if there are several test with several spies, that would become cumbersome quickly. For now, handling them within each test seems like the best pattern available.

@cpojer is jest.restoreAllMocks() a planned feature?

I've been looking for this as well. Also, I have documented mockRestore which has not been documented in the API docs before. That might have been the source of all confusion although a function that does that with all mocks would be more than welcome.

I just came across this issue and found out that jest.restoreAllMocks() is now implemented. Might help someone in the future :)

For more information, see: https://github.com/facebook/jest/pull/4045

Was this page helpful?
0 / 5 - 0 ratings