【发布时间】:2021-11-30 11:41:58
【问题描述】:
如何在 Jest / React 测试库中编写单元测试来测试 React 的错误边界是否使用 npm 库 react-error-boundary 工作正常?例如
const ErrorFallback = ({error}) => <p>There was an error!</p> // can use error.message later
const SimpleComponent = () => <h1>Hello, world</h1>
const TopLevelComponent = () => (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<SimpleComponent />
</ErrorBoundary>
)
所以现在我的测试可能是:
describe("Error Boundary", () => {
test("renders a fallback UI if an error occurs in a child component", () => {
const error = throw new Error("An error occurred")
render(<TopLevelComponent>)
// Somehow throw an error inside of SimpleComponent
SimpleComponent.simulateError()
expect(screen.getByText("There was an error!")).toBeInTheDocument()
})
})
那么我将如何做到这一点?还是我走错了方向?
【问题讨论】:
-
那么你要测试第 3 方库
react-error-boundary吗?如果是,那么这样做几乎没有什么好处,因为包的作者已经这样做了 -
@skyboyer 我认为这过于简单化了。我还没有检查包,但即使他们正在做测试,他们也可能不会测试你的上下文。为您的用例编写测试是一件非常好的事情,我们通过这种方式发现了很多上游问题。
标签: reactjs testing jestjs react-testing-library