在酶测试中改变MemoryRouter中的路径路径

时间:2018-03-26 15:08:48

标签: reactjs enzyme

我正在尝试通过在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订阅历史记录更改。

1 个答案:

答案 0 :(得分:0)

您可以将基础<Route>组件与自定义history对象一起使用。

首先,安装history软件包(如果仅在测试中使用,则安装到devDevpendency)。

在您的测试文件中:

// 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