【问题标题】:Changing route path in MemoryRouter in Enzyme tests在酶测试中更改 MemoryRouter 中的路由路径
【发布时间】:2018-09-04 19:02:45
【问题描述】:

我正在尝试测试一个组件,该组件通过在 Enzyme 中创建一个包装器来侦听正在更改的历史记录,该包装器将我的组件放在 MemoryRouter 中;即:

mount(
  <MemoryRouter initialEntries={'/path/param1}>
    <Switch>
      <Route
        path="/path"
        component={MyComponent}
      />
  </Switch>
</MemoryRouter>
)

对于初始路径,这可以正常工作,但是,我特别想测试当它以 /path/param1 开头但随后历史记录更改为 /path/param2 时会发生什么

通过使用withRouter 包装组件的导出来完成对路径的监控,如下所示:

export default withRouter(MyComponent)

然后在构建时,我使用history.listen 订阅历史更改。

【问题讨论】:

    标签: reactjs enzyme


    【解决方案1】:

    您可以使用带有自定义 history 对象的基本 &lt;Route&gt; 组件来执行此操作。

    首先,安装history 包(如果您只在测试中使用它,则安装到 devDevpendencies)。

    在您的测试文件中:

    // we are using memory history only
    import { createMemoryHistory } from 'history';
    import { Router, Route} from 'react-router-dom';
    

    然后,像这样设置您的组件:(如果只有一条路线,您可以删除 Switch

    const history = createMemoryHistory({
      initialEntries: ['/path/param1'],
    });
    
    // mount with custom history object
    mount(
      <Router history={history}>
        <Route
          path="/path"
          component={MyComponent}
        />
      </Router>
    )
    

    稍后在您的测试中,您可以在组件执行完操作后检查history 的当前位置。

    // check current path has been changed
    expect(history.entries[0].pathname).to.eq('/path/param2');
    

    您可以在此处找到通过history 访问的所有其他内容: https://github.com/ReactTraining/history

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 2021-04-18
      • 2016-09-01
      • 2017-05-22
      • 2018-02-04
      • 2010-10-17
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多