首页 > 解决方案 > 如何使用 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>, + ]

那么,最好的方法是什么?

标签: javascriptreactjsunit-testingjestjsreact-test-renderer

解决方案


我必须用 包装每个测试套件<Suspense>吗?

是的,该Suspense组件是延迟加载子组件所必需的,特别是在延迟组件可用时提供回退和协调。

导出Component1Component2输入,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();
  })
})

推荐阅读