【问题标题】:React-router: testing inside the `render` prop with enzymeReact-router:使用酶在“渲染”道具内部进行测试
【发布时间】:2018-12-17 01:40:58
【问题描述】:

我想测试从/ 路径到语言环境路径(例如/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 组件作为 render 到 Route 的函数在子组件内

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

但即使在 Routes 组件中拆分路由,我也不知道如何在 render 属性中进行测试。

【问题讨论】:

    标签: javascript reactjs react-router jestjs enzyme


    【解决方案1】:

    您可以通过检查重定向后应呈现的组件来测试这一点,在本例中为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)
    })
    

    我必须删除 &lt;Router&gt; 才能使其正常工作,因为我们没有将它用于浏览器。另一种方法是检查 location 属性中的 &lt;Route&gt; 路径名属性。看这里:

    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")
    })
    

    【讨论】:

    • 与此同时,我将整个开关提取到 Routes.js 组件中以便于测试,而您的第一个解决方案完全解决了我的问题。非常感谢!
    猜你喜欢
    • 2020-03-12
    • 2019-01-10
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2019-03-23
    • 2016-08-06
    相关资源
    最近更新 更多