test("shows an error when the request fails", async () => {
server.use(
http.get("/api/user", () => new HttpResponse(null, { status: 500 })),
);
render(<Profile />);
expect(await screen.findByRole("alert")).toHaveTextContent(/could not load/i);
});
Override the endpoint for this one test so it returns an error, then wait for the error message the user sees.
The setup:
- Keep the happy-path handlers as defaults in
setupServer. - Override the endpoint for this one test with
server.use(...). - Make the override return an error response, such as
new HttpResponse(null, { status: 500 }). Or useHttpResponse.error()to simulate a network failure.
The test:
- Render the component.
- Wait for the error UI with
await screen.findByRole('alert')orfindByText. - Assert what the user sees, not that
console.errorwas called. - Optionally, check that the success content isn't shown.
- Optionally, test a 'Retry' button: restore the handler and click it.
Your afterEach calls server.resetHandlers(), so the override doesn't leak into other tests.
- Keep default handlers for the happy path.
- Use
server.useto override a handler for one test. - Return a 500 response, or
HttpResponse.error()for a network failure. - Assert the error the user sees with
findBy*. resetHandlersinafterEachkeeps tests isolated.
Read more