Component tests for apps that use React Router v5
- src/App.spec.js shows basic routing
- src/Nesting.spec.js shows two level of routing
- src/Auth.spec.js takes protected routes for a spin
- src/RouteConfig.spec.js passes the list of routes from the test to the component to render
Cannot read property 'location' of undefined
If the test fails with this error from `useContext(Context).location` line, you have probably forgotten to surround the mounted route with the `BrowserRouter` component.import { BrowserRouter } from 'react-router-dom'
// then in the test mount the component the same way
// as you would in the "normal" mini web application
// AuthenticatedRoute and NewNote are user code we want to test
mount(
<BrowserRouter>
<AuthenticatedRoute>
<NewNote />
</AuthenticatedRoute>
</BrowserRouter>
)
See cypress-react-unit-test#388 for example
Cannot read property '...' of null
If the components inside the route rely on a context, surround the routes with appropriate context provider.// AuthenticatedRoute.js
export default function AuthenticatedRoute({ children, ...rest }) {
const { isAuthenticated } = useAppContext();
...
}
// test file
mount(
<BrowserRouter>
<AppContext.Provider value={{ isAuthenticated: true, userHasAuthenticated: true }}>
<AuthenticatedRoute>...</AuthenticatedRoute>
</AppContext.Provider>
</BrowserRouter>
)
See cypress-react-unit-test#388 for example