writing test using react-testing-library and react router v6

Viewed 244

I'm stuck for hours trying to test a simple page, I'm using "react-router-dom": "^6.3.0"

I have this component that I want to test:

const Main: React.FC = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<div>Home</div>}></Route>
        <Route
          path={"about"}
          element={<div>About</div>}
        />
      </Routes>
    </BrowserRouter>
  )
}

export default Main

It worked well, then I have Main.test.tsx

const renderWithRouter = (ui: React.ReactElement, { route = '/' } = {}) => {
  window.history.pushState({}, 'Test page', route)

  return {
    user,
    ...render(ui, { wrapper: BrowserRouter }),
  }
}

describe('Main', () => {
  beforeEach(() => {
    renderWithRouter(<Main />, { route: '/about' })
  })

  test('should land on about page', async () => {
    await screen.findByText('about')
  })
})

but I got this error

Error: Uncaught [Error: You cannot render a <Router> inside another <Router>. You should never have more than one in your app.]

Any clue why?

1 Answers

The error is caused by using the BrowserRouter twice (you both wrapped the Main component and also its content). I would suggest you to remove the BrowserRouter from inside the Main component and instead wrap the root element with it. If the Main component is the root element the result will be this in the index.tsx file:

ReactDOM.render(
 <BrowserRouter>
   <Main />
 </BrowserRouter>,
 document.getElementById("root")
)

Once you did that and removed the BrowserRouter from the Main component you will be good to go and you won't receive that error during the test.

More docs here: https://testing-library.com/docs/example-react-router/

Related