1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.