I'm trying to unit test a React component which generate my app's Routes declaration for react-router-dom.
My code look like this:
import React, { lazy, Suspense } from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import Loading from 'app/components/Loading';
export interface IRoute {
exact?: boolean;
path?: string;
component?: any;
routes?: IRoute[];
}
export const renderRoutes = (routes: IRoute[] = []): JSX.Element => (
<Suspense fallback={<Loading />}>
<Switch>
{routes.map((route: IRoute, i) => {
const Component = route.component;
return (
<Route
key={i}
path={route.path}
exact={route.exact}
render={(props) => <>{route.routes ? renderRoutes(route.routes) : <Component {...props} />}</>}
/>
);
})}
</Switch>
</Suspense>
);
const routes: IRoute[] = [
{
exact: true,
path: '/404',
component: lazy(() => import('./app/errors/NotFound')),
},
{
path: '*',
routes: [
{
exact: true,
path: '/home',
component: lazy(() => import('./app/home/Home')),
},
{
component: () => <Redirect to="/404" />,
},
],
},
];
export default routes;
And my attempt to test it, which fail, look like this:
import React from 'react';
import { Route } from 'react-router-dom';
import routes, { renderRoutes, IRoute } from './routes';
describe('Routes declaration', () => {
it('Render Routes', () => {
const routesComponent = renderRoutes(routes);
assertsRoutes(routes, routesComponent);
});
});
const assertsRoutes = (routes: IRoute[], routesComponent: JSX.Element) => {
routes.forEach((route, i) => {
if (route.routes) {
assertsRoutes(route.routes, routesComponent);
}
const Component = route.component;
expect(routesComponent).toContain(<Route key={i} path={route.path} exact={route.exact} render={(props) => <>{<Component {...props} />}</>} />);
});
};
How can I test that renderRoutes properly generate Route components for all given IRoute?