首页 > 解决方案 > React-router:使用酶在“渲染”道具内部进行测试

问题描述

我想测试从/路径到语言环境路径的重定向(例如/en)。所以这是组件的样子:

// GuessLocale is imported from a helper
const App = () => (
<Router>
  <Switch>
    <Route exact path='/' render={() => (
      <Redirect to={`/${guessLocale()}`} />
    )} />
    <Route exact path='/:lang' component={Home} />
  </Switch>
</Router>
)

这是当前的测试功能:

it('redirects to a localed path', () => {
  const wrapper = mount(
    <MemoryRouter initialEntries={['/']}>
      <App />
    </MemoryRouter>
  )

  expect(wrapper.find('Redirect')).toHaveLength(1)
})

显然,测试失败了,因为 Redirect 组件在一个子组件中,作为一个函数作为renderprop 到Route

在测试中,我将应用程序包装在内存路由器中,但在应用程序组件中,浏览器路由器已经存在,因此我可能需要对其进行重构。

但即使将路由拆分为 Routes 组件,我也不知道如何在render道具内部进行测试。

标签: javascriptreactjsreact-routerjestjsenzyme

解决方案


您可以通过检查重定向后应该呈现的组件来测试这一点,在这种情况下,Home组件如下所示:

it('redirects to a localed path', () => {
  let wrapper = mount(
    <MemoryRouter initialEntries={['/']}>
      <Switch>
        <Route exact path='/' render={() => (
          <Redirect to={`/en`} />
        )} />
        <Route path='/en' component={Home} />
        <Route render={() => "not found"} />
      </Switch>
    </MemoryRouter>
  )



  expect(wrapper.find(Home)).toHaveLength(1)
})

<Router>由于我们没有将它用于浏览器,因此我必须删除它才能使其正常工作。另一种方法是检查<Route>location 属性中的 pathname 属性。看这里:

it('redirects to a localed path', () => {
  let wrapper = mount(
    <MemoryRouter initialEntries={['/']}>
      <Switch>
        <Route exact path='/' render={() => (
          <Redirect to={`/en`} />
        )} />
        <Route path='/en' component={Home} />
        <Route render={() => "not found"} />
      </Switch>
    </MemoryRouter>
  )



  expect(wrapper.find("Route").prop('location').pathname).to.equal("/en")
})

推荐阅读