← Back to Frontend, page 3

frontend-0049 · Medium mid

How do you test front-end code that calls an API without using the network, and which cases should you cover?

Replace the network edge with a controlled fake, such as a stubbed fetch or a mock service layer, and then test the success path, an HTTP error status, a network failure and the loading state. Mock as little as possible, so the code between the user action and the network is real.

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 fetch for 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 api object or a fetch function 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:

  1. Success: data is shown.
  2. Empty data: the empty state, not a blank page.
  3. HTTP error: fetch does not reject on 404 or 500. The code must check response.ok. A common bug is to call .json() on an error page.
  4. Network failure: fetch rejects with a TypeError. The user should see an error message and a way to retry.
  5. Slow response and loading state, and a canceled request when the user leaves.
  6. 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.

javascript
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.