英文:
React Testing Library render does not work with react router dom Navigate
问题
我有一个组件,里面包含一个名为"Navigate"的组件。我想测试这个导航功能。但每当我尝试渲染这个组件时,测试用例都会卡住,一直运行下去。
我正在使用react-router-dom v6。
这是我的示例代码片段。
render(
<MemoryRouter initialEntries={['/']}>
<Navigate to="/target" />
</MemoryRouter>,
);
我尝试过使用enzyme的mount
方法和RTL的render
方法,但这段代码从未产生任何输出。测试一直在无限执行。
英文:
I have a component which has a "Navigate" component inside it. I want to test this navigation. But whenever I try to render the component, the test case gets stuck and keeps on running forever.
I am using react-router-dom v6.
This is my sample code snippet.
render(
<MemoryRouter initialEntries={['/']}>
<Navigate to="/target" />
</MemoryRouter>,
);
I have tried both mount
method from enzyme and render
method from RTL. This code snippet never produces any output. The test keep on executing forever.
答案1
得分: 0
测试代码无条件地渲染了 Navigate
组件,该组件会触发导航操作。这会创建一个渲染循环。
将 Navigate
组件放置在一个路由上,以便它被有条件地渲染。
示例:
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<Navigate to="/target" />} />
</Routes>
</MemoryRouter>,
);
上面的 Navigate
组件在 MemoryRouter
的 initialEntries
数组属性值中指定的主页 "/"
上进行了渲染。
英文:
The test code is unconditionally rendering the Navigate
component which issues a navigation action. This creates a render loop.
Place the Navigate
component on a route so that it is conditionally rendered.
Example:
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<Navigate to="/target" />} />
</Routes>
</MemoryRouter>,
);
Above the Navigate
component is rendered on the home "/"
that is specified in the MemoryRouter
's initialEntries
array prop value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论