【Jest_36】 TypeScriptでJestを使う準備は?
TypeScriptでJestを使う準備
1. プロジェクトの準備
1-1. Node.js と npm/yarn のインストール確認
Node.js(推奨v14以上)がインストールされているか確認
node -v
npm -v2. 必要なパッケージのインストール
TypeScript + Jest のテスト環境構築には以下のパッケージが必要です。
npm install --save-dev jest typescript ts-jest @types/jestまたは yarnの場合
yarn add -D jest typescript ts-jest @types/jest各パッケージの役割
jest
テストランナー本体
typescript
TypeScriptコンパイラ
ts-jest
JestでTypeScriptを動かすためのトランスパイラ
@types/jest
Jestの型定義(TypeScript用)
3. TypeScriptコンパイラの初期設定
3-1. tsconfig.json の作成
npx tsc --init生成された tsconfig.json に以下を追記・確認してください。
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true
},
"include": ["src", "tests"]
}rootDir はソースのルート、include にテストコードも入れてください。
4. Jestの設定ファイル作成
4-1. jest.config.js を作成
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest', // ts-jestを使うことを宣言
testEnvironment: 'node', // 実行環境をNode.jsに設定
roots: ['<rootDir>/tests'], // テストコードのあるディレクトリ
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
testMatch: ['**/*.test.ts', '**/*.spec.ts'], // テストファイルのパターン
globals: {
'ts-jest': {
isolatedModules: true // 高速化のため(必要に応じて)
}
}
};5. テスト用TypeScriptファイルの作成
5-1. ディレクトリ構成例
project-root/
├─ src/
│ └─ sample.ts
├─ tests/
│ └─ sample.test.ts
├─ jest.config.js
├─ tsconfig.json
└─ package.json5-2. 簡単なテスト例
src/sample.ts
export function add(a: number, b: number): number {
return a + b;
}tests/sample.test.ts
import { add } from '../src/sample';
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});6. npm scripts にテスト実行コマンドを追加
package.json の scripts に
"scripts": {
"test": "jest"
}を追加し、ターミナルで
npm testでテストが走るようにします。
7. よくあるトラブルと対処法
JestがTypeScriptファイルを認識しない
preset: 'ts-jest' が設定されているか確認
型エラーでビルドが通らない
tsconfig.json の strict 設定を見直し
テストファイルが見つからない
testMatch または roots の設定を確認
import 文でモジュールが解決できない
moduleResolution: "node" を確認
Jestの型定義が効かない
@types/jest がインストールされているか確認
8. 補足:ESM(ECMAScript Modules)での対応
Node.jsのESMモードでTypeScriptテストを書く場合は設定が複雑になるため、
基本はCommonJSで運用することをおすすめします。
9. 補足:VSCodeでの補助設定
settings.json に
{
"typescript.tsdk": "node_modules/typescript/lib"
}などを入れてTypeScriptのバージョンを固定すると良いです。
10. まとめ
1. 必要なパッケージをインストール
jest, typescript, ts-jest, @types/jest
2. tsconfig.json を用意しTypeScript環境整備
strictモード推奨
3. jest.config.js で ts-jest をpresetに設定
テストの実行環境を明示
4. テストコードとソースコードを分けて管理
tests/ フォルダなど
5. npm test でテスト実行
スクリプト設定で簡単に呼び出せる
6. 問題は設定ファイルとパッケージのバージョンを確認
設定ミスが多いポイント
