Search code examples
react-hooksreact-testing-libraryreact-hooks-testing-library

How to mock useRouter parameters for react-hooks-testing-library?


I have a custom hook, which has structure of:

const urlHook = () => {
const router = useRouter();

const read = () => {
  return validate(router.query.param);
}

const write = (params) => {
  router.push(
    {
      query: {
        param: params,
      },
    },
    undefined,
    {shallow: true},
  )
}

const validate = (params) => {}
}

I want to test this hook using react-hooks-testing-library but I'm not sure how to setup for router.query.param to read values that I want or how to check if function write() will create correct url?


Solution

  • To mock entire hook - jest.requireActual:

    jest.mock('react-router-dom', () => ({
      ...jest.requireActual('react-router-dom'),
      useParams: () => ({
        blogId: 'company1',
        articleId: 'blog1',
      }),
      useRouteMatch: () => ({ url: '/blog/blog1/article/article1' }),
    }));
    

    To mock history/routing state - MemoryRouter:

    import {Route, MemoryRouter} from 'react-router-dom';
    
    ...
    
    const renderWithRouter = ({children}) => (
      render(
        <MemoryRouter initialEntries={['blogs/1']}>
          <Route path='blogs/:blogId'>
            {children}
          </Route>
        </MemoryRouter>
      )
    )
    

    Helpful example with explanations: https://v5.reactrouter.com/web/guides/testing