I'm using fetch-mock
(v.9.11.0) with React Testing Library to test a login form component, and as soon as I have more than 2 unit tests that have a mocked fetch response I start getting ECONNREFUSED
errors, and my tests fail with a Network Error
message.
An example of one of my unit tests (i18nConfigOptions
is declared at the start of the file):
it('should produce an error if something unexpected occurs (with return body)', async () => {
await i18n
.use(initReactI18next)
.init(i18nConfigOptions).then(async () => {
render(
<BrowserRouter>
<LoginForm />
</BrowserRouter>,
);
fetchMock.postOnce('/login', {
status: 404,
body: {
error: {
message: 'An error',
},
},
}, {
overwriteRoutes: true,
});
const inputs = screen.getAllByTestId('loginform_input');
userEvent.type(inputs[0], 'test@test.com');
userEvent.type(inputs[1], 'incorrectPassword');
userEvent.click(screen.getByRole('button'));
// wait for the error message to appear on screen
await waitFor(() => screen.findByTestId('loginform_error'));
expect(screen.getByTestId('loginform_error').textContent).toBe('An error');
fetchMock.reset();
});
});
I don't think that this is a setup/teardown issue as I'm declaring the fetchMock
object individually, and making sure to rest it after each test.
I should probably also mention that these errors start occurring from the first test if I set the delay
parameter in the fetchMock
options to anything other than 0, which could point to a wider issue.
Perhaps the strangest thing of all is that I see the errors on my M1 MacBook Pro, but not my Intel-based MacBook Pro from 2019. Could this be an M1 issue? Maybe the tests are executing too quickly on the M1? Splitting the tests into separate files also prevents the error from occurring, and all tests still pass.
Something odd is evidently happening, and it's got me stumped. Any advice gratefully received!