Tested for react-router-dom v6
Based on @Freez 's answer, I implemented a recursive function that returns a correct url map even if you are using nested routes.
You just need to add this once in setupTests.js for jest tests to be able to use it in any test:
function recursiveGetPathMap(route, parentPath){
let pathMap = {};
const routeProps = route.props();
let path = parentPath + (parentPath.length == 0 || parentPath[parentPath.length-1] == '/' ? '' : '/') + routeProps.path;
pathMap[path] = routeProps.element.type;
route.children(Route).forEach(el=>{
pathMap = {...pathMap, ...recursiveGetPathMap(el, path)};
});
return pathMap;
}
global.getPathMap = (wrapper)=>{
let pathMap = {};
wrapper.find(Routes).children(Route).forEach(el =>{
pathMap = {...pathMap, ...recursiveGetPathMap(el, "")};
});
return pathMap;
}
Example:
App.js
...
<Routes>
<Route path="/" element={<Layout/>}>
<Route path="users" element={<Users/>}>
<Route path=":name" element={<Profile/>}/>
</Route>
</Route>
</Routes>
...
App.test.js
...
it('whatever', ()=>{
const component = <App/>;
const wrapper = shallow(component);
const pathMap = getPathMap(wrapper);
expect(pathMap['/']).toBe(Layout);
expect(pathMap['/users']).toBe(Users);
expect(pathMap['/users/:name']).toBe(Profile);
});
...
The output of console.log(pathMap)
in that example is:
{
'/': [Function: Layout],
'/users': [Function: Users],
'/users/:name': [Function: Profile]
}
Note that if you have a route without path (index route):
<Route index element={<SomeComponent/>}/>
the route will be like /somepath/somepath/undefined