javascript - 如何使用 Jest 和新的 React lazy 16.6 API 测试快照

标签 javascript reactjs unit-testing jestjs react-test-renderer

我必须使用新的 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.

导出 Component1Component2CustomComponent以便它们可以在测试中导入。

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/

相关文章:

JavaScript 模块模式与示例

reactjs - Express cors 不允许凭据

python - 使用 pytest 和 Flask 模拟 auth 装饰器

javascript - 清除ajax调用上的图表数据

javascript - js 正则表达式匹配以 X 开头而不是 Y 开头的路径

javascript - 如何设计 react 选择组件的箭头样式?

android - Robolectric getResources() 抛出 RuntimeException (Android)

angularjs - Jasmine 提示返回 Promise 的函数上出现 ".then is not a function"

javascript - Reactjs 中使用 JSX 的安全导航运算符

javascript - 如何在谷歌地图上平移时保持下拉菜单和按钮固定