How do you mock useRouter in tests?
For the App Router, mock the next/navigation module with jest.mock or vi.mock and return fake useRouter, usePathname, useSearchParams and useParams implementations, then assert that push or replace was called. For the Pages Router, mock next/router or use the next-router-mock package, which provides an in-memory router.
App Router (next/navigation)
useRouterreturns{ push, replace, refresh, prefetch, back, forward }; make each a mock function.usePathnamereturns a string;useSearchParamsreturns aURLSearchParams(it is read-only in real code, but a real instance works in tests).- Keep the mock in a setup file or a helper so tests can override per case with
mockReturnValue.
Pages Router (next/router)
jest.mock("next/router", () => require("next-router-mock"))gives a working router withmemoryRouter.setCurrentUrl("/path").- Or mock
useRouterto return{ push: jest.fn(), query: {}, pathname: "/" }.
Testing <Link>
next/link renders an <a> and works in jsdom without mocks; assert on href. Clicking it triggers navigation through the router context, so for navigation assertions prefer testing your own router.push calls or use E2E.
Avoid over-mocking
If a component's behavior depends heavily on routing, an E2E test with Playwright is often clearer and less brittle than mocking every hook.
Code example
1// src/components/search-box.test.tsx (Vitest; swap vi for jest in Jest)2import { describe, it, expect, vi, beforeEach } from "vitest";3import { render, screen } from "@testing-library/react";4import userEvent from "@testing-library/user-event";5import { SearchBox } from "./search-box";67const replace = vi.fn();89vi.mock("next/navigation", () => ({10 useRouter: () => ({ push: vi.fn(), replace, refresh: vi.fn(), prefetch: vi.fn(), back: vi.fn() }),11 usePathname: () => "/products",12 useSearchParams: () => new URLSearchParams("q=shoe"),13}));1415describe("SearchBox", () => {16 beforeEach(() => replace.mockClear());1718 it("updates the query string with replace", async () => {19 render(<SearchBox />);20 const input = screen.getByRole("textbox");21 expect(input).toHaveValue("shoe");2223 await userEvent.type(input, "s");24 expect(replace).toHaveBeenLastCalledWith("/products?q=shoes", { scroll: false });25 });26});
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.