Blog>
Snippets

Unit Testing Error Boundaries

Provide an example of how to write unit tests for Error Boundaries using jest and react-testing-library.
import React from 'react';
import { render, screen } from '@testing-library/react';
import { ErrorBoundary } from './ErrorBoundary';
import { toThrowErrorMatchingInlineSnapshot } from 'jest-snapshot';

// Dummy Component to trigger an error
const ProblematicComponent = () => {
  throw new Error('Test error');
};

describe('ErrorBoundary', () => {
  it('renders the children when there is no error', () => {
    render(
      <ErrorBoundary>
        <div>Child content</div>
      </ErrorBoundary>
    );
    expect(screen.getByText('Child content')).toBeInTheDocument();
  });

  it('renders fallback UI when a child component throws an error', () => {
    jest.spyOn(console, 'error');
    console.error.mockImplementation(() => {});

    render(
      <ErrorBoundary>
        <ProblematicComponent />
      </ErrorBoundary>
    );

    expect(screen.getByRole('alert')).toHaveTextContent('Something went wrong.');
    expect(console.error).toHaveBeenCalledTimes(2);

    // Clean up mock to avoid affecting other tests
    console.error.mockRestore();
  });
});
This code provides two unit tests for an ErrorBoundary component using jest and react-testing-library. The first test checks that child components render correctly when there is no error. The second test checks that the ErrorBoundary renders a fallback UI when a child component throws an error. It also mocks and checks that `console.error` is called as a side effect when an error is caught, in line with React's error logging mechanism, and restores the mock afterward to not affect other tests.