如何在Jest / React测试库中编写单元测试,以使用npm库react-error-boundary测试React的错误边界是否正常工作?例如。
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()
})
})那么我该如何完成这项工作呢?还是我走错了方向?
发布于 2021-10-11 21:14:10
我不确定这对测试第三方组件库是否有意义,但你总是可以制作一个总是抛出以下异常的哑巴组件:
const ComponentThatThrows = () => { throw new Error(''); };
render(<ErrorBoundary FallbackComponent={ErrorFallback}>
<ComponentThatThrows />
</ErrorBoundary>)
expect(screen.getByText("There was an error!")).toBeInTheDocument()如果我误解了,你想专门测试TopLevelComponent而不是ErrorBoundary,你需要弄清楚它必须在什么条件下抛出并重现那个条件(例如,“单击initiates fetch(),然后出现拒绝”或类似的情况)。
当时在酶(.simulateError())中模拟错误很方便,但就像直接调用wrapper.setState()一样脆弱-我们的测试仍然可能通过,但在真正的代码中,可能不可能达到这种情况。
https://stackoverflow.com/questions/69531002
复制相似问题