Skip to content

特定の環境でnpm test を実行すると、全テストスイートが以下のエラーで失敗する。 #17

Description

@reomin

自分が詰まった箇所の調査ログを残しておきます。

環境

  • Next.js: 13.5.11
  • next-router-mock: 0.9.13
  • jest: 29.3.1

エラー詳細

npm test を実行すると、全テストスイートが以下のエラーで失敗する。

FAIL src/components/templates/Post/LikeButton/index.test.tsx ● Test suite failed to run
Cannot find module 'next/dist/shared/lib/router-context' from 'jest.setup.ts'

9 | jest.mock("next/dist/client/router", () => require("next-router-mock"));
10 | // scottrippey/next-router-mock#58

11 | jest.mock("next/dist/shared/lib/router-context", () => {
| ^
12 | const { createContext } = require("react");
13 | const router = require("next-router-mock").default;
14 | const RouterContext = createContext(router);

at Resolver._throwModNotFoundError (node_modules/.pnpm/jest-resolve@29.7.0/node_modules/jest-resolve/build/resolver.js:427:11)
at Object.mock (jest.setup.ts:11:6)

影響範囲: 全52テストスイートが実行不可

原因

Next.js 13で内部モジュール構造が変更され、router-contextのパスが変更された。

  • 旧: next/dist/shared/lib/router-context
  • 新: next/dist/shared/lib/router-context.shared-runtime

解決方法

jest.setup.ts の11行目を修正:

  // MEMO: @storybook/testing-react で globalSetup している場合は不要
  jest.mock("next/router", () => require("next-router-mock"));
  jest.mock("next/dist/client/router", () => require("next-router-mock"));
  // https://github.com/scottrippey/next-router-mock/issues/58
- jest.mock("next/dist/shared/lib/router-context", () => {
+ jest.mock("next/dist/shared/lib/router-context.shared-runtime", () => {
    const { createContext } = require("react");
    const router = require("next-router-mock").default;
    const RouterContext = createContext(router);
    return { RouterContext };
  });

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions