首页 > 解决方案 > 使用 testing-library 进行测试时,无法捕获 React 组件内引发的错误

问题描述

要测试的组件

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();
});

结果

测试失败:✖ 未在 Chrome Headless 87.0.4272.0 (Mac OS 11.0.0) 中呈现时抛出错误错误:未捕获错误:错误...

标签: reactjsunit-testingreact-testing-library

解决方案


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

相比之下,<ShopStatsConsumer />命令式代码...


推荐阅读