我已经使用新的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>, + ]
那么,哪种方法是最好的呢?
await
行之后调用toJSON
了吗?我猜你是在未解决的组件上调用了toJSON
,而await
得到了这个结果,而不是等待CustomComponent
被解决。 - Andreas Köberleconst component = await create(loading
+ Array [ +
+ loading
+ ,
+ ]
- Albert Olivé Corbella