I am having an issue where the final case of the test.each block below seems to run with the real implementation of fetch() rather than the spy version.
describe('renders correct number of components', () => {
afterEach(() => {
jest.restoreAllMocks();
});
test.each([1,2,3,4])('renders %i components', async (componentCount) => {
jest.spyOn(window, 'fetch').mockResolvedValueOnce({
json: async () => ({ components: componentCount })
} as Response);
render(<ParentComponent />);
expect(await screen.findAllByText(/my component/i)).toHaveLength(componentCount);
});
});
The real implementation is:
const getSomeData = async (): Promise<ComponentData> => {
const res = await fetch('http://localhost:8080', { method: "GET" });
return res.json();
}
When I run the tests the first 3 pass fine, however the 4th throws a Error: connect ECONNREFUSED 127.0.0.1:8080. If I remove the 4th test the same happens with the 3rd.
If I change http://localhost:8080 to something like https://google.com I get a warning about a 'worker process failing to exit gracefully' but the tests all pass and there are no errors.
It seems to me that somehow the restored fetch() is making it through to the final test without being remocked by spyOn() but I can't for the life of me see how.