我的应用程序从 中获取API,然后呈现数据。如果输入了不存在的值,则error boundary触发并捕获错误。
我正在ErrorBoundary从react-error-boundary图书馆和图书馆QueryErrorResetBoundary使用react-query。
使用我的React-Error-Boundary设置,我的应用程序在发生error boundary事件时有一个触发器,error并且能够error通过重置从state. 我目前对发生事件error boundary时的触发进行了通过测试error。现在我想测试是否error boundary可以从 triggererror boundary和 reset中恢复state。请让我知道如何使用Jestand来解决这个问题React Testing Library。
应用组件
const ErrorFallback = ({ error, resetErrorBoundary }) => {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre style={{ color: "red" }}>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
};
const App = () => {
const [idQuery, setIdQuery] = useState(0);
return (
<div>
<QueryErrorResetBoundary>
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
setIdQuery(0);
}}
resetKeys={[idQuery]}
>
<Home idQuery={idQuery} setIdQuery={setIdQuery} />
</ErrorBoundary>
</QueryErrorResetBoundary>
<ReactQueryDevtools initialIsOpen={true} />
</div>
);
};
应用程序.test.js
const App = () => {
const [state, setState] = useState(0)
return (
<QueryErrorResetBoundary>
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
setState(0);
}}
resetKeys={[state]}
>
<Child />
</ErrorBoundary>
</QueryErrorResetBoundary>
)
}
const Child = () => {
throw new Error()
}
describe("Error Boundary", () => {
beforeEach(() => {
render(
<App />
);
});
it("should trigger the Error Boundary when an error occurs", () => {
const errorMessage = screen.getByTestId("error-boundary-message");
expect(errorMessage).toBeInTheDocument();
});
it("should recover from Error Boundary", () => {
// ???
})
});