wheresrhys / fetch-mock-jest

Jest wrapper for fetch-mock, a comprehensive stub for fetch
http://www.wheresrhys.co.uk/fetch-mock/
MIT License
60 stars 11 forks source link

`fetchMock.mock.calls` never updates (possibly jest 26) #26

Open green-arrow opened 3 years ago

green-arrow commented 3 years ago

After upgrading our codebase to jest 26 and this library to 1.5.1, our tests that used the .toHaveBeenCalled assertions stopped working. It appears that the .mock property is never updated with the calls to the spy.

I tried digging into the code a bit, and it seems like this wrapper does the Object.assign(jestifiedInstance.mock, spy.mock) only once, so those aren't kept in sync. Unfortunately fetchMock.mock is also a method, so we can't just assign jestifiedInstance.mock = spy.mock.

I tinkered around with the code locally and got something working by handling the fetchHandler and mock inside the proxy. It seems to run on our codebase without issue. I'd be happy to spin up a PR if you're interested!

wheresrhys commented 3 years ago

Yep that would be good - thanks

alexpovh commented 3 years ago

Same issue here, happens only when clearMocks is set to true in jest configuration.

SpencerKaiser commented 2 years ago

Just to add onto the content above, I'm having the exact same issue... I have clearMocks enabled in my Jest config and I spent the last two hours debugging this:

// ✅
expect(fetchMock).toHaveLastFetched(
  onboardingEndpoint,
  expect.objectContaining({
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    body: JSON.stringify({ name }),
  }),
);

// ❌
expect(fetch).toHaveBeenCalled();

// ✅
expect(fetchMock).toHaveLastFetched(onboardingEndpoint);

// ❌
expect(fetchMock).toHaveLastFetched(expect.anything());

So yea... that was quite rough 😅 @wheresrhys do you think that last example is related? If not or if you aren't sure, I'll open up a new issue for it.

th3fallen commented 2 years ago

same here, but removing clearMocks in our config is a no go as our tests go BANANAS