How to Mock Error Boundaries in React
Mocking Error Boundaries in React is essential for unit testing component failures and ensuring your fallback UI renders correctly. This article provides a straightforward guide on how to mock Error Boundaries using Jest and React Testing Library, including how to mock the boundary component itself and how to suppress noisy console error logs during testing.
Method 1: Mocking the Error Boundary Component Globally
If you want to isolate a component under test and prevent a real Error Boundary from catching errors during your test suite, you can mock the entire Error Boundary module using Jest. This replaces the complex boundary logic with a simple mock component.
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
// Mock the ErrorBoundary component
jest.mock('./ErrorBoundary', () => {
return function MockErrorBoundary({ children }) {
return <div data-testid="mock-error-boundary">{children}</div>;
};
});
test('renders children inside the mocked Error Boundary', () => {
render(
<MyComponent />
);
expect(screen.getByTestId('mock-error-boundary')).toBeInTheDocument();
});Method 2: Testing a Real Error Boundary by Mocking Child Errors
Instead of mocking the boundary itself, you may want to test that your actual Error Boundary correctly catches errors thrown by its children. To do this, you can mock a child component to intentionally throw an error when rendered.
import React from 'react';
import { render, screen } from '@testing-library/react';
import ErrorBoundary from './ErrorBoundary';
// A dummy component that throws an error
const ThrowError = () => {
throw new Error('Test error');
};
test('ErrorBoundary catches error and displays fallback UI', () => {
render(
<ErrorBoundary fallback={<div>Something went wrong.</div>}>
<ThrowError />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong.')).toBeInTheDocument();
});Method 3: Suppressing Console Errors in Jest
When testing components that throw errors, React and Jest will output
loud error stacks to your terminal console, even if the error is
successfully caught by an Error Boundary. You can mock
console.error to keep your test output clean.
describe('ErrorBoundary', () => {
let consoleErrorSpy;
beforeAll(() => {
// Spy on console.error and mock its implementation to do nothing
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterAll(() => {
// Restore console.error to its original state
consoleErrorSpy.mockRestore();
});
test('renders fallback without cluttering the console', () => {
render(
<ErrorBoundary fallback={<div>Error occurred</div>}>
<ThrowError />
</ErrorBoundary>
);
expect(screen.getByText('Error occurred')).toBeInTheDocument();
});
});