【问题标题】:Jest: react-router tests returns undefined 'params'开玩笑:react-router 测试返回未定义的“参数”
【发布时间】:2018-12-11 21:35:13
【问题描述】:

我正在尝试使用 MemoryRouter 测试组件,如 React-router 文档中所示,并设置了初始条目,因此我可以在包装的组件中包含参数。

组件示例:

render () {
  console.log(this.props.match.params.item)
}

在应用程序中(工作正常):

<Router>
  <Switch>
    <Route exact path='/' render={() => (
      <Redirect to={`/${guessLocale()}`} />
    )} />
    <Route exact path='/:lang' component={Home} />
    <Route exact path='/:lang/:itemName' component={Vidactic} />
  </Switch>
</Router>

在测试中(从 Enzyme 挂载,匹配未定义):

mount(<MemoryRouter initialEntries={['/fr/pamp']}>
  <Vidactic />
</MemoryRouter>)

所以我使用了这个解决方法,但为什么 initialEntries 不能自行工作?

mount(<MemoryRouter initialEntries={['/fr/pamp']}>
  <Vidactic match={{ params: { item: 'pamp' } }} />
</MemoryRouter>)

【问题讨论】:

    标签: reactjs react-router jestjs enzyme react-router-v4


    【解决方案1】:

    您的测试中没有Route,因此不会发生匹配,并且this.props.match 将未定义Vidactic。添加路线应该使它工作:

    mount(
      <MemoryRouter initialEntries={['/fr/pamp']}>
        <Route exact path="/:lang/:itemName" component={Vidactic} />
      </MemoryRouter>
    );
    

    为避免重复路由,您可能希望将 &lt;Switch&gt;..&lt;/Switch&gt; 部分放在单独的组件中并在测试中使用它。

    【讨论】:

    • 我现在感觉非常愚蠢!感谢您的帮助。
    • 请注意,您的根组件将不再是Vidactic,而是MemoryRouter。显然这可以通过 Enzyme 的 mount 上下文(mount() 的第二个参数)来规避,但这对我不起作用。但是,由于通常不需要访问组件,因此这个答案完全没问题。
    • 你太棒了,谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-11-01
    • 2017-07-13
    • 2018-06-02
    • 1970-01-01
    • 2020-03-13
    • 2018-11-30
    • 2019-09-25
    • 2020-03-17
    相关资源
    最近更新 更多