Sub topic 13
Testing boundaries and fallbacks
This chapter shows how to test an error boundary and its fallback UI with Vitest and React Testing Library. It assumes you can write a boundary (class-based or from react-error-boundary) and have used render, screen, and userEvent in tests. The examples use Vitest. In Jest, replace vi with jest.
What a boundary test has to prove
A boundary is hard to test by hand because the error only appears when something breaks. A good test makes that break happen on purpose. It then checks four behaviors:
- The fallback appears when a child throws during render.
- Code outside the boundary keeps working.
- The reporting callback receives the error and the component stack.
- The reset path returns the user to a working screen.
You also need to check that errors from event handlers and async code reach the boundary when you route them there.
Setup
Install the test tools and configure jsdom. These packages are typical:
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-domIn vitest.config.js, set test.environment to "jsdom". Point test.setupFiles at a file that contains import "@testing-library/jest-dom/vitest";. That import gives you matchers such as toBeInTheDocument.
A boundary that is easy to test
The class boundary from earlier chapters logs with console.error. That is awkward to assert on, because React also writes to console.error. Give the boundary an onError prop instead. Production code passes your logging function, and tests pass a spy.
// ErrorBoundary.jsx
import { Component } from "react";
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
this.props.onError?.(error, info);
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}Silence the expected noise
When a boundary catches an error, React still reports it to the console. React 19 calls console.error for caught errors by default. React 18 in development also re-throws the error to the window, and jsdom prints it as Error: Uncaught [...]. Your test output fills with stack traces from errors you caused on purpose.
Mock console.error for the tests that throw, and restore it afterward:
import { afterEach, beforeEach, vi } from "vitest";
beforeEach(() => {
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
});Test 1: the fallback replaces the failing subtree
Create a small component that throws on demand. The tests below use it as the failing child.
// ErrorBoundary.test.jsx
import { render, screen } from "@testing-library/react";
import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
import "@testing-library/jest-dom/vitest";
import { ErrorBoundary } from "./ErrorBoundary";
function Bomb({ shouldThrow = true }) {
if (shouldThrow) {
throw new Error("Boom");
}
return <p>All good</p>;
}
describe("ErrorBoundary", () => {
beforeEach(() => {
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
});
test("shows the fallback when a child throws", () => {
render(
<ErrorBoundary fallback={<p role="alert">Something went wrong.</p>}>
<Bomb />
</ErrorBoundary>
);
expect(screen.getByRole("alert")).toHaveTextContent("Something went wrong.");
expect(screen.queryByText("All good")).not.toBeInTheDocument();
});
test("renders children when nothing throws", () => {
render(
<ErrorBoundary fallback={<p role="alert">Something went wrong.</p>}>
<Bomb shouldThrow={false} />
</ErrorBoundary>
);
expect(screen.getByText("All good")).toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});The second test is easy to skip, but it guards against a boundary that always shows its fallback.
Query the fallback by role or text, the way a user would see it. Do not assert on the boundary's internal state. Giving the fallback role="alert" makes it easy to find and also helps screen reader users.
Test 2: isolation
Boundaries exist to contain damage, so test containment directly. Render a sibling next to the boundary and confirm it survives.
test("keeps content outside the boundary", () => {
render(
<>
<ErrorBoundary fallback={<p role="alert">Widget failed.</p>}>
<Bomb />
</ErrorBoundary>
<nav>Sidebar</nav>
</>
);
expect(screen.getByRole("alert")).toBeInTheDocument();
expect(screen.getByText("Sidebar")).toBeInTheDocument();
});Without the boundary, the Sidebar text would disappear along with the whole tree. This test fails if someone later moves or removes the boundary.
Test 3: error reporting
Pass vi.fn() as onError and check what it received. The second argument holds the component stack.
test("reports the error and component stack", () => {
const onError = vi.fn();
render(
<ErrorBoundary fallback={<p>Failed</p>} onError={onError}>
<Bomb />
</ErrorBoundary>
);
expect(onError).toHaveBeenCalledTimes(1);
const [error, info] = onError.mock.calls[0];
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe("Boom");
expect(info.componentStack).toContain("Bomb");
});Test 4: reset and recovery
Reset tests need a child that fails first and succeeds later. A module-level flag works well. The test flips the flag, clicks the retry button, and checks that the boundary renders the children again. This example uses react-error-boundary, whose fallback receives resetErrorBoundary.
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ErrorBoundary } from "react-error-boundary";
import { expect, test, vi } from "vitest";
import "@testing-library/jest-dom/vitest";
let broken = true;
function Flaky() {
if (broken) {
throw new Error("Not ready");
}
return <p>Recovered</p>;
}
function Fallback({ resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
test("retry re-renders the children", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const user = userEvent.setup();
broken = true;
render(
<ErrorBoundary FallbackComponent={Fallback}>
<Flaky />
</ErrorBoundary>
);
expect(screen.getByRole("alert")).toBeInTheDocument();
broken = false;
await user.click(screen.getByRole("button", { name: "Try again" }));
expect(screen.getByText("Recovered")).toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
vi.restoreAllMocks();
});Also test the failure case. If broken stays true, the click should bring the fallback back instead of crashing the test or looping. A test like that confirms users can retry more than once.
To test resetKeys, render with one key, let the child fail, then call rerender with a different key. The fallback should disappear without any click.
Test 5: errors from handlers and async code
Boundaries do not catch these errors on their own, so the test should confirm that your routing code works. Use showBoundary and an async assertion, because the error arrives after a rejected Promise settles.
import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
function SaveButton({ save }) {
const { showBoundary } = useErrorBoundary();
async function handleClick() {
try {
await save();
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}
test("routes a failed save to the boundary", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const user = userEvent.setup();
const save = vi.fn().mockRejectedValue(new Error("Save failed"));
render(
<ErrorBoundary fallback={<p role="alert">Could not save.</p>}>
<SaveButton save={save} />
</ErrorBoundary>
);
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save.");
vi.restoreAllMocks();
});findByRole waits for the fallback to appear. getByRole would fail here because the rejection has not been handled yet when the click returns.
Test 6: lazy loading failures
A failed dynamic import is a good case to simulate, because real network failures are hard to reproduce. A lazy component whose loader rejects triggers the boundary the same way a failed chunk download does.
import { lazy, Suspense } from "react";
test("shows the fallback when the lazy import fails", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const Chart = lazy(() => Promise.reject(new Error("Failed to fetch module")));
render(
<ErrorBoundary fallback={<p role="alert">The chart failed to load.</p>}>
<Suspense fallback={<p>Loading chart…</p>}>
<Chart />
</Suspense>
</ErrorBoundary>
);
expect(await screen.findByRole("alert")).toHaveTextContent("failed to load");
vi.restoreAllMocks();
});Create the lazy component inside the test. React caches a lazy component's result, so a rejected one would stay rejected in every later test that shares it.
Common mistakes
| Problem | Cause | Fix |
|---|---|---|
| Test output is full of stack traces | React reports caught errors to the console | Mock `console.error` in the throwing tests |
| Test fails with an uncaught error | The thrown error has no boundary above it | Wrap the component in a boundary, or test it with `expect(() => render(...)).toThrow()` |
| Retry test passes with the fallback still showing | The failure flag was reset after the click | Change the flag before the click |
| Lazy test fails only on the second run | A shared `lazy` component cached its rejection | Create the `lazy` component inside each test |
| Async test is flaky | A synchronous query ran before the error arrived | Use `findBy` queries or `waitFor` |
Testing the root callbacks
The onCaughtError and onUncaughtError options belong to createRoot in your entry file. You rarely need to test them through the DOM. Move the reporting logic into a function such as reportError(label, error, componentStack) and unit test that function directly. Keep the entry file thin so there is little left to test.
Exercise
A test renders <ErrorBoundary fallback={<p role="alert">Failed</p>}><Bomb /></ErrorBoundary> and then asserts expect(screen.getByRole("alert")).toBeInTheDocument(). The assertion passes, but the console fills with errors. Name two ways to handle that noise. Then explain why a second test that renders <Bomb shouldThrow={false} /> in the same boundary is worth writing.
Show answer
Mock console.error with vi.spyOn(console, "error").mockImplementation(() => {}) in a beforeEach, and restore it in afterEach. Alternatively, pass an onError spy so the boundary's own reporting is checked, and keep the mock only around the throwing tests. The second test checks that the boundary renders its children when nothing throws. Without it, a boundary that always shows the fallback would still pass the first test.
Exercise
In a retry test, the fallback's "Try again" button is clicked, but the fallback is still on screen afterward. The test sets broken = false after the click. What is wrong, and what is the fix?
Show answer
Clicking the button calls resetErrorBoundary, which re-renders the children immediately. Flaky still sees broken === true, throws again, and the fallback comes back. Set broken = false before the click so the re-rendered child succeeds.