Next.jsMedium

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)

  • useRouter returns { push, replace, refresh, prefetch, back, forward }; make each a mock function.
  • usePathname returns a string; useSearchParams returns a URLSearchParams (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 with memoryRouter.setCurrentUrl("/path").
  • Or mock useRouter to 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

tsx
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";
6
7const replace = vi.fn();
8
9vi.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}));
14
15describe("SearchBox", () => {
16 beforeEach(() => replace.mockClear());
17
18 it("updates the query string with replace", async () => {
19 render(<SearchBox />);
20 const input = screen.getByRole("textbox");
21 expect(input).toHaveValue("shoe");
22
23 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.

Open in study app