【问题标题】:Unable to catch error thrown inside a React component when testing with testing-library使用 testing-library 进行测试时,无法捕获 React 组件内引发的错误
【发布时间】:2020-12-03 10:47:52
【问题描述】:

要测试的组件

function ShopStatsConsumer({ shopId, shopName }) {
  return (
    <ShopStatsContext.Consumer>
      {(context) => {
        if (!(context || {}).state) {
          throw new Error('ERROR');
        }
        return <ShopStats context={context} shopId={shopId} shopName={shopName} />;
      }}
    </ShopStatsContext.Consumer>
  );
}

用业力测试,测试库

it('throws error when not rendered inside a <ShopStatsProvider />', function () {
  const renderConsumer = () => {
    render(<ShopStatsConsumer {...props} />);
  };
  expect(renderConsumer).to.throw();
});

结果

失败的测试: ✖ 未在 a 中渲染时抛出错误 Chrome 无头 87.0.4272.0 (Mac OS 11.0.0) 错误:未捕获错误:错误...

【问题讨论】:

    标签: reactjs unit-testing react-testing-library


    【解决方案1】:

    我怀疑它不能像React docs 中所述那样工作,因为throws() 的工作方式类似于try/catch,并且只能处理命令式代码。

    相比之下,&lt;ShopStatsConsumer /&gt; 是命令式代码...

    【讨论】:

      猜你喜欢
      • 2019-06-14
      • 2021-09-24
      • 2019-07-08
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 2020-09-29
      • 2019-11-11
      相关资源
      最近更新 更多