reactjs - 为 React Router 测试解决 React Lazy Components
问题描述
我在 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'));
解决方案
即使我也是 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;
}
如果您仍然面临这个概念的一些问题,我强烈建议您阅读此 博客
推荐阅读
- python - 找到一个变量的最大值和最小值并找到对应的值
- r - 如何在R中的同一数据框中合并2列
- android - 如何从另一个类更新片段的用户界面?
- css - 如何在现有的圆形边框周围创建多个边框
- authentication - 带有 IAuthenticationSchemeProvider 的 IdentityServer4 的动态方案 SAML 2.0
- javascript - 这是有效的自动分号插入吗?
- php - 使用公平槽策略从队列中获取下一个任务
- java - Spring 中具有服务器端处理的 JQuery DataTables(使用 Java 和 Thymeleaf)
- ios - 一些 gif 占用了太多内存
- javascript - 如何检查用户是否已登录并更改 routerlink 值