代码之家  ›  专栏  ›  技术社区  ›  3Dos

反应路由器:用酶在“渲染”道具内测试

  •  4
  • 3Dos  · 技术社区  · 6 年前

    我想测试从 / 区域设置路径的路径(例如 /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)
    })
    

    显然,测试失败,因为重定向组件作为 render 支持 Route

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

    但即使在路由组件中拆分了路由,我也不知道如何在 提供 支柱。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Abdulrahman Sulaiman    6 年前

    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>

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