I am trying to test a React error boundary (with react-error-boundary
library) by creating a button (to test that the code inside the library is displayed) and when clicked I want to verify that the error text is displayed, here are some screenshots
Here are the 2 files used:
- error-fallback.tsx
import Box from "@mui/material/Box";
function ErrorFallback({ error }: { error: Error; resetErrorBoundary: () => void }) {
return (
<Box sx={{ textAlign: "center" }}>
<p>Error displaying this section</p>
<pre>{error.message}</pre>
</Box>
);
}
export default ErrorFallback;
- error-fallback.test.tsx
import { render, fireEvent } from "@testing-library/react";
import { ErrorBoundary } from "react-error-boundary";
import Box from "@mui/material/Box";
import { useState } from "react";
import ErrorFallback from "./error-fallback";
const buttonText = "Throw Error";
const errorValue = "This is a test error";
const ThrowError = () => {
throw new Error(errorValue);
};
export const ErrorFallbackTest = () => {
const [error, setError] = useState(false);
const triggerError = () => setError(true);
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<Box sx={{ textAlign: "center" }}>
{error && <ThrowError />}
<button onClick={triggerError}>{buttonText}</button>
</Box>
</ErrorBoundary>
);
};
it("react boundary works", async () => {
const { getByText } = render(<ErrorFallbackTest />);
const buttonTrigger = getByText(buttonText);
fireEvent(buttonTrigger, new MouseEvent("click", { bubbles: true }));
const boundaryText = getByText("Error displaying this section");
expect(boundaryText).toBeInTheDocument();
expect(boundaryText).toBeDefined();
expect(boundaryText).toBeVisible();
});
Attaching Jest error log. I am not sure which is the proper way to handle this, should I expect an error with Jest? How can I add it if the error is expected to be thrown on button click?
● Console
console.error
Error: Uncaught [Error: This is a test error]