为React Router测试解析React Lazy Components

问题描述 投票:1回答:1

我遇到了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'));
reactjs react-router jestjs lazy-loading
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.