【发布时间】:2021-07-28 06:48:23
【问题描述】:
我的应用程序从API 获取数据,然后呈现数据。如果输入了不存在的值,则error boundary 触发并捕获错误。
我正在使用来自react-error-boundary 库的ErrorBoundary 和来自react-query 库的QueryErrorResetBoundary。
使用我的React-Error-Boundary 设置,当error 发生时,我的应用程序有一个error boundary 触发器,并且能够通过重置state 从error 中恢复。当error 发生时,我目前对error boundary 触发进行了通过测试。现在我想测试error boundary 是否可以从触发的error boundary 中恢复并重置state。请让我知道如何使用 Jest 和 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>
);
};
App.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", () => {
// ???
})
});
【问题讨论】:
标签: reactjs jestjs react-hooks react-testing-library react-error-boundary