Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve React Lazy Components for React Router test

I am having a problem with Jest testing React lazy components. The lazy components do not resolve to React components and instead are the lazy objects, so it throws the Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. error. How do I have them resolve so that they can be elements to test? My setup is below.

I am using React-Router and Redux. Trying to test that certain components show up with each route.

Test wrapper function is setup like so:

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;

With the lazy loaded components imported into the test:

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

From the export of 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'));
like image 673
Chad Avalon Avatar asked Aug 02 '26 01:08

Chad Avalon


1 Answers

Even Through I am also new to React but I definitely can say that there is not need for aysnc/await to handling the suspense component.

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;
}

If you still face some issues with this concept, I highly recommend to read this blog

like image 158
jawahar Avatar answered Aug 05 '26 13:08

jawahar