Course contentsShow
← React
Lesson 2139 of 2,39647. Testing Patterns and Best PracticesFree lesson

Testing the Fallback UI Renders

Verify that when an error occurs, the error boundary renders its fallback UI instead of crashing the test.

Testing the Fallback UI Renders

What you'll learn: How to verify that your error boundary's fallback UI actually appears when an error occurs, proving your error handling works.

The Core Idea

When you've set up an error boundary with a fallback UI (like "Something went wrong"), you need to confirm it actually displays when errors happen. This isn't just about throwing an error—it's about asserting that the right UI replacement appears to users instead of a white screen or cryptic error messages.

Think of it like testing a safety net: you need to verify that when someone falls (error occurs), the net catches them (fallback displays) rather than letting them hit the ground (app crashes).

How It Works

After triggering an error with a throwing component, you query for elements that only exist in your fallback UI. If you can find them, your error boundary is working:

test('displays fallback UI when child throws', () => {
  const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
  
  render(
    <ErrorBoundary fallback={<div>Something went wrong</div>}>
      <ThrowError />
    </ErrorBoundary>
  );
  
  // The fallback should now be visible
  expect(screen.getByText('Something went wrong')).toBeInTheDocument();
  
  // The normal content should NOT be there
  expect(screen.queryByText('Normal Content')).not.toBeInTheDocument();
  
  consoleError.mockRestore();
});

You're testing the user experience of failure: does the user see a helpful message, or does everything break?

What You're Really Testing

This validates that your error boundary's componentDidCatch or error handling logic correctly switches to rendering the fallback instead of the crashed children. It's behavior testing—the user doesn't know React components exist, they just know "the app shows me an error message."

Key Takeaway: Test that your error boundary's fallback UI renders by querying for fallback-specific content after triggering an error—this proves users see graceful error handling, not crashes.