Sub topic 13
Testing boundaries and fallbacks
This chapter assumes you can write a React component test with React Testing Library, and that you have a boundary like the one from the earlier chapters. The examples use Vitest with jsdom, @testing-library/react, @testing-library/user-event, and react-error-boundary. They work in Jest with jest.fn() and jest.spyOn in place of vi.
What to test
A boundary has four behaviors worth checking:
- It shows the fallback when a child throws while rendering.
- It leaves content outside the boundary alone.
- It recovers when the user retries.
- It reports the error with its component stack.
Test through the rendered output. Don't assert on this.state or call lifecycle methods directly.
Silence the expected noise
When a boundary catches an error, React still logs it to console.error, and jsdom may log it again as an uncaught error. The test passes but the output is full of stack traces. Replace console.error with a no-op for these tests, and restore it afterwards.
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ErrorBoundary } from "react-error-boundary";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
let shouldThrow;
function Bomb() {
if (shouldThrow) {
throw new Error("boom");
}
return <p>Recovered</p>;
}
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
beforeEach(() => {
shouldThrow = true;
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
});
test("shows the fallback and keeps outside content", () => {
render(
<div>
<p>Header</p>
<ErrorBoundary FallbackComponent={Fallback}>
<Bomb />
</ErrorBoundary>
</div>
);
expect(screen.getByRole("alert").textContent).toContain("boom");
expect(screen.getByText("Header")).toBeTruthy();
});getByRole and getByText throw if nothing matches, so the assertions fail on their own when the fallback or header is missing.
Test recovery
Bomb reads a module-level flag, so the test can make the failure go away before the user clicks the retry button. This models a real cause such as a network error that has since cleared.
test("recovers after the user clicks Try again", async () => {
const user = userEvent.setup();
render(
<ErrorBoundary FallbackComponent={Fallback}>
<Bomb />
</ErrorBoundary>
);
expect(screen.getByRole("alert")).toBeTruthy();
shouldThrow = false;
await user.click(screen.getByRole("button", { name: "Try again" }));
expect(screen.getByText("Recovered")).toBeTruthy();
expect(screen.queryByRole("alert")).toBeNull();
});If you only click the button while shouldThrow is still true, the boundary resets, Bomb throws again, and the fallback comes straight back. That is a useful second test: it confirms a failed retry doesn't leave the app in a broken state.
Test reporting
Pass a mock to the boundary's onError prop and check what it receives. With a hand-written class boundary, spy on whatever logging function componentDidCatch calls instead.
test("reports the error with a component stack", () => {
const onError = vi.fn();
render(
<ErrorBoundary FallbackComponent={Fallback} onError={onError}>
<Bomb />
</ErrorBoundary>
);
expect(onError).toHaveBeenCalledTimes(1);
const [error, info] = onError.mock.calls[0];
expect(error.message).toBe("boom");
expect(info.componentStack).toContain("Bomb");
});Test errors from event handlers
Errors from handlers reach a boundary only if your code sends them there. Test that wiring by making the async call fail and waiting for the fallback. Use findByRole, which waits, because the rejection resolves after the click.
import { 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("sends a failed save to the boundary", async () => {
const user = userEvent.setup();
const save = vi.fn().mockRejectedValue(new Error("save failed"));
render(
<ErrorBoundary FallbackComponent={Fallback}>
<SaveButton save={save} />
</ErrorBoundary>
);
await user.click(screen.getByRole("button", { name: "Save" }));
const alert = await screen.findByRole("alert");
expect(alert.textContent).toContain("save failed");
});Exercise
A test renders a boundary around a component that throws, then asserts that the fallback appears. The assertion passes, but the test output is full of error stack traces. What causes this, and how do you fix it without hiding real failures in other tests?
Show answer
React logs caught errors to console.error, and jsdom can log them again as uncaught errors. Mock console.error with vi.spyOn(console, "error").mockImplementation(() => {}) in beforeEach, and call vi.restoreAllMocks() in afterEach so other tests keep their normal console output.