reactjs - 使用 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) 中呈现时抛出错误错误:未捕获错误:错误...
解决方案
我怀疑它不能像React 文档中所述那样工作,因为它的工作方式throws()
类似于try/catch
并且只能处理命令式代码。
相比之下,<ShopStatsConsumer />
命令式代码...
推荐阅读
- reactjs - 将 react-draft-wyswig 连接到 redux-form
- carousel - 是否可以仅在鼠标悬停时防止 Bootstrap 轮播播放?
- php - 在更高的计算机配置 PHP 中执行时间不会减少
- typescript - 如何不使用打字稿复制代码?
- javascript - 纯 JavaScript - for 循环适用于元素 [0] 但不适用于元素 [i]
- postgresql - 使用 WAL 进行主从复制:Postgres uuid_generate_v4() 生成主键
- react-native - 为什么Android App在带有后退按钮React Native Navigation的应用程序中显示空白屏幕?
- c++ - 调用 clear() 后,vector 的元素仍然可以引用吗?
- vala - 使用 Vala 的默认应用程序打开文件?
- java - 使用 lambda 的可运行线程