Testing with APIs
🏠The everyday picture
A flight simulator: pilots practise engine failures and storms safely, on demand, without a real plane or real weather.
📘What it really is
- Components that fetch data need a pretend API during tests: fast, predictable, and able to fail on demand.
- Mock Service Worker (MSW) intercepts requests and returns responses you define:
const server = setupServer(
http.get("http://localhost:3001/enquiries", () => HttpResponse.json(sampleEnquiries)),
);
In a test, change it to simulate failure:
server.use(http.get("http://localhost:3001/enquiries", () => new HttpResponse(null, { status: 500 })));
- Test each state: loading appears, data appears, error appears with Try again, and Try again works.
- Use
findBy…queries for things that appear after waiting:await screen.findByText("Asha"). - Mocking the network (not
api.tsitself) means your real API code is tested too.
🖱️Try it
Install MSW and write tests for the dashboard: shows enquiries from the API; shows the error message on a 500 and
recovers after Try again; shows the empty state when the API returns [].
✅Quick check
Why use a pretend API in tests rather than a real server?
Show the answer
Tests stay fast and predictable, and failures can be simulated on demand.
When do you use findByText instead of getByText?
Show the answer
When the text appears after waiting, such as after data loads.
