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'));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With