Integration Testing with react-error-boundary
You'll learn how to write integration tests that verify your error boundaries work correctly with the react-error-boundary library's components and utilities.
Moving Beyond Manual Error Boundaries
In earlier lessons, you tested error boundaries you built yourself using React's componentDidCatch. The react-error-boundary library provides pre-built, production-ready error boundary components with helpful utilities that make testing more streamlined.
The ErrorBoundary Component
The library's <ErrorBoundary> component wraps your code and catches errors declaratively:
import { ErrorBoundary } from 'react-error-boundary';
import { render, screen } from '@testing-library/react';
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
test('ErrorBoundary catches and displays component errors', () => {
const ThrowError = () => { throw new Error('Test error'); };
render(
<ErrorBoundary FallbackComponent={ErrorFallback}>
<ThrowError />
</ErrorBoundary>
);
expect(screen.getByRole('alert')).toBeInTheDocument();
expect(screen.getByText(/Test error/i)).toBeInTheDocument();
});
The useErrorHandler Hook
The library also provides useErrorHandler() to programmatically throw errors from event handlers or async code—areas where error boundaries normally don't catch:
import { useErrorHandler } from 'react-error-boundary';
function AsyncComponent() {
const handleError = useErrorHandler();
const handleClick = async () => {
try {
await failingApiCall();
} catch (error) {
handleError(error); // Triggers the error boundary
}
};
return <button onClick={handleClick}>Fetch</button>;
}
This bridges the gap you tested earlier where event handler errors don't trigger boundaries automatically.
Key Takeaway: Use react-error-boundary's ErrorBoundary component and useErrorHandler hook in your tests to verify realistic error-handling scenarios, combining declarative error catching with programmatic error throwing for comprehensive coverage.