Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Test React Error Boundaries & Reporting

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Error boundaries are React components that catch JavaScript errors in their child component tree, log them, and display a fallback UI instead of crashing the whole app. Testing them ensures your app degrades gracefully and that errors are reported to your monitoring service. This guide walks you through writing tests for error boundaries and verifying that error reporting works as expected.

What You'll Need

  • A React project (16.0 or later) with a test runner set up (Jest is assumed, but the concepts transfer to Vitest).
  • @testing-library/react and @testing-library/jest-dom installed.
  • An error boundary component (either your own or a library like react-error-boundary).
  • An error reporting service (e.g., Sentry, LogRocket, or a custom logger) – or a mock of it.

Step-by-Step

  1. Create a test file for your error boundary, e.g., ErrorBoundary.test.jsx.
  2. Import React, the testing library, and your error boundary component. Also import the component you'll use to trigger an error (a simple child component that throws).
  3. Write a helper that silences console.error during tests. React logs errors to the console by default, which can clutter test output. Use jest.spyOn(console, 'error').mockImplementation(() => {}) in a beforeEach and restore it in afterEach.
  4. Test that the fallback UI renders when a child throws. Render the error boundary with a child that throws (e.g., a component that calls throw new Error('Test error') in its render). Assert that the fallback UI text appears.
  5. Test that the error boundary does not catch errors from its own event handlers. Error boundaries only catch errors during rendering, in lifecycle methods, and in constructors. To test this, render a button that throws on click, and assert that the error is not caught (the fallback does not appear).
  6. Test that the error reporting function is called. Pass a mock onError prop to your error boundary (or mock your reporting service). Render the throwing child, then assert that the mock was called with the error object.
  7. Test that the error boundary resets correctly if it has a reset mechanism (e.g., a resetKeys prop). Change the key prop and assert that the fallback disappears and the child re-renders.
  8. Test error reporting to an external service. If you use a library like Sentry, mock its captureException method and assert it's called when the boundary catches an error.
  9. Run your tests with npm test or yarn test and ensure they pass.

Common Mistakes

  • Forgetting to mock console.error – this leads to noisy test output and can hide real issues.
  • Testing event handler errors – error boundaries do not catch errors in event handlers, so expecting them to is incorrect.
  • Not resetting mocks – if you mock your error reporting service, clear the mock between tests to avoid cross-test contamination.
  • Using a child that throws asynchronously – error boundaries only catch synchronous errors during render. For async errors, you need a separate mechanism.
  • Not testing the reset behavior – if your boundary can recover, you should test that the recovery works.

Tips

  • Use a test-friendly error boundary like react-error-boundary which provides a onError prop and reset capabilities out of the box.
  • Structure your tests with describe blocks for each behavior: rendering fallback, calling onError, resetting, etc.
  • Keep the throwing child simple – a component that just throws in its render is enough.
  • Test the error boundary in isolation – don't wrap it in a full app context unless necessary.
  • Verify error reporting integration with a smoke test that checks the reporting function is called, but avoid testing the external service's internals.

Troubleshooting

  • Fallback UI not rendering: Ensure the error is thrown during render or in a lifecycle method. Check that the error boundary is a class component (or uses the new componentDidCatch hook) and that it's placed correctly in the tree.
  • Error reporting not called: Verify that the onError prop is passed correctly and that the boundary's componentDidCatch actually calls it. If you're mocking a service, ensure the mock is set up before the render.
  • Tests pass but console shows errors: Make sure you mock console.error in beforeEach and restore it in afterEach. If you still see errors, check if they come from async code or from React itself (e.g., act warnings).
  • Error boundary catches errors from event handlers: This is expected – error boundaries do not catch those. If your test expects them to, adjust your test to simulate a render error instead.
  • Reset not working: If you use resetKeys, ensure the key actually changes between renders. If you use a state-based reset, make sure the state is updated correctly.

Frequently Asked Questions

Can I test error boundaries with React Testing Library?

Yes, React Testing Library works well. Use render to render the boundary with a throwing child, and use screen to query the fallback UI.

Do error boundaries catch errors in event handlers?

No, error boundaries do not catch errors in event handlers, asynchronous code (like setTimeout or fetch callbacks), or server-side rendering. You need to handle those separately, e.g., with try-catch or error event listeners.

How do I test error reporting to Sentry?

Mock the Sentry module in your test (e.g., jest.mock('@sentry/react', () => ({ captureException: jest.fn() }))) and assert that captureException is called with the error.

What is the difference between componentDidCatch and getDerivedStateFromError?

getDerivedStateFromError is used to update state (e.g., to show fallback UI), while componentDidCatch is for side effects like logging. Both are called when an error is thrown.

Can I test error boundaries with Enzyme?

Yes, but React Testing Library is more aligned with modern React testing practices. If you use Enzyme, you can use mount and simulate errors, but you'll need to handle React's error logging similarly.

How do I test that the error boundary resets after a successful retry?

Render the boundary with a key prop. Change the key to force a remount, then assert that the fallback is gone and the child renders successfully. If your boundary uses a reset function, call it via a button and assert the UI updates.