我试图通过创建一个按钮(测试库中的代码是否显示)来测试一个React边界(使用react-error-boundary库),当单击时,我想验证错误文本是否显示,下面是一些屏幕截图


以下是所使用的两个文件:
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;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();
});附加Jest错误日志。我不确定哪一种是正确的方法来处理这个问题,我是否应该期望Jest会出错呢?如果希望在单击按钮时抛出错误,我如何添加它?
● Console
console.error
Error: Uncaught [Error: This is a test error]发布于 2022-05-17 20:23:53
在这里找到答案
it("react boundary works", async () => {
const { getByText } = render(<ErrorFallbackTest />);
const buttonTrigger = getByText(buttonText);
const spy = jest.spyOn(console, "error");
spy.mockImplementation(() => {});
fireEvent(buttonTrigger, new MouseEvent("click", { bubbles: true }));
const boundaryText = getByText("Error displaying this section");
expect(boundaryText).toBeInTheDocument();
expect(boundaryText).toBeDefined();
expect(boundaryText).toBeVisible();
spy.mockRestore();
});https://stackoverflow.com/questions/72280076
复制相似问题