javascript - 如何使用 Jest 和新的 React lazy 16.6 API 测试快照
问题描述
lazy
我必须使用新的 React 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>, + ]
那么,最好的方法是什么?
解决方案
我必须用 包装每个测试套件<Suspense>
吗?
是的,该
Suspense
组件是延迟加载子组件所必需的,特别是在延迟组件可用时提供回退和协调。
导出Component1
和Component2
输入,CustomComponent
以便可以在测试中导入它们。
import React, {PureComponent, lazy} from 'react';
export const Component1 = lazy(() => import('./Component1'));
export const Component2 = lazy(() => import('./Component2'));
export default class CustomComponent extends PureComponent {
//...
}
请记住,延迟加载的组件类似于 Promise。在测试中导入它们,并等待它们解决,然后再检查快照是否匹配。
import { create } from 'react-test-renderer';
import React, {Suspense} from 'react';
import CustomComponent, {Component1, Component2} from './LazyComponent';
describe('CustomComponent', () => {
it('rendered lazily', async()=> {
const root = create(
<Suspense fallback={<div>loading...</div>}>
<CustomComponent/>
</Suspense>
);
await Component1;
await Component2;
expect(root).toMatchSnapshot();
})
})
推荐阅读
- callback - 将回调转换为客户端回调
- python - 创建新类实例时,如何在 Python 中的任何其他类方法之前自动运行类的一个方法
- android - 使用 webview 拍照/拍照
- neo4j - neo4j cyper 使用 UNWIND 在单个查询中删除和更新关系
- html - 使用flex-direction作为列时如何使flexbox利用空白空间
- xmonad - 无法在连接的显示器上设置 xmobar
- python - 如何检查 Scikit-Learn Pipeline 所做的更改?
- python - 正则表达式匹配不包含符号的单词
- html - 使用数据/图像的 css 在浏览器中不起作用
- windows - 禁用 Hyper-V - 有什么方法可以进行 2 次引导登录