javascriptnode.jsreactjsnext.jsvitest

How to mock next/router for unit testing with vitest?


When trying to write simple tests for out Next.js app that uses useRouter() hook, vitest starts throwing errors.

Looking for ways to mock next/router for unit testing with vitest.


Solution

  • After some research and trial and error, I figured out the way to mock next/router.

    You need to create a setup file for your test setup and configure vitest to use that.

    // vitest.config.js/ts
    export default defineConfig({
      test: {
        environment: "jsdom",
        globals: true,
        setupFiles: ["vitestSetup.ts"],
      },
    });
    

    Now create vitestSetup.ts in the root directory with the following content.

    // vitestSetup.ts
    import { beforeAll, vi } from "vitest";
    beforeAll(() => {
      vi.mock("next/router", () => require("next-router-mock"));
    })
    

    Congratulations! You have successfully mocked next/router.