[Feature] Add feature to allow mocking useRouter in Next.js for component testing
See original GitHub issueIf the component uses useRouter()
hook, tests will fail because the hook will be null/undefined.
Jest has jest.spyOn
to mock it (reference - https://jamespotz.github.io/blog/how-to-mock-userouter). It would be helpful to have something similar here.
Issue Analytics
- State:
- Created a year ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
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
In this video we will unit- test components that use the Next. js useRouter hook.We will also see how to have unit- tests...
Read more >Mocking NextJS router events with Jest - Stack Overflow
Based on that, I was able to put together the working solution below: jest.mock('next/router', () => ({ useRouter() { ...
Read more >next-router-mock - npm
Mock implementation of the Next.js Router. ... Useful in tests and Storybook. ... Dynamic Routes; Sync vs Async; Supported Features.
Read more >How to mock Next router with Jest - DEV Community
I give a long explanation including examples and tests after. ... components/List.js import { useRouter } from 'next/router' function ...
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
Given component
the test
will result in:
What I would like to do, is mock what router would return in the test:
With Jest, it seems is possible to mock what the router would return on test by test basis (like in blog example I posted earlier)
Once the patch above lands, you should be able to do the following: