6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Jest(Nextjs13)でError: invariant expected app router to be mountedというエラーが出る

Last updated at Posted at 2023-09-15

はじめに

NextjsでRoterを使ったページ遷移の処理を実装したのですが、その実装が影響して既存のコンポーネントテストが動かなくなったのでまとめていきます

問題

今まで動いていたコンポーネントテストのrender(<Smaple />がエラーになるようになりました

-----
Error: invariant expected app router to be mountedJest
(alias) function Contact(): JSX.Element
import Sample

解決方法

Routerをモックする必要があったので以下をテストの最初に追加することで解決しました

sample.spec.tsx

const mockedUseRouter = jest.fn();

jest.mock("next/navigation", () => ({
  useRouter: () => mockedUseRouter(),
  usePathname: jest.fn().mockReturnValue("/some-route"),
}));

describe(....

調べたところ

const mockedUseRouter = jest.fn();

この箇所がないものがあり、うまく動かなかったので注意が必要です

おわりに

まとめようか悩んだのですが困りそうな人がいると思ったので投稿しました

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?