patterntypescriptnoneModerate
Testing Error Boundaries in React
Viewed 0 times
error boundaryReacttestingconsole.errorgetDerivedStateFromError
Error Messages
Problem
Error boundaries catch runtime errors but are hard to test because React swallows console.error output during tests and the test environment behaves differently from the browser.
Solution
Suppress expected console.error output and test error boundary rendering explicitly.
import { render, screen } from '@testing-library/react';
class ErrorBoundary extends React.Component<
{ children: React.ReactNode; fallback: React.ReactNode },
{ hasError: boolean }
> {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() {
return this.state.hasError ? this.props.fallback : this.props.children;
}
}
// Component that throws
function BrokenComponent({ shouldThrow }: { shouldThrow: boolean }) {
if (shouldThrow) throw new Error('Test error');
return <div>OK</div>;
}
test('ErrorBoundary shows fallback on error', () => {
// Suppress React's console.error for expected errors
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
render(
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<BrokenComponent shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
spy.mockRestore();
});Why
React intentionally logs uncaught errors during render to console.error even when an error boundary catches them. Not suppressing this causes tests to appear to have errors in their output.
Gotchas
- Always restore console.error after the test — use mockRestore() or a try/finally block.
- React 18+ calls console.error twice in StrictMode for some errors — your spy may be called more times than expected.
- Error boundaries do not catch errors in event handlers — only errors in render and lifecycle methods.
Revisions (0)
No revisions yet.