5

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.

1 Answer 1

2

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")
})
Sign up to request clarification or add additional context in comments.

1 Comment

In the meantime I extracted the entire switch in a Routes.js component in order to be easily tested and you first solution totally fixed my problem. Thank you very much !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.