CodePark/ questions / Testing Next.js
START PRACTICINGPRACTICE
Frontend question · Testing › Testing Next.js

A Jest test renders a Client Component that calls useRouter() from next/navigation, and it throws an error about the app router not being mounted. What's the usual fix?

Mock next/navigation with jest.mock and return a fake router

Mock next/navigation with jest.mock and return a fake router. The App Router context only exists inside a running Next.js app, so unit tests mock the hooks. The tempting next/router option is wrong. next/router is the Pages Router API, and it doesn't work in App Router components. Switching to the node environment is wrong because it removes the DOM the test needs.