6

I'm using jest 4.2.4 with my React 16.13.0 application. I have set up this type of mock ...

  jest.spyOn(ReduxFirebase, "getFirebase").mockReturnValue({
    firestore: jest.fn(() => ({ collection: jest.fn(() => collection) })),
  });

How do I clear this between tests? I tried this ...

describe("User", () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

but it is not working. Setting this later in the test suite

  jest.spyOn(ReduxFirebase, "getFirebase").mockReturnValue({
    firestore: jest.fn(() => ({ collection: jest.fn(() => collection2) })),
  });

does not take (the original spy is still in place.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Dave
  • 15,639
  • 133
  • 442
  • 830
  • The question isn't specific enough. How do you know that it doesn't work? What do you expect and what do you get? – Estus Flask Apr 30 '20 at 09:57

2 Answers2

6

This should do the job :

const getFirebaseMock = jest.spyOn(ReduxFirebase, "getFirebase").mockReturnValue({
  firestore: jest.fn(() => ({ collection: jest.fn(() => collection) })),
});
getFirebaseMock.mockRestore();
  • Thanks. Currently I'm not savinga reference to that anywhere. Is there any way I can start out the test suite (or an individual test) with a clean state without saving any state from anything before? – Dave Apr 29 '20 at 17:19
  • I'm not sure you can if `clearAllMocks` does not work. You'll probably need to define your spy before the test suite, mock implementation in each test and use `afterEach(getFirebaseMock.mockRestore)` –  Apr 29 '20 at 17:35
  • Apart from this case you can't clear your mock to retrieve the originally state. Besides an issue has been opened, check here https://github.com/facebook/jest/issues/7136 – jonn Dec 29 '20 at 19:46
5

You can try

afterEach(() => {
    jest.restoreAllMocks();
  });
Dani Alcalà
  • 212
  • 3
  • 5