我必须使用新的 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>, + ]
那么,哪种方法最好呢?
最佳答案
我是否必须用 <Suspense>
包装每个测试套件? ?
Yes, the
Suspense
component is neccessary for lazily loading child components, particularly providing a fallback and for reconciliation when the lazy components are available.
导出 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();
})
})
关于javascript - 如何使用 Jest 和新的 React lazy 16.6 API 测试快照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53189059/