はじめに
以下の環境にJestを導入する手順を備忘録としてまとめる
・TypeScript
・React
・Next.js
導入手順
- 依存関係をインストール
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node ts-jest @types/jest
# or
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node ts-jest @types/jest
# or
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node ts-jest @types/jest
2. Jest構成ファイルの生成
npm init jest@latest
# or
yarn create jest@latest
# or
pnpm create jest@latest
参考:https://zenn.dev/andota05/scraps/f960ef1e3aab96
? Would you like to use Jest when running "test" script in "package.json"? » (Y/n) ⇒ Y
? Would you like to use Typescript for the configuration file? » (y/N) ⇒ Y
? Choose the test environment that will be used for testing » - Use arrow-keys. Return to submit. node jsdom (browser-like) ⇒ jsdom
? Do you want Jest to add coverage reports? » (y/N) ⇒ N
? Which provider should be used to instrument code for coverage? » - Use arrow-keys. Return to submit. ⇒babel
? Automatically clear mock calls, instances, contexts and results before every test? » (y/N) ⇒ Y
3. jest.config.ts 設定ファイルを以下のように更新
/**
* 各設定プロパティの詳細については、以下を参照してください:
* https://jestjs.io/docs/configuration
*/
import type { Config } from 'jest';
import nextJest from 'next/jest.js';
const createJestConfig = nextJest({
// テスト環境で next.config.js や .env ファイルを読み込むために Next.js アプリのパスを指定
dir: './',
});
const config: Config = {
// 使用するテスト環境
testEnvironment: 'jsdom',
// テストの前にモックの呼び出し、インスタンス、コンテキスト、結果を自動的にクリアする
clearMocks: true,
// リソースを単一モジュールでスタブ化するために正規表現をモジュール名にマッピング
moduleNameMapper: {
// tsconfig の alias @/ ⇒ src/ に対応
'^@/(.*)$': '<rootDir>/src/$1',
// CSS / Sass モジュールを identity-obj-proxy でモック
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
// 画像ファイルをモック
'\\.(png|jpg|jpeg|gif|svg)$': '<rootDir>/__mocks__/fileMock.js',
},
// 各テストの前にテストフレームワークを設定するモジュールのパスのリスト
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
// ルートDir(optional)
roots: ['<rootDir>/src'],
// テスト対象外フォルダ
testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
};
export default createJestConfig(config);
4. jest.setup.ts をroot直下に作成
import '@testing-library/jest-dom';
5. _mocks_\fileMock.js をroot直下に作成
module.exports = 'test-file-stub';
6. package.jsonのscriptsに以下を追加
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
},
実行方法
ターミナルで以下のコマンドを実行する
npm run test
# or
yarn test
# or
pnpm test
参考