Properly mocking useParams hook in jest

Viewed 23

I am trying to mock the useParams hook in jest and try to make it dynamic so I can mock it a few times. However, I can only mock it if I hardcode the value. Here's what I got so far:

const mockedUsedNavigate = jest.fn();

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'), // use actual for all non-hook parts
  useNavigate: () => mockedUsedNavigate,
  useParams: () => ({
    hash: '123',
  }),
}));

This works because I am hardcoding the useParam to return a { hash: '123' } object. However, if I try to mock this, it won't work:

const mockedUsedNavigate = jest.fn();

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'), // use actual for all non-hook parts
  useNavigate: () => mockedUsedNavigate,
  useParams: () => jest.fn().mockReturnValue({ hash: '123' })
}));

If I do that, my component will receive an empty value and the value wont be mocked the way I want:

  const { hash = '' } = useParams<{ hash: string }>();
  console.log('hash: ', hash); ---> ''

So I'm not sure what I'm doing wrong... Can anybody point me to the right direction?

1 Answers

You wrap useParams into 2 functions (one is the anonymous function () => {}, one is jest.fn()).

For the fix, you should remove the first anonymous function like below

useParams: jest.fn().mockReturnValue({ hash: '123' })
Related