Mocking Next Router In React Tests: A Step-by-Step Guide
Mocking `useRouter` from Next.js is crucial when testing React components with Jest. Use `jest.mock` to create a mock, return useful values & test the `push` method separately.
Edit: This article is outdated. Read an updated version here: mocking useRouter in app router in Next 15. I will start off with a quick snippet for the people only looking for that. I give a long explanation including examples and tests after. tl;dr // mock useRouter jest.mock('next/router', () => ({ useRouter: jest.fn() })) // setup a new mocking function for push method const pushMock = jest.fn() // mock a return value on useRouter useRouter.mockReturnValue({ query: {}, // return mock for push method push: pushMock, // ... add the props or methods you need })...