Reputation: 2275
At https://github.com/rancher-sandbox/rancher-desktop/blob/22f94cb2c3a8cd0734f2f4f505b10ee660e94041/pkg/rancher-desktop/backend/tests/k3sHelper.spec.ts#L194 we have a sequence of mocks for fetch
, structured like so:
jest.mocked(fetch).mockImplementationOnce((url) => {
// Fake fetching from a channel
}).mockImplementationOnce((url) => {
// Fake fetching release data
}).mockImplementationOnce((url) => {
// Fake hitting a 403
}).mockImplementationOnce((url) => {
// Fake getting the end of the data
}).mockImplementationOnce((url) => {
// Shouldn't call this one!
throw new Error(`Unexpected fetch call to ${ url }`);
});
// Do the thing ...
expect(fetch).toHaveBeenCalledTimes(4);
I added a new test, that runs immediately after the one I described,
with its own sequence of mocked fetches.
But the first call to fetch
hits the fifth mocked function in the
previous test.
We have a beforeEach
that we think clears the mocked fetch:
beforeEach(() => {
jest.mocked(fetch).mockClear();
});
If I add a fifth call to try { fetch('blah') } catch{}
in the first test, the second test runs as expected.
Currently the first test is the only test where fetch
is getting mocked.
So my question is, do we still need to ensure that all the mocked calls are actually hit before trying to write a new test that also mocks fetch
? The docs at https://jestjs.io/docs/mock-function-api only say what happens if you call a mocked function too many times, but there's no mention of what happens when you don't consume all the mocked implementations.
Upvotes: 0
Views: 24
Reputation: 2275
The solution is to change the call to mockClear
to in that beforeEach
to mockReset
. I'm dense, because the docs for mockReset
say:
Does everything that mockFn.mockClear() does, and also replaces the mock implementation with an empty function, returning undefined.
I suppose if I write 10,000 more jest tests one day I'll understand why I would not want mockClear
to clear the unused function mocks. But todaay I'm baffled....
Upvotes: 0