0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsでテストを実行したときにNextRouter was not mountedというエラーが発生したときの解消法

Last updated at Posted at 2025-04-18

概要

現在Next.jsで開発をしており、フロントエンドテストを行っているときにNextRouter was not mountedというエラーが発生。
結論から言うとルーターをモックすることで解決することができたので、それについて書いていきたいと思います。

エラーの原因

テスト環境ではルーターは自動的にセットアップされず、明示的にルーティングを実行しない限りルーターはマウントされません。
なので、テスト対象のコンポーネントがuseRouterを使ってルーティング情報にアクセスしているにも関わらずテスト環境でルーターがセットアップされていない場合、コンポーネントはNextRouter was not mountedエラーを投げます。
自分の場合、テストでエラーが発生したコンポーネント内で

import { useRouter } from "next/router";
const router = useRouter();

このようにuseRouterを使用していたのにも関わらず、テスト環境でルーターをセットアップしていないため今回のエラーが発生したようです。

エラーの解消方法

テスト内でルーターをモックすることでエラーを解消することができました。

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

参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?