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

Testing Error Boundaries Don't Catch Event Handler Errors

Confirm error boundaries only catch render/lifecycle errors, not errors thrown in event handlers or async code.

Testing Error Boundaries Don't Catch Event Handler Errors

You'll learn how to verify that error boundaries correctly ignore errors from event handlers, catching only render and lifecycle errors.

The Boundary's Blind Spot

Error boundaries in React have a specific job: catch errors during rendering, in lifecycle methods, and in constructors of the component tree below them. They do not catch errors thrown inside event handlers like onClick or onChange.

Think of an error boundary like a safety net under a trapeze artist (rendering). If the artist falls during their routine, the net catches them. But if they trip while walking to the snack bar (event handler), that's a different scenario entirely—the safety net isn't there.

This distinction exists because event handlers don't happen during the render phase. They're asynchronous user interactions that occur after rendering is complete. React expects you to handle these errors with traditional try-catch blocks.

Testing the Boundary

To confirm your error boundary respects this limitation, write a test where a component throws an error in an event handler. The error boundary should not catch it:

it('does not catch errors from event handlers', () => {
  const ThrowOnClick = () => (
    <button onClick={() => { throw new Error('Click error'); }}>
      Break
    </button>
  );

  render(
    <ErrorBoundary fallback={<div>Error caught</div>}>
      <ThrowOnClick />
    </ErrorBoundary>
  );

  const button = screen.getByRole('button');
  
  // This error won't be caught by the boundary
  expect(() => fireEvent.click(button)).toThrow('Click error');
  
  // Fallback should NOT render
  expect(screen.queryByText('Error caught')).not.toBeInTheDocument();
});

The error propagates normally, and the fallback UI never appears.

Key Takeaway: Error boundaries only catch rendering/lifecycle errors. Always test that event handler errors correctly bypass the boundary, confirming developers must use try-catch for user interactions.