CodePark/ questions / Mocking the network (MSW)
START PRACTICINGPRACTICE
Frontend question · Testing › Mocking the network (MSW)

Using MSW, how do you test that a component shows an error message when the API fails?

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 use HttpResponse.error() to simulate a network failure.

The test:

  • Render the component.
  • Wait for the error UI with await screen.findByRole('alert') or findByText.
  • Assert what the user sees, not that console.error was 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.use to 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*.
  • resetHandlers in afterEach keeps tests isolated.