3Dos
3Dos

Reputation: 3487

React-router: testing inside the `render` prop with enzyme

I'd like to test a redirection from the / path to a locale path (e.g. /en). So here's what the component looks like:

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

And this is the current testing function:

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

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

Obviously, the test fails as the Redirect component is inside a child as a function as the render prop to the Route

In the test, I wrap the App in a memory router but in the App component, a browser router is already present so I might need to refactor that.

But even with the routes splitted in a Routes component, I don't know how to test inside the render prop.

Upvotes: 5

Views: 3158

Answers (1)

Abdulrahman Sulaiman
Abdulrahman Sulaiman

Reputation: 38

You can test this by checking the component that should be rendered after the redirection, in this case the Home component like this:

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

I had to remove <Router> to get this working since we're not using it for the browser. Another way of doing this is to check the <Route> pathname property within the location prop. see here:

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

Upvotes: 2

Related Questions