profile
viewpoint

Ask questionsHow to mock useRouter?

Question about Next.js

I'm want to make sure my component renders correctly with useRouter hook (actually I'm trying to understand how new dynamic routing works), so I have code:

import React from 'react';
import { NextPage } from 'next';
import { useRouter } from 'next/router';

const UserInfo : NextPage = () => {
  const router = useRouter();
  const { query } = router;

  return <div>Hello {query.user}</div>;
};

export default UserInfo;

And what I'm trying is:

// test
import { render, cleanup, waitForElement } from '@testing-library/react';

import UserInfo from './$user';

// somehow mock useRouter for $user component!!!

afterEach(cleanup);

it('Should render correctly on route: /users/nikita', async () => {
  const { getByText } = render(<UserInfo />);

  await waitForElement(() => getByText(/Hello nikita!/i));
});

But I get an error TypeError: Cannot read property 'query' of null which points on const router = useRouter(); line.

P. S. I know dynamic routing is available on canary verions just for now and might change, but I get a problem with router, not with WIP feature (am I?).

zeit/next.js

Answer questions borisowsky

@ijjk Hi, thank you! I don't know if I'm doing it right, but test passes 😂

import { render, cleanup, waitForElement } from '@testing-library/react';
import { createRouter } from 'next/router';
import { RouterContext } from 'next-server/dist/lib/router-context';

const router = createRouter('', { user: 'nikita' }, '', {
  initialProps: {},
  pageLoader: jest.fn(),
  App: jest.fn(),
  Component: jest.fn(),
});

import UserInfo from './$user';

afterEach(cleanup);

it('Should render correctly on route: /users/nikita', async () => {
  const { getByText } = render(
    <RouterContext.Provider value={router}>
      <UserInfo />
    </RouterContext.Provider>,
  );

  await waitForElement(() => getByText(/Hello nikita!/i));
});

If there is more abstract way to mock query params, so I'd be able to pass actual route (/users/nikita for example) and pass path to file? What do you think?

useful!
source:https://uonfu.com/
answerer
Nikita Borisowsky borisowsky @mailru Kaliningrad, RU linkedin.com/in/borisowsky Front End developer with Back End knowledge, GraphQL enthusiast.
Github User Rank List