解决React Lazy组件以进行React Router测试

时间:2019-02-13 20:03:29

标签: reactjs react-router jestjs lazy-loading

我在Jest测试React惰性组件时遇到问题。惰性组件不会解析为React组件,而是惰性对象,因此会引发Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.错误。我该如何解决它们,以便它们可以作为测试的要素?我的设置如下。

我正在使用React-Router和Redux。尝试测试某些组件随每条路线出现。

测试包装器功能的设置如下:

const mountWithPath = async (path, newProps = {}) => {
    const wrapper = mount(
        <MemoryRouter initialEntries={[path]}>
            <Provider store={store}>
                <Suspense fallback={<div />}>
                    <CompAppNoRouter {...modProps} />
                </Suspense>
            </Provider>
        </MemoryRouter>
    );
    await People;
    await DashboardPage;
    await ActivityPage;
    await Analysis;
    await Upload;
    return wrapper;

将延迟加载的组件导入到测试中:

import { People, DashboardPage, ActivityPage, Analysis, Upload } from '../app';

从app.jsx导出:

export const People = lazy(() => import('./pages/people/people'));
export const DashboardPage = lazy(() => import('./pages/dashboard/dashboard'));
export const ActivityPage = lazy(() => import('./pages/activity-report/activity-report'));
export const Analysis = lazy(() => import('./pages/analysis/analysis'));
export const Upload = lazy(() => import('./pages/upload'));

1 个答案:

答案 0 :(得分:1)

即使我也是React的新手,但我绝对可以说不需要 让aysnc / await处理悬念组件。

const SomeMemoryFunction = (path, newProps) => {
// sry for redefining a function with same parameter 
// and I don't have idea about passing newProps explicitly
// but pls refer the given blog for clear view.
  return = modProps => (
      <MemoryRouter initialEntries={[path]}>
          <Provider store={store}>
              <Suspense fallback={<div />}>
                  <CompAppNoRouter {...modProps} />
              </Suspense>
          </Provider>
      </MemoryRouter>    
  )  
}

const mountWithPath = (path, newProps = {}) => {
  const wrapper = SomeMemoryFunction(path, newProps);

   Analysis;
   Upload;
  return wrapper;
}

如果您仍然对这个概念有疑问,我强烈建议您阅读 blog