【问题标题】:How to Test React's Error Boundary using Jest and React Testing Library如何使用 Jest 和 React 测试库测试 React 的错误边界
【发布时间】: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


【解决方案1】:

我不确定测试 3rd 方组件库是否有意义,但你总是可以制作一个总是抛出的愚蠢组件:

    const ComponentThatThrows = () => { throw new Error(''); };
    render(<ErrorBoundary FallbackComponent={ErrorFallback}>
      <ComponentThatThrows />
    </ErrorBoundary>)

    expect(screen.getByText("There was an error!")).toBeInTheDocument()

如果我误解了并且您想专门测试TopLevelComponent 而不是ErrorBoundary,您需要弄清楚它必须在什么条件下抛出并重现该条件(例如“点击启动 fetch() 并且有一个拒绝”或类似的)。

当时在 Enzyme(.simulateError()) 中模拟错误很方便,但与直接调用 wrapper.setState() 一样脆弱 - 我们的测试仍然可能通过,但在实际代码中可能无法达到这种情况。

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2020-03-24
    • 2019-04-22
    • 2021-06-14
    • 2021-06-04
    • 2020-06-14
    • 2020-06-01
    • 2021-09-20
    • 2021-07-27
    相关资源
    最近更新 更多