我想知道如何用Jest和RTL测试坏路由和404页面。我试着做了一些示例测试,测试代码看起来像这样:
test('should render page not found when no match route', async () => {
const history = createMemoryHistory()
history.push("/bad/route")
const { getByText } = render(<Router history={history}><App /></Router>)
await waitFor(() => {
expect(getByText(/page that doesn't exist./i)).toBeInTheDocument()
})
})
字符串
App.js(我使用v6 react-router):
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./styles/index.css";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<MainComp />} />
<Route path="#path2" element={<Comp2/>} />
<Route path="#path3" element={<Comp3/>} />
<Route path="#path4" element={<Comp4/>} />
<Route path="*" element={<NoMatch />} />
</Routes>
</Router>
);
}
型
得到这个错误:
● App › should render page not found when no match route
TypeError: Cannot read properties of undefined (reading 'pathname')
27 |
28 | history.push("/bad/route")
> 29 | const { getByText } = render(<Router history={history}><App /></Router>)
| ^
30 |
31 | await waitFor(() => {
32 | expect(getByText(/Oops!/i)).toBeInTheDocument()
at Router (node_modules/react-router/lib/components.tsx:448:5)
at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:16305:18)
at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:20074:13)
at beginWork (node_modules/react-dom/cjs/react-dom.development.js:21587:16)
at beginWork$1 (node_modules/react-dom/cjs/react-dom.development.js:27426:14)
at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:26560:12)
型
CodeSandbox
有人能告诉我怎么做吗?
1条答案
按热度按时间a0x5cqrl1#
我认为你应该在测试MemoryRouter:
字符串
在您使用的版本的路由器的RTL文档中有一个特定的页面:https://testing-library.com/docs/example-react-router/我会尝试模仿它。如果这不起作用,请查看您的实现中有什么不同(如果您需要任何帮助,请分享)。
更新:我认为你不应该把你的browserRouter放在你的应用程序中,而是把你的应用程序 Package 在你的index.js中的BrowserRouter中:
这样我就通过了测试。
或者,如果你真的想你的路由器在你的应用程序组件.你将不得不模仿模块.但我认为这是容易得多.