reactjs - React 测试库、动态导入和 React Router DOM 总是渲染未找到的组件
问题描述
我在测试简单导航时遇到了一些麻烦,
我有一个使用 react-router-dom 的反应应用程序,并且应用程序组件被悬念包裹着。
我还动态导入我的组件以便能够进行代码拆分。
出于某种原因,在单元测试中,当我从主页触发点击导航关于链接时。
它总是呈现 404 NotFound 组件,而不是存在的 about 组件
我做错了什么?
主.js
const Main = () => <h1>Home page</h1>;
关于.js
const About = () => <h1>About page</h1>;
NotFound.js
const NotFound = () => <div>404 this page does not exist</div>;
导航.js
const Nav = () => (
<div className="dummy-nav">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</div>
);
应用程序.js
import React, { Component, Suspense, lazy } from "react";
import { Switch, Route } from "react-router-dom";
import Nav from "./Nav";
const Main = lazy(() => import(/* webpackChunkName: "Main" */ "./Main"));
const About = lazy(() => import(/* webpackChunkName: "About" */ "./About"));
const NotFound = lazy(() =>
import(/* webpackChunkName: "About" */ "./NotFound")
);
class App extends Component {
render() {
return (
<Suspense fallback={<div>Loading...</div>}>
<div>This is the App</div>
<Nav />
<Switch>
<Route exact path="/" component={Main} />
<Route path="/about" component={About} />
<Route render={() => <NotFound />} />
</Switch>
</Suspense>
);
}
}
app.test.js
function renderWithRouter(
ui,
{
route = "/",
history = createMemoryHistory({ initialEntries: [route] }),
...renderOptions
} = {}
) {
// eslint-disable-next-line react/prop-types
function Wrapper({ children }) {
return <Router history={history}>{children}</Router>;
}
return {
...render(ui, { wrapper: Wrapper, ...renderOptions }),
history
};
}
test("renders homepage by default and can navigate to about", async () => {
renderWithRouter(<App />);
screen.getByText(/Home page/i);
const link = screen.getByRole("link", { name: /About/i });
userEvent.click(link);
await waitFor(() => screen.getByText(/About page/i));
screen.debug();
});
这是一个代码沙箱,其中包含我正在使用的损坏测试和应用程序结构,如果您有任何使用和测试惰性和动态导入的技巧,请分享
https://codesandbox.io/s/react-router-suspense-lrnp7?file=/src/App.js
解决方案
react-router-dom v6
如果你想使用,你应该使用history v5.x
.
推荐阅读
- visual-studio-code - Visual Studio Code SASS 编译器
- r - 找不到签名“tbl_df”的函数“坐标”的继承方法
- javascript - 如何在不使用 UI 的情况下检查 yahoo 邮件收件箱?
- r - Zeppelin,livy sparkr 显示变量不起作用
- mysql - 如何循环更新语句以更新所有可能的唯一组合?
- ansible - 在 Ansible 中,有没有办法在循环范围函数中使用 loop_controls index_var
- html - 如何在 CSS 中设置动画时间?
- winapi - WinAPI Region 没有意义吗?
- python - 两个张量在同一个设备上,但我收到错误:预期所有张量都在同一个设备上,但找到至少两个设备,cuda:0 和 cpu
- java - 使回收站视图可垂直滚动