gpt4 book ai didi

reactjs - 为 React Router 测试解决 React Lazy Components

转载 作者:行者123 更新时间:2023-12-04 17:40:35 27 4
gpt4 key购买 nike

我在使用 Jest 测试 React 惰性组件时遇到问题。惰性组件不解析为 React 组件,而是惰性对象,因此它抛出 Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) ) 但得到: 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;

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

从 '../app' 导入 { People, DashboardPage, ActivityPage, Analysis, Upload};

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

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

关于reactjs - 为 React Router 测试解决 React Lazy Components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54678544/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com