如何测试 React Loadable 组件

Alb*_*ivé 7 unit-testing reactjs jestjs enzyme react-loadable

我有这个组件:

import React from 'react';

const UploadAsync = Loadable({
  loader: () => import('components/Upload'),
  loading: () => <LoadingComponent full />
});

const Component = () => {
  return <UploadAsync />
}

export default Component
Run Code Online (Sandbox Code Playgroud)

和测试:

import React from 'react';
import Component from './index';

describe('Component', () => {
  it('should render correctly with upload component', () => {
    const tree = create(<Component />).toJSON();

    expect(tree).toMatchSnapshot();
  });
});
Run Code Online (Sandbox Code Playgroud)

如何在快照中看到上传组件而不是加载组件?

exports[`Content should render correctly with form component 1`] = `
  <div>
    <Loading
      full={true}
    />
  </div>
`;
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过setTimeOutPromises

小智 9

Loadable.preloadAll()在测试之前使用然后您可以访问您需要的组件。

文档

简单的例子:

all imports here

Loadable.preloadAll()

describe('TestName', () => {
 //tests
})

Run Code Online (Sandbox Code Playgroud)


小智 0

似乎没有正确的解决方案,但如果您的测试实际上是在 iframe 内的浏览器中渲染组件,那么您可以通过 Jquery contentDocument 获取您的 React 组件

$('#component-iframe')[0].contentDocument
Run Code Online (Sandbox Code Playgroud)

您可以使用类或 id 查找组件中的某些特定元素

$('#component-iframe')[0].contentDocument.getElementById('componentID')
Run Code Online (Sandbox Code Playgroud)