bahmutov / test-react-router-v5

Component tests for apps that use React Router v5

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

test-react-router-v5

Component tests for apps that use React Router v5

cypress version cypress-react-unit-test version

Uses cypress-react-unit-test

Route config test

Common problems

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

About

Component tests for apps that use React Router v5


Languages

Language:JavaScript 86.1%Language:HTML 9.0%Language:CSS 4.9%