Full answer
Real network calls make tests slow, flaky and dependent on data. The fix is to control the edge of your code that talks to the network.
Options:
- Stub
fetchfor the test. Simple and good for small functions. A runner's mock helper can restore the original after each test. - Inject the dependency. Pass an
apiobject or afetchfunction into the code, and give the test a fake. - Intercept requests at the network level with a tool such as Mock Service Worker (MSW). The code under test calls the real
fetch, and the interceptor answers. This keeps the tests closer to production code, and the same handlers can serve in development and in the browser tests. - Use a real test backend only in a few end-to-end tests.
Cases that deserve a test, since users meet all of them:
- Success: data is shown.
- Empty data: the empty state, not a blank page.
- HTTP error:
fetchdoes not reject on 404 or 500. The code must checkresponse.ok. A common bug is to call.json()on an error page. - Network failure:
fetchrejects with aTypeError. The user should see an error message and a way to retry. - Slow response and loading state, and a canceled request when the user leaves.
- Race conditions: an old response arriving after a newer request.
Practical rules: reset mocks between tests, assert on what the user sees and on the request that was made (URL, method, body), and never let a test pass silently because an assertion sits in a callback that never ran. Return or await the promise.
The snippet tests a small loader with the Node test runner. It covers success, a 404, and a network failure, and checks that the request URL was correct.
import test, { mock } from 'node:test';
import assert from 'node:assert/strict';
async function loadCourses() {
const res = await fetch('/api/courses');
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
test('returns the list on success', async () => {
const fake = mock.method(globalThis, 'fetch', async () => new Response(JSON.stringify(['HTML']), { status: 200 }));
assert.deepEqual(await loadCourses(), ['HTML']);
assert.equal(fake.mock.calls[0].arguments[0], '/api/courses');
fake.mock.restore();
});
test('throws a clear error on HTTP 404', async () => {
mock.method(globalThis, 'fetch', async () => new Response('missing', { status: 404 }));
await assert.rejects(loadCourses(), /Request failed: 404/);
mock.restoreAll();
});
test('rejects when the network fails', async () => {
mock.method(globalThis, 'fetch', async () => { throw new TypeError('Failed to fetch'); });
await assert.rejects(loadCourses(), /Failed to fetch/);
mock.restoreAll();
});Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Run with the Node test runner (node --test). Three tests passed in two runs. MSW and a real component were not used.
Key points
- Control the network edge. Do not hit real servers in unit or integration tests.
- Options: stub fetch, inject a fake, or intercept requests with a tool such as MSW.
- Test success, empty, HTTP error, network failure and loading.
- fetch does not reject on 404 or 500. Check response.ok.
- Reset mocks and await every promise.
Common mistakes
- Mocking so much that the test checks only the mock.
- Forgetting the HTTP error case because fetch did not throw.
- Not awaiting the async code, so the test passes before the assertion runs.
- Sharing mock state between tests.
Follow-ups
- What does MSW do differently from stubbing fetch?
- How would you test that a stale response is ignored?
- How do you test a retry button?
Tips
- List the cases, not only the tool.
- Mention response.ok, since it is the classic trap.