我的应用程序从API中获取,然后呈现数据。如果输入一个不存在的值,则error boundary将触发并捕获错误.
我使用的是来自react-error-boundary库的QueryErrorResetBoundary和来自react-query库的QueryErrorResetBoundary。
使用我的React-Error-Boundary设置,我的应用程序在发生error时有一个error boundary触发器,并且能够通过重置state从error中恢复。目前,我已经对发生error boundary时触发的error进行了一个通过测试。现在,我想测试一下error boundary是否可以从触发的error boundary和重置state中恢复。请让我知道如何使用Jest和React Testing Library。
App组件
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", () => {
// ???
})
});发布于 2021-05-05 23:55:59
在不知道你到底想做什么的情况下,我怀疑像这样的事情可能会帮助你开始:
const App = () => {
const [isRecovered,setIsRecovered] = useState(false)
return (
<QueryErrorResetBoundary>
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
setIsRecovered(true)
}}
resetKeys={[isRecovered]}
>
<Child isRecovered={isRecovered} />
</ErrorBoundary>
</QueryErrorResetBoundary>
)
}
const Child = ({isRecovered}) => {
if(!isRecovered) throw new Error();
return 'All Good';
}至少您可以将ErrorBoundary的代码添加到您的问题中。
https://stackoverflow.com/questions/67409901
复制相似问题