How to mock useRouter?
See original GitHub issueQuestion 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:
- Created 4 years ago
- Reactions:7
- Comments:38 (6 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

I ended up mocking it like this, I only need the
useRouterexport so this worked well enough for my purposes:I managed to mock it this way.