React Test TypeError: Network request failed

If you get this error message during a test, it’s because jest isn’t making the network call. You need to make a mock for fetch(), replacing the network call with a fake.

Since I’m a rookie at React, this is a total rookie error.

There’s a solution here: Asynchronous API testing in React by Will Mitchell.

I found a simpler way to do it, though. It was in this post Visual unit testing with react-storybook and fetch-mock by Edoardo Colombo. That looked involved, and I’m not at that level quite yet, but there was a tip in there: use the mock called fetch-mock. fetch-mock makes one-liner mocks for the fetch().

To install:

yarn add --dev fetch-mock

Here’s the source code for the example test, with a couple things mocked:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import fetchMock from 'fetch-mock';

fetchMock.get('end:/legacy-sitemap/api/sitemap', [{"url":"d\/content\/unix-text-file-database.html","title":"Unix Text File Database "},{"url":"d\/content\/file-sync-and-share-and-file-server-terminology-clashes.html","title":"File Sync and Share and File Server Terminology Clashes "}]);
fetchMock.post('end:/legacy-sitemap/api/move', {});

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

That tells fetch-mock to look for specific urls that end with a string, and then return some sample data. I copied the sample from actual data.

The right way to use the mock is within a test case, where you mock a response, and then test that your component does the right thing for that response. You can mock data and different HTTP status codes. For simpler situations, mocking successful responses should be enough.

Leave a Reply