我必须使用新的 React lazy
API (16.6) 导入组件。
import React, {PureComponent, lazy} from 'react';
const Component1 = lazy(() => import('./Component1'));
const Component2 = lazy(() => import('./Component2'));
class CustomComponent extends PureComponent {
...
render() {
return (
<div>
<Component1 />
<Component2 />
</div>
);
}
}
在我的测试中,我正在做这个组件的快照。这是一个非常简单的测试:
import { create } from 'react-test-renderer';
const tree = await create(<CustomComponent />).toJSON();
expect(tree).toMatchSnapshot();
在日志中,测试失败并出现以下错误:
A React component suspended while rendering, but no fallback UI was specified.
Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.
我是否必须用 <Suspense>...
包装每个测试套件?
it('should show the component', async () => {
const component = await create(
<React.Suspense fallback={<div>loading</div>}>
<CustomComponent />
</React.Suspense>
);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
};
如果这样做,我只会在快照中看到 fallback
组件。
+ Array [ + <div> + loading + </div>, + ]
那么,哪种方法最好呢?
原文由 Albert Olivé Corbella 发布,翻译遵循 CC BY-SA 4.0 许可协议
我是否必须用
<Suspense>
包装每个测试套件?导出
Component1
和Component2
CustomComponent
以便它们可以在测试中导入。请记住,延迟加载的组件是类似 promise 的。在测试中导入它们,并在检查快照是否匹配之前等待它们解析。