Error Boundary Tester Skill
You are an expert QA automation engineer specializing in error boundary and fault tolerance testing. When the user asks you to write, review, or debug tests for error boundaries and graceful degradation, follow these detailed instructions to validate that applications handle errors correctly, render appropriate fallback UIs, support error recovery, and prevent full-page crashes from isolated component failures.
Core Principles
- Errors are inevitable, crashes are not -- Every component will eventually encounter an error. Error boundaries ensure that a failure in one part of the UI does not bring down the entire application. Test that each error boundary contains failures within its scope.
- Fallback UI must be useful -- A blank screen or a raw error stack trace is not an acceptable fallback. Test that fallback UIs provide clear messaging, actionable recovery options, and a path back to a working state.
- Error reporting must be verified -- Error boundaries should report errors to monitoring services. Test that error logging occurs with sufficient context (component stack, user actions, application state) for debugging.
- Recovery must be tested explicitly -- Many error boundaries include a "Try Again" or "Reload" button. Test that these recovery mechanisms actually work and do not just re-render the same error state.
- Nested boundaries must scope correctly -- Inner error boundaries should catch errors before outer ones. If a sidebar widget fails, only the sidebar should show a fallback, not the entire page.
- Async errors need special handling -- Error boundaries in React only catch synchronous rendering errors by default. Async errors (from
useEffect, event handlers, promises) require separate handling strategies that must be tested independently.
Project Structure
Organize error boundary test projects with this structure:
tests/
error-boundaries/
unit/
error-boundary-component.test.tsx
fallback-ui.test.tsx
error-reporter.test.ts
recovery-flow.test.tsx
e2e/
component-crash.spec.ts
nested-boundary.spec.ts
full-page-crash.spec.ts
chunk-load-failure.spec.ts
network-error.spec.ts
integration/
error-logging.spec.ts
error-recovery.spec.ts
helpers/
error-injector.ts
crash-component.tsx
boundary-test-utils.ts
fixtures/
error-scenarios.fixture.ts
mocks/
error-reporter.mock.ts
playwright.config.ts
vitest.config.ts
React Error Boundary Unit Testing
Testing the Error Boundary Component Itself
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, test, expect, vi, beforeEach } from 'vitest';
import { ErrorBoundary } from '../../src/components/error-boundary';
function CrashingComponent({ shouldCrash }: { shouldCrash: boolean }) {
if (shouldCrash) {
throw new Error('Intentional test crash');
}
return <div data-testid="healthy-content">Everything is working</div>;
}
function AlwaysCrashes(): JSX.Element {
throw new Error('Component always crashes');
}
function TypeErrorComponent(): JSX.Element {
const obj: Record<string, unknown> = {};
return <div>{(obj as { nested: { value: string } }).nested.value}</div>;
}
describe('ErrorBoundary Component', () => {
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
test('renders children when no error occurs', () => {
render(
<ErrorBoundary fallback={<div>Error occurred</div>}>
<CrashingComponent shouldCrash={false} />
</ErrorBoundary>
);
expect(screen.getByTestId('healthy-content')).toBeInTheDocument();
expect(screen.queryByText('Error occurred')).not.toBeInTheDocument();
});
test('renders fallback UI when child component throws', () => {
render(
<ErrorBoundary fallback={<div data-testid="fallback">Something went wrong</div>}>
<AlwaysCrashes />
</ErrorBoundary>
);
expect(screen.getByTestId('fallback')).toBeInTheDocument();
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
expect(screen.queryByTestId('healthy-content')).not.toBeInTheDocument();
});
test('calls onError callback with error and component stack', () => {
const onError = vi.fn();
render(
<ErrorBoundary
fallback={<div>Error</div>}
onError={onError}
>
<AlwaysCrashes />
</ErrorBoundary>
);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Component always crashes',
}),
expect.objectContaining({
componentStack: expect.any(String),
})
);
});
test('catches TypeError from nested rendering', () => {
render(
<ErrorBoundary fallback={<div data-testid="type-error-fallback">Type error caught</div>}>
<TypeErrorComponent />
</ErrorBoundary>
);
expect(screen.getByTestId('type-error-fallback')).toBeInTheDocument();
});
test('different error boundaries catch errors independently', () => {
render(
<div>
<ErrorBoundary fallback={<div data-testid="sidebar-fallback">Sidebar error</div>}>
<AlwaysCrashes />
</ErrorBoundary>
<ErrorBoundary fallback={<div data-testid="main-fallback">Main error</div>}>
<CrashingComponent shouldCrash={false} />
</ErrorBoundary>
</div>
);
expect(screen.getByTestId('sidebar-fallback')).toBeInTheDocument();
expect(screen.getByTestId('healthy-content')).toBeInTheDocument();
expect(screen.queryByTestId('main-fallback')).not.toBeInTheDocument();
});
});
Testing Fallback UI Content
import { render, screen } from '@testing-library/react';
import { describe, test, expect, vi } from 'vitest';
import { ErrorFallback } from '../../src/components/error-fallback';
describe('ErrorFallback Component', () => {
test('displays user-friendly error message', () => {
render(
<ErrorFallback
error={new Error('API request failed')}
resetErrorBoundary={vi.fn()}
/>
);
expect(screen.getByRole('heading')).toHaveTextContent(/something went wrong/i);
expect(screen.queryByText('API request failed')).not.toBeInTheDocument();
});
test('shows recovery button', () => {
const resetFn = vi.fn();
render(
<ErrorFallback
= (' ')}
=
/>
);
retryButton = screen.(, { : });
(retryButton).();
});
(, () => {
resetFn = vi.();
(
);
retryButton = screen.(, { : });
retryButton.();
(resetFn).();
});
(, {
(
);
homeLink = screen.(, { : });
(homeLink).(, );
});
(, {
(
);
alertRegion = screen.();
(alertRegion).();
retryButton = screen.(, { : });
(retryButton)..(, );
});
(, {
originalEnv = process..;
process.. = ;
(
);
(screen.())..();
(screen.())..();
process.. = originalEnv;
});
});
Error Injection for E2E Testing
Forced Error Injection via Playwright
import { test, expect, Page } from '@playwright/test';
async function injectRenderError(page: Page, componentSelector: string): Promise<void> {
await page.evaluate((selector) => {
const element = document.querySelector(selector);
if (!element) throw new Error(`Element not found: ${selector}`);
const errorDiv = document.createElement('div');
errorDiv.setAttribute('data-crash-injected', 'true');
Object.defineProperty(errorDiv, 'textContent', {
get() {
throw new Error('Injected render error for testing');
},
});
element.appendChild(errorDiv);
}, componentSelector);
}
test.describe(, {
(, ({ page }) => {
page.();
page.();
(page.()).();
(page.()).();
page.( {
.(
(, {
: { : },
})
);
});
(page.()).();
sidebarFallback = page.();
(sidebarFallback).();
retryButton = sidebarFallback.();
(retryButton).();
});
(, ({ page }) => {
page.();
page.();
page.( {
.(
(, {
: { : , : },
})
);
});
fallback = page.();
(fallback).();
fallback.().();
(page.()).();
(fallback)..();
});
});
Testing Error Boundaries with Network Failures
import { test, expect } from '@playwright/test';
test.describe('Network Error Boundaries', () => {
test('should show error boundary when API request fails', async ({ page }) => {
await page.route('**/api/dashboard/stats', (route) => {
route.abort('connectionrefused');
});
await page.goto('/dashboard');
await page.waitForLoadState('networkidle');
const statsError = page.locator('[data-testid="stats-error"]');
await expect(statsError).toBeVisible();
await expect(statsError).toContainText(/unable to load|failed to load/i);
await expect(page.locator('[data-testid="recent-activity"]')).toBeVisible();
});
test('should recover when API becomes available again', async ({ page }) => {
requestCount = ;
page.(, {
requestCount++;
(requestCount <= ) {
route.();
} {
route.({
: ,
: ,
: .({ : , : }),
});
}
});
page.();
page.();
statsError = page.();
(statsError).();
statsError.().();
(page.()).();
(page.()).();
});
(, ({ page }) => {
page.(, {
route.({
: ,
: ,
: .({ : }),
});
});
page.();
page.();
(page.()).();
(page.())..();
(page.())..();
});
});
Nested Error Boundary Scoping
Testing that inner boundaries catch errors before outer boundaries is critical for maintaining partial functionality during failures.
import { render, screen } from '@testing-library/react';
import { describe, test, expect, vi } from 'vitest';
import { ErrorBoundary } from '../../src/components/error-boundary';
function CrashingWidget(): JSX.Element {
throw new Error('Widget crashed');
}
function HealthyWidget(): JSX.Element {
return <div data-testid="healthy-widget">Working widget</div>;
}
describe('Nested Error Boundary Scoping', () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
test('inner boundary catches error before outer boundary', () => {
const innerOnError = vi.fn();
const outerOnError = vi.fn();
render(
);
(screen.()).();
(screen.()).();
(screen.())..();
(screen.()).();
(innerOnError).();
(outerOnError)..();
});
(, {
outerOnError = vi.();
(
);
(screen.()).();
(outerOnError).();
});
(, {
(
);
(screen.()).();
(screen.()).();
(screen.()).();
(screen.())..();
});
});
Error Logging and Reporting Verification
import { describe, test, expect, vi, beforeEach } from 'vitest';
import { render } from '@testing-library/react';
import { ErrorBoundary } from '../../src/components/error-boundary';
import * as errorReporter from '../../src/lib/error-reporter';
function CrashingComponent(): JSX.Element {
throw new Error('Crash for reporting test');
}
describe('Error Reporting from Boundaries', () => {
let reportSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
reportSpy = vi.spyOn(errorReporter, 'reportError').mockResolvedValue(undefined);
vi.spyOn(console, 'error').mockImplementation(() => {});
});
test('error boundary should report error to monitoring service', () => {
render(
< =<>Error}>
);
(reportSpy).();
(reportSpy).(
expect.({
: ,
}),
expect.({
: expect.(),
})
);
});
(, {
(
);
[, errorInfo] = reportSpy..[];
(errorInfo.).();
});
(, {
(
);
[error, errorInfo] = reportSpy..[];
reportString = .({ : error., ...errorInfo });
(reportString)..();
(reportString)..();
(reportString)..();
});
});
Async Error Handling
React error boundaries do not catch errors in event handlers, async functions, or setTimeout callbacks. These require separate handling.
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { describe, test, expect, vi } from 'vitest';
import { useState } from 'react';
import { ErrorBoundary } from '../../src/components/error-boundary';
function AsyncCrashingComponent() {
const [error, setError] = useState<Error | null>(null);
const handleClick = async () => {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('API failed');
const data = await response.json();
return data;
} catch (err) {
setError(err as Error);
}
};
if (error) {
throw error;
}
return (
< = =>
Load Data
);
}
(, {
vi.(, ).( {});
(, () => {
. = vi.().( ());
(
);
fireEvent.(screen.());
( {
(screen.()).();
});
});
});
Chunk Loading Failure Handling
Dynamic imports can fail when deployment invalidates old chunks. This is a common production error that error boundaries must handle.
import { test, expect } from '@playwright/test';
test.describe('Chunk Loading Failure', () => {
test('should show error boundary when a lazy-loaded chunk fails', async ({ page }) => {
await page.route('**/*.chunk.js', (route) => {
route.fulfill({
status: 404,
body: 'Not Found',
});
});
await page.goto('/');
await page.waitForLoadState('networkidle');
await page.click('a[href="/settings"]');
await expect(
page.locator('[role="alert"], [data-testid="chunk-error"]')
).toBeVisible({ timeout: 10000 });
const reloadButton = page.locator(
'button:has-text("Reload"), button:has-text("Refresh")'
);
await expect(reloadButton).();
});
(, ({ page }) => {
chunkRequestCount = ;
page.(, {
chunkRequestCount++;
(chunkRequestCount <= ) {
route.({ : , : });
} {
route.();
}
});
page.();
page.();
(
page.()
).({ : });
(chunkRequestCount).();
});
(, ({ page }) => {
page.(, {
(route.().().()) {
route.({ : , : });
} {
route.();
}
});
page.();
page.();
errorMessage = page.();
( errorMessage.()) {
text = errorMessage.();
(text).();
}
});
});
Configuration
Vitest Configuration for Error Boundary Tests
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./tests/setup.ts'],
globals: true,
include: [
'tests/error-boundaries/unit/**/*.test.{ts,tsx}',
'tests/error-boundaries/integration/**/*.test.{ts,tsx}',
],
coverage: {
include: [
'src/components/error-boundary/**',
'src/components/error-fallback/**',
'src/lib/error-reporter.*',
],
thresholds: {
statements: 90,
branches: 85,
functions: 90,
lines: 90,
},
},
},
});
Playwright Configuration for Error Boundary E2E Tests
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests/error-boundaries/e2e',
fullyParallel: true,
retries: 1,
reporter: [
['html', { open: 'never' }],
['json', { outputFile: 'error-boundary-results.json' }],
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'on-first-retry',
},
projects: [
{
name: 'error-boundaries-chrome',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'error-boundaries-firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'error-boundaries-mobile',
use: { ...devices['iPhone 14'] },
},
],
});
Test Setup File
import '@testing-library/jest-dom';
import { cleanup } from '@testing-library/react';
import { afterEach, vi } from 'vitest';
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
const originalConsoleError = console.error;
console.error = (...args: unknown[]) => {
const message = typeof args[0] === 'string' ? args[0] : '';
if (
message.includes('Error: Uncaught') ||
message.includes('The above error occurred in') ||
message.includes('Consider adding an error boundary')
) {
return;
}
originalConsoleError(...args);
};
Best Practices
-
Wrap every route-level component in an error boundary -- Each page or route should have its own error boundary so that navigation to a broken page does not crash the entire application.
-
Use granular boundaries for independent widgets -- Dashboard widgets, sidebar components, and data visualization panels should each have their own error boundary. A failing chart should not bring down the navigation.
-
Always provide a recovery action in fallback UIs -- Every error fallback must include at least one actionable button: "Try Again", "Reload Page", or "Go Home". A dead-end error screen forces users to manually refresh.
-
Log errors with component stack traces -- The componentStack from getDerivedStateFromError or componentDidCatch shows exactly where in the component tree the error occurred. Always include this in error reports.
-
Test error boundaries with multiple error types -- Test with TypeError, RangeError, SyntaxError, network errors, and custom application errors. Different error types may need different fallback messaging.
-
Handle async errors explicitly -- Since React error boundaries do not catch async errors by default, use the "re-throw via state" pattern: catch the async error, set it in state, and throw from render.
-
Implement retry with exponential backoff -- When error boundaries support retry, implement exponential backoff to prevent rapid retry loops that overwhelm failing services.
-
Test error boundaries in production mode -- Development mode shows additional error overlays and detailed stack traces. Production mode hides these. Test in production mode to verify users see the correct fallback.
-
Add error boundaries around dynamic imports -- Every React.lazy() call should be wrapped in a Suspense with an error boundary. Chunk loading failures are common after deployments and must be handled gracefully.
-
Verify error boundaries do not swallow errors silently -- An error boundary that catches an error but does not log it or show a fallback is worse than no boundary at all. Test that every caught error is both displayed and reported.
-
Test keyboard navigation within fallback UIs -- Users who encounter an error boundary while navigating with a keyboard must be able to reach the retry button and other recovery actions without a mouse.
Anti-Patterns to Avoid
-
Catching errors without reporting them -- An error boundary that renders a fallback but does not send the error to a monitoring service is a blind spot. Production errors caught by silent boundaries are invisible to the development team.
-
Using a single error boundary at the app root only -- A single top-level boundary means any component failure replaces the entire UI with a fallback. This defeats the purpose of error containment. Use boundaries at multiple levels.
-
Showing raw error messages to users -- Error messages like "TypeError: Cannot read properties of undefined" are meaningless to users and may expose implementation details. Always show user-friendly messages in production.
-
Retrying without clearing the error state -- If a retry attempt does not properly reset the error boundary's internal state, it will continue showing the fallback even after the underlying issue is resolved.
-
Ignoring async error handling -- Assuming that wrapping a component in an error boundary catches all errors within it, including those from useEffect, event handlers, and promises, is a dangerous misconception. These require explicit error handling.
-
Testing error boundaries only in development mode -- React's development mode includes an error overlay that masks the actual error boundary behavior. Always run error boundary tests against a production build to verify real user experience.
-
Nesting too many boundaries -- While granular boundaries are good, excessive nesting (every single component) creates maintenance burden and can make error UIs fragmented. Find the right balance at the feature or widget level.
Debugging Tips
-
Use React DevTools to inspect error boundary state -- React DevTools shows the component tree including error boundary state. Look for boundaries in the "errored" state to understand which boundary caught which error.
-
Check the browser console for "The above error occurred in..." messages -- React logs detailed component stack traces when an error boundary catches an error. These messages show the exact component path from the root to the error source.
-
Temporarily remove error boundaries to see raw errors -- When debugging, temporarily remove the error boundary wrapping a problematic component. This lets you see the full unhandled error with its original stack trace.
-
Verify error boundary reset behavior with React key prop -- Adding a key prop to an error boundary forces React to unmount and remount it when the key changes. Use this as a reset mechanism: <ErrorBoundary key={resetKey}>.
-
Test with React's Strict Mode enabled -- Strict Mode double-renders components in development, which can expose error boundary issues related to side effects in render. Ensure boundaries work correctly under Strict Mode.
-
Watch for "Maximum update depth exceeded" in error recovery -- If clicking "Retry" causes the component to immediately error again, it can create an infinite error-recovery loop. Add safeguards like retry counters or cooldown periods.
-
Check for hydration errors in SSR applications -- Server-side rendered applications can trigger error boundaries during hydration when server-rendered HTML does not match client-rendered output. Test error boundaries specifically around the hydration phase.
-
Log the error boundary lifecycle -- Add console logs to getDerivedStateFromError and componentDidCatch (or the equivalent hooks) to trace exactly when errors are caught, what fallback is rendered, and when recovery is attempted.
-
Verify that error boundaries handle errors during unmount -- Components that throw errors during cleanup (in useEffect return functions or componentWillUnmount) may not be caught by error boundaries. Test these edge cases explicitly.
-
Use Sentry or similar tools to verify error boundary reports in staging -- Before deploying to production, verify that error boundary reports actually reach your monitoring tool with correct source maps, component stacks, and user context.