Next.js 14 でJestを設定する方法
Next.js + Jest サンプルをもとに設定
Next.jsにJestのサンプルがあります。これを参考にしてJestの設定を行います。
上記のサンプルプロジェクトをローカルに作成する場合、以下を実行します。実行すると with-jest-app ディレクトリが作成されます。
npx create-next-app --example with-jest with-jest-app
サンプルではテストファイルは __tests__ ディレクトリ以下に置かれますが、今回は tests/jest ディレクトリに変更して以下のようなディレクトリ構成にします。 これはJest以外にテストツール等を追加するための対応です。 例えば、e2eテストを追加するとき、tests/e2e ディレクトリを作成して、その中にe2eテスト関係のファイルをまとめるケースです。
next-app -- (Next.js用プロジェクトディレクトリ)
|- package.json
|- tsconfig.json
|- src --- app
|
|- jest.config.js
|- jest.setup.js
|
|- tests --- jset --- spec --- app (src/app 以下にあるファイルのテストファイルを置く)
テスト設定の作業はサンプルを参考に以下を行います。
必要なパッケージのインストール
サンプルを参考に必要なパッケージをインストールします。
Jest関係は以下になります。
npm i -D jest jest-environment-jsdom @types/jest
Testing-library関係は以下になります。
npm i -D @testing-library/react @testing-library/jest-dom
jest.config.jsの作成
サンプルの jest.config.js に修正を加えます。 この例ではテストファイルを置くディレクトリを tests/jest/spec にしますので、その設定として testMatch を追加します。
const nextJest = require("next/jest");
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: "./",
});
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
testEnvironment: "jsdom",
testMatch: [
"**/tests/jest/spec/**/*.(spec|test).ts?(x)"
]
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
jest.setup.jsの作成
jest.config.js はサンプルと同じにします。内容は以下のようになります。
// Learn more: https://github.com/testing-library/jest-dom import "@testing-library/jest-dom";
テスト用ディレクトリ作成と動作確認
テスト用ディレクトリを作成します。Next.jsプロジェクトのトップディレクトリで以下を実行します。
mdkir -p tests/jest/spect/app
次に動作確認用テストファイルを作成します。ファイルパスは以下になります。
tests/jest/spec/app/page.test.tsx
中身は以下になります。 これはトップページのある文字列が存在することを確認するテストです。 バージョンによっては文字列が異なるかもしれません。 そのときは src/app/page.tsx の中から適当な文字列を見つけて置き換えます。
import Home from '@/app/page';
import { render } from '@testing-library/react';
describe("Hom page test", () => {
test("Sample test", async () => {
const { findAllByText } = render(<Home />);
expect(await findAllByText("Find in-depth information about Next.js features and API.")).toHaveLength(1);
});
});
実行して以下のようになれば成功です。
$ npm run test
> next-app@0.1.0 test
> jest
PASS tests/jest/spec/app/page.test.tsx
Home Test
✓ Shanpshot test (59 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.862 s, estimated 1 s
Ran all test suites.