vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.42k stars 26.79k forks source link

useRouter not working with jest #38230

Open fmacherey opened 2 years ago

fmacherey commented 2 years ago

Verify canary release

Provide environment information

[fmacherey@macbook application (feature/WR-333-update-packages *>)]$ npx --no-install next info

    Operating System:
      Platform: darwin
      Arch: x64
      Version: Darwin Kernel Version 21.3.0: Wed Jan  5 21:37:58 PST 2022; root:xnu-8019.80.24~20/RELEASE_X86_64
    Binaries:
      Node: 16.13.1
      npm: 8.1.2
      Yarn: 1.22.19
      pnpm: N/A
    Relevant packages:
      next: 12.2.1-canary.1
      eslint-config-next: 12.2.0
      react: 17.0.2
      react-dom: 17.0.2

What browser are you using? (if relevant)

Chrome

How are you deploying your application? (if relevant)

No response

Describe the Bug

When updating from next@12.1.6 to 12.2.x I got the following error message in my jest tests:

 FAIL  components[...]/index.test.jsx
  ● Test suite failed to run

    No router instance found.
    You should only use "next/router" on the client side of your app.

    > 1 | import { useRouter } from "next/router";
        | ^

With next 12.1.6 it was no problem to import useRouter and mock it with useRouter.mockReturnValue... but now this fails.

Expected Behavior

jest tests should run as before and no warning for useRouter should be thrown.

Link to reproduction

example.com

To Reproduce

see above

martin-fv commented 2 years ago

Same problem here. Maybe this is the solution? https://github.com/scottrippey/next-router-mock

fmacherey commented 2 years ago

Hey @martin-fv yes this fixed the test for me. But i keep this issue open for now, since the bug is still there and might be fixed.

dsueltenfuss commented 2 years ago

I'm encountering the same issue as well

martin-fv commented 2 years ago

Is there any update?

tuckwilli commented 2 years ago

not sure if this helps anyone else but I was seeing this issue after updating when I had next/router mocked like this:

import { useRouter } from 'next/router';

jest.mock('next/router');

changing to the following fixed the issue for me:

import { useRouter } from 'next/router';

jest.mock('next/router', () => ({
  useRouter: jest.fn(),
}));
Ali-Khamis commented 1 year ago

not sure if this helps anyone else but I was seeing this issue after updating when I had next/router mocked like this:

import { useRouter } from 'next/router';

jest.mock('next/router');

changing to the following fixed the issue for me:

import { useRouter } from 'next/router';

jest.mock('next/router', () => ({
  useRouter: jest.fn(),
}));

@tuckwilli thank you, I've been looking for a fix all day and this works for me but can I know more, what is the difference?

VadimZP commented 9 months ago

For Next.js 14 you can use:

jest.mock("next/navigation", () => ({
  useRouter: jest.fn(),
}));

No need to import useRouter 🙂