Mock Service Worker
- React course
- Advanced
- Lesson 46/56
- 4 min
Learn to mock API requests with MSW.
Mock Service Worker
MSW intercepts network requests in the test environment and returns fake responses. You set up a server with setupServer and register a route with http.get.
A handler returns a response via HttpResponse.json(...). In the test file you call beforeAll(() => server.listen()) and afterAll(() => server.close()).
This way a component tests real fetch behaviour without a live API.
Handlers and responses
An MSW handler looks like http.get('/api/user', resolver). The resolver receives request info and returns an HttpResponse.
To set a status code use HttpResponse.json(data, { status: 201 }). To test an error scenario return HttpResponse.error().
All handlers are passed to setupServer in an array.
Practice Write the MSW server
Write the MSW server. Call setupServer with http.get('/api/user', () => HttpResponse.json({ name: 'Alex' })). Export the server.
Starter code
// Write the MSW server hereSample solution
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
const server = setupServer(
http.get('/api/user', () => HttpResponse.json({ name: 'Alex' }))
);
export default server;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: set up the MSW server
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
const server = ____(
http.get('/api/user', () => HttpResponse.json({ name: 'Alex' }))
);
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
const server = setupServer(
http.get('/api/user', () => HttpResponse.json({ name: 'Alex' }))
);
Explanation: setupServer starts the server.
2 How is an error scenario tested in MSW?
- By shutting the real server
- By returning HttpResponse.error() Correct answer
- By setting fetch to null
- By wrapping with try/catch
Explanation: HttpResponse.error() gives an error response.
3 Match MSW concepts
| Term | Meaning |
|---|---|
setupServer |
Creates the server |
http.get |
Catches a route |
HttpResponse.json |
Gives a fake response |
server.listen |
Starts listening |