如何使用 MemoryRouter 和 Jest 设置匹配路径? (不是位置或历史)

Posted

技术标签:

【中文标题】如何使用 MemoryRouter 和 Jest 设置匹配路径? (不是位置或历史)【英文标题】:How can you set path of match with MemoryRouter and Jest? (not location or history) 【发布时间】:2018-01-17 09:50:49 【问题描述】:

如有重复请见谅。

我知道 MemoryRouter 有 initialEntries 和 initialIndex,所以你可以为“位置”和“历史”设置路径等。但是“匹配”没有更新......我需要为我的反应应用程序和 Jest 测试设置“匹配”。

当我尝试时,

<MemoryRouter initialEntries=['/hello'] initialIndex=0>
      <Hello store=store />
</MemoryRouter>

我得到了

match:  path: '/', url: '/', params:  ... ,
location:  path: '/hello', pathname: '/', ... ,
history:  ..., location:  path: '/hello', pathname: '/', ... 

我想知道是否有办法设置匹配。提前致谢。

【问题讨论】:

您能提供您的整个文件示例吗?在这里浪费了一整天,但没有解决办法。 【参考方案1】:

您可以用&lt;Route ... /&gt; 组件包装您的&lt;Hello store=store /&gt; 组件,例如:

import React from 'react';
import  MemoryRouter, Route  from 'react-router-dom';

// later in tests

<MemoryRouter initialEntries=['/home']>      
  <Route component=props => <HomeComponent ...props /> path="/home" /> 
</MemoryRouter>

那么您应该可以通过props 访问正确的match 对象。

【讨论】:

谢谢!我花了一整天的时间才弄明白。

以上是关于如何使用 MemoryRouter 和 Jest 设置匹配路径? (不是位置或历史)的主要内容,如果未能解决你的问题,请参考以下文章