React Testing Library 的 `render` 不与 React Router DOM 的 `Navigate` 配合工作。

huangapple go评论44阅读模式
英文:

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(
  &lt;MemoryRouter initialEntries={[&#39;/&#39;]}&gt;
    &lt;Navigate to=&quot;/target&quot; /&gt;
  &lt;/MemoryRouter&gt;,
);

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(
  &lt;MemoryRouter initialEntries={[&#39;/&#39;]}&gt;
    &lt;Routes&gt;
      &lt;Route path=&quot;/&quot; element={&lt;Navigate to=&quot;/target&quot; /&gt;} /&gt;
    &lt;/Routes&gt;
  &lt;/MemoryRouter&gt;,
);

上面的 Navigate 组件在 MemoryRouterinitialEntries 数组属性值中指定的主页 &quot;/&quot; 上进行了渲染。

英文:

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(
  &lt;MemoryRouter initialEntries={[&#39;/&#39;]}&gt;
    &lt;Routes&gt;
      &lt;Route path=&quot;/&quot; element={&lt;Navigate to=&quot;/target&quot; /&gt;} /&gt;
    &lt;/Routes&gt;
  &lt;/MemoryRouter&gt;,
);

Above the Navigate component is rendered on the home &quot;/&quot; that is specified in the MemoryRouter's initialEntries array prop value.

huangapple
  • 本文由 发表于 2023年6月6日 01:29:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定