Search code examples
reactjsjestjsreact-router-domreact-testing-library

Testing navigation with react-testing-library


I want to test if a sidebar that I have created for navigation works or not, this is a simple example of what I have made

<ul>
  <li><Link to="/location1">location 1</Link></li>
  <li><Link to="/location2">location 2</Link></li>
</ul>

this is my test

const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>

// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})

it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})

When I test the navigation with RTL, first test runs fine, but after that the location remains at that directory for next test, how do I clear location after every test? or any suggestions how should I test navigation?


Solution

  • Well I did figure it out, we can use <MemoryRouter> for this purpose. https://reactrouter.com/docs/en/v6/api#memoryrouter

    Just passed the value ['/'] to initialEntries prop from <MemoryRouter> and tests work fine.

    also slideshowp2 answer is very useful if you are interested