question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to mock useRouter?

See original GitHub issue

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?).

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:7
  • Comments:38 (6 by maintainers)

github_iconTop GitHub Comments

59reactions
aekscocommented, Sep 20, 2019

I ended up mocking it like this, I only need the useRouter export so this worked well enough for my purposes:

jest.mock("next/router", () => ({
    useRouter() {
        return {
            route: "/",
            pathname: "",
            query: "",
            asPath: "",
        };
    },
}));
46reactions
francisprovostcommented, Jul 17, 2019

I managed to mock it this way.

import * as nextRouter from 'next/router';

nextRouter.useRouter = jest.fn();
nextRouter.useRouter.mockImplementation(() => ({ route: '/' }));

Read more comments on GitHub >

github_iconTop Results From Across the Web

Read more - back - GitHub Pages
With this approach we mock the implementation of useRouter with our own. // SomeComponent.test.js ... const useRouter = jest.spyOn(require('next/router'), ...
Read more >
How to mock Next router with Jest - DEV Community ‍ ‍
mock useRouter jest.mock('next/router', () => ({ useRouter: jest.fn() })) // setup a new mocking function for push method const pushMock ...
Read more >
Mocking NextJS router events with Jest - Stack Overflow
Firstly you mock useRouter. jest.mock('next/router', () => ({ userRouter: jest.fn() }). Then, you add a return value to your mock.
Read more >
mocking useRouter (just basics) with react testing library (4/6)
In this episode , I create the navbar & product component while writing 3 tests and :1. creating advanced nav links ,2. displaying...
Read more >
Unit Testing Next.js Router - useRouter - YouTube
02:10 Common online solution to mock useRouter 02:43 Create Mock Router function 04:35 How to unit test useRouter by providing RouterContext ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found