前提
- アプリケーションの開発概要
- Next.js
- TypeScript
- HTML/CSS(SaSS)
必要なパッケージ
以下のパッケージをnpmでインストールする
npm install -D jest ts-jest @testing-library/react @testing-library/jest-dom @types/jest identity-obj-proxy
※TypeScirptを使用する場合 ts-jestが必要。
※@types/jest identity-obj-proxyはCSSをモックで返してくれるモジュールです。
1.セットアップファイルを用意する
ルートディレクトリに、config.jsとsetup.jsを作成する
- jest.config.ts
// jest.config.ts
import type { Config } from "jest";
const config: Config = {
testEnvironment: "jsdom",
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/$1",
"\\.(css|scss|sass)$": "identity-obj-proxy", // スタイルファイルを無視する設定
},
testMatch: ["**/__tests__/**/*.(test|spec).[jt]s?(x)"], //__tests__の中にあるtest.jsファイルを読み込むように設定する
transform: {
"^.+\\.(ts|tsx)$": "ts-jest", //tsファイルをjsファイルに変換する
},
};
export default config;
- jest.setup.ts
// jest.setup.ts
require("@testing-library/jest-dom");
2.ts.config.jsに以下を追加
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"jest.setup.ts", // ← 明示的に追加
"src/__tests__/**/*" // ← テストフォルダも必要なら
],
3.テスト用ファイルを設定する
// src/__tests__/Home.test.tsx
import { render, screen } from "@testing-library/react";
import Home from "@/src/components/Home";
// useRouter をモックする
jest.mock("next/navigation", () => ({
useRouter: () => ({
push: jest.fn(),
replace: jest.fn(),
prefetch: jest.fn(),
}),
}));
test("renders heading", () => {
render(<Home />);
expect(screen.getByRole("heading")).toBeInTheDocument();
});
Homeコンポーネントでは、useRouterを使ってルーティングしているかつAppRouter構成なので、
useRouterではモックを返すように設定しています。
4. テストを実行する
package.jsonにjestを走らせるスクリプトを追加して実行する
- package.json
"scripts": {
...
"test": "jest"
},
- ターミナルでnpm testを実行する
> npm run test
Debugger attached.
> client@0.1.0 test
> jest
Debugger attached.
PASS src/__tests__/Home.test.tsx
√ renders heading (178 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.854 s
Ran all test suites.
Waiting for the debugger to disconnect...
Waiting for the debugger to disconnect...
これで、Jestを使った簡単なテストが実行できました。