All topics
Testingintermediate

Mocking API Calls in Tests

Learn how to isolate component tests from real network requests using mocking tools like MSW.

Component tests that trigger real network requests are slow, flaky (dependent on network conditions and a live backend being available and in a known state), and hard to control precisely for testing specific scenarios like an error response. Mocking intercepts those requests and returns controlled, predictable responses instead, keeping tests fast, deterministic, and fully within your control.

Mocking API calls with MSW is like a stunt double intercepting a dangerous scene on a film set — the actor (your component code) performs their scene exactly as written, believing they're doing the real stunt (a real network request), while the stunt double (the mock) actually handles the risky part safely and predictably behind the scenes.

Key Concepts

1
Mock Service Worker (MSW) has become a preferred approach because it intercepts requests at the network level (using a Service Worker in the browser, or request interception in Node for tests) rather than mocking fetch/axios directly in your application code — this means your component code makes real fetch calls exactly as it would in production, and MSW transparently intercepts them before they leave the process, so you're testing your actual data-fetching code path rather than a stubbed-out version of it.
fetchaxios
2
Defining handlers per HTTP method and URL pattern (http.get('/api/users/:id', ...)) lets you return whatever response shape, status code, or delay a specific test scenario needs — including deliberately testing error states and loading states by controlling exactly what the mocked endpoint returns for that test.
http.get('/api/users/:id', ...)
3
Interviewers ask candidates to set up a test that verifies a component correctly displays an error message when its data-fetching request fails, expecting them to configure a mock handler that returns an error response for that specific test rather than only ever testing the successful, happy-path response.