Mock network requests in front-end tests
8 steps · about 1 h 50 min · Intermediate
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.