Mock network requests in front-end tests

8 steps · about 1 h 50 min · Intermediate

  1. Why mock at the network boundary (doc, Mock Service Worker, 10 min)

    Understand the benefit of intercepting real requests instead of stubbing fetch or your data module by hand.

  2. Write your first request handlers (tutorial, Mock Service Worker, 20 min)

    Describe the API your component calls and return realistic responses from one handlers file.

  3. Use the handlers in Node test runners (doc, Mock Service Worker, 15 min)

    Start and reset the interceptor around a Node-based test suite so each test begins with a clean state.

  4. Organise handlers as the API grows (doc, Mock Service Worker, 10 min)

    Keep a happy-path baseline and group handlers by resource so tests stay readable.

  5. Override responses inside one test (doc, Mock Service Worker, 15 min)

    Simulate a 500 error, an empty list or a slow reply for one test without touching the others.

  6. Test loading states with controlled delays (doc, Mock Service Worker, 10 min)

    Add explicit delays to confirm spinners and disabled buttons appear and clear correctly.

  7. Avoid common Testing Library mistakes, including waiting wrong (article, Kent C. Dodds, 20 min)

    Shows how to use findBy queries and waitFor so assertions wait for the UI after a mocked response, without arbitrary sleeps.

  8. Assert outcomes, not requests (doc, Mock Service Worker, 10 min)

    Check what the user sees after a request instead of counting calls, which keeps tests stable when code is refactored.