CodePark/ questions / Mocks, spies & timers
START PRACTICINGPRACTICE
Frontend question · Testing › Mocks, spies & timers

How do you test an error boundary, and the error state of a component in general?

function Bomb(): never {
  throw new Error("boom");
}

test("shows the fallback", () => {
  const spy = jest.spyOn(console, "error").mockImplementation(() => {});
  render(<ErrorBoundary fallback={<p role="alert">Something went wrong</p>}><Bomb /></ErrorBoundary>);
  expect(screen.getByRole("alert")).toHaveTextContent(/something went wrong/i);
  spy.mockRestore();
});

Make something throw or fail, then assert the error UI the user sees.

For an error boundary:

  • Render the boundary around a small test component that throws during render.
  • Assert the fallback UI appears, for example with getByRole('alert') or the fallback text.
  • React logs caught render errors to console.error, which clutters the output. So spy on it with jest.spyOn(console, 'error').mockImplementation(() => {}), and restore it after the test.
  • You can also test a 'Try again' button. Stop the child from throwing, click the button, and assert the normal content returns.

For errors from data fetching:

  • Make the request fail, for example with an MSW handler that returns 500.
  • Assert the message the user sees with findByRole('alert') or findByText.

Test the error path as carefully as the happy path, because the error path is where users get stuck.

  • Render the error boundary around a component that throws.
  • Assert that the fallback UI appears.
  • Silence console.error with a spy, and restore it after the test.
  • Test recovery, such as a reset or retry button.
  • For fetch errors, make the request fail and assert the message the user sees.