自分が詰まった箇所の調査ログを残しておきます。
環境
- 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 };
});
自分が詰まった箇所の調査ログを残しておきます。
環境
13.5.110.9.1329.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
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-contextnext/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 }; });