0

As titled

I set up the following jest mock for next/navigation

jest.mock('next/navigation', async () => {
  const actual = await jest.requireActual('next/navigation');

  return {
    __esModule: true,
    ...actual,
    useParams: jest.fn(),
    useRouter: jest.fn(() => ({
      push: jest.fn(),
      replace: jest.fn(),
    })),
    useSearchParams: jest.fn(),
    usePathname: jest.fn(),
  }
});

and then in my test block

describe('ChannelDetailPage', () => {

  const SomePage = () => (
    <SomeProvider value={mockProvider}>
      <SomeTemplate />
    </SomeProvider>
  );

  it('renders items correctly', async () => {
    const useParams = require('next/navigation').useParams;
    useParams.mockReturnValue({ slug: 'test-slug' });
    render(<SomePage />);

However the test failed with the following messages

TypeError: Cannot read properties of undefined (reading 'mockReturnValue')

      89 |   it('renders items correctly', async () => {
      90 |     const useParams = require('next/navigation').useParams;
    > 91 |     useParams.mockReturnValue({ slug: 'test-slug' });

Most of the docs related to this are for react-router-dom only, but this is useParams from NextJS's next/navigation, and the search results were very little.

Therefore i need help here to point and guide me of doing test with Jest RTL for NextJS's custom hooks.

0

Your Answer

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

Browse other questions tagged or ask your own question.