Jest の--watch オプション活用術

モダンな Web 開発において、テストの実行効率は開発者の生産性に直結する重要な要素です。特に Jest の --watch
オプションは、開発サイクルを劇的に改善する強力な機能でありながら、その真の活用法を理解している開発者は意外に少ないのが現状でしょう。
この記事では、Jest の --watch
オプションを使った開発効率向上のテクニックから、大規模プロジェクトでのパフォーマンス最適化まで、実践的な活用術を詳しく解説いたします。手動でのテスト実行から解放され、より快適な開発体験を実現していきましょう。
背景
開発効率向上の重要性
現代の Web 開発では、アジャイル開発やスクラム開発など、短期間でのイテレーションが求められています。この環境下では、フィードバックサイクルの短縮が成功の鍵となります。
迅速なフィードバックループの価値
テストを頻繁に実行し、即座に結果を確認することで、以下のメリットを得られます:
# | メリット | 効果 |
---|---|---|
1 | バグの早期発見 | 修正コストの大幅削減 |
2 | 自信を持った開発 | リファクタリングへの心理的障壁の軽減 |
3 | 集中力の維持 | 長時間のテスト待機によるフロー状態維持 |
4 | 品質の向上 | 継続的な品質チェックによる品質担保 |
5 | 開発速度の向上 | 手戻り作業の削減 |
TDD(テスト駆動開発)での重要性
テスト駆動開発では、Red-Green-Refactor サイクルを高速で回すことが重要です。Jest の --watch
オプションは、このサイクルを自動化し、開発者がコードの品質に集中できる環境を提供します。
javascript// TDDのサイクル例
describe('計算機能', () => {
test('加算が正しく動作する', () => {
// Red: まずテストを書く(失敗することを確認)
expect(add(2, 3)).toBe(5);
});
});
// Green: 最小限のコードで通す
function add(a, b) {
return a + b;
}
// Refactor: リファクタリング(watchが継続的に検証)
function add(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('引数は数値である必要があります');
}
return a + b;
}
手動テスト実行の課題
従来の手動テスト実行では、開発効率を大きく阻害する課題が存在します。
時間的コストの問題
bash# 従来の手動実行パターン
# 1. コード変更
# 2. ターミナルに切り替え
yarn test
# 3. 結果待機(10-30秒)
# 4. 結果確認
# 5. コードに戻る
# 6. 修正
# 7. 再度テスト実行...
この一連の流れを 1 日に何十回も繰り返すと、累積的な時間損失は膨大になります。
集中力の分散
プログラミング中の集中状態(フロー状態)は非常に貴重です。手動でのテスト実行は、この集中状態を頻繁に中断させる原因となってしまいます。
実行忘れのリスク
手動実行では、つい「後でテストしよう」と思ってしまい、結果的にテストを実行し忘れることがあります。これにより、バグの発見が遅れる可能性があります。
課題
テスト実行の手間
開発中のテスト実行には、以下のような手間が発生します。
コマンド入力の煩雑さ
プロジェクトによっては、複雑なオプションを指定してテストを実行する必要があります:
bash# 複雑なテスト実行コマンド例
yarn test --coverage --verbose --watchPathIgnorePatterns="node_modules" --testPathPattern="components"
このような長いコマンドを毎回入力するのは非効率的です。
ファイル切り替えの負担
bash# ファイル変更後の典型的な手順
1. src/utils/math.js を編集
2. エディタからターミナルに切り替え
3. テストコマンド実行
4. 結果確認
5. エディタに戻る
6. テストファイルを確認
7. 再度実装ファイルに戻る
エラー発生時の非効率性
テストが失敗した場合、以下のような非効率なサイクルが発生しがちです:
テスト実行 → エラー確認 → コード修正 → 再実行 → まだエラー → 修正 → 再実行...
フィードバックサイクルの遅延
心理的な実行障壁
手動実行は「面倒」と感じる心理的な障壁があり、結果的にテスト実行の頻度が下がってしまいます。
テスト結果の見落とし
大量のテスト出力の中から、重要な情報を見落としてしまうリスクがあります:
bash# 大量の出力例
PASS src/components/Button.test.js
PASS src/components/Input.test.js
FAIL src/utils/validation.test.js
● ValidationError: Invalid email format
PASS src/hooks/useUser.test.js
PASS src/services/api.test.js
Test Suites: 4 passed, 1 failed, 5 total
Tests: 23 passed, 2 failed, 25 total
バグ発見の遅延
手動実行の頻度が低いと、バグの発見が遅れ、修正コストが増大します。特に、複数のファイルを変更した後にまとめてテストを実行すると、どの変更がバグを引き起こしたかの特定が困難になります。
解決策:--watch オプションの基本
--watch と --watchAll の違い
Jest では、2 つの主要な監視オプションが提供されています。それぞれの動作と使い分けを理解することが、効率的な活用の第一歩です。
--watch オプション
--watch
はGit の変更追跡機能を利用して、変更されたファイルに関連するテストのみを実行します。
bash# --watch オプションの基本使用法
yarn test --watch
動作の仕組み
bash# Git で管理されているプロジェクトでの動作例
1. src/components/Button.js を変更
2. Git が変更を検知
3. Button.js に関連するテストファイルを特定
4. 関連テストのみ自動実行
# 実際の出力例
Watch Usage
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
適用される条件
javascript// Button.js を変更した場合、以下のテストが実行される
// 1. Button.test.js (直接的な関連)
// 2. App.test.js (Buttonをimportしている場合)
// 3. その他Buttonを使用しているコンポーネントのテスト
--watchAll オプション
--watchAll
はすべてのテストファイルを監視し、いずれかのファイルが変更されると全テストを実行します。
bash# --watchAll オプションの使用法
yarn test --watchAll
使用シーン
シーン | 推奨オプション | 理由 |
---|---|---|
機能開発 | --watch | 関連テストのみ実行で高速 |
リファクタリング | --watchAll | 影響範囲が予測困難なため全テスト実行 |
設定ファイル変更 | --watchAll | 全体への影響可能性 |
CI/CD 前の最終確認 | --watchAll | 全テストの通過確認 |
新機能の統合テスト | --watchAll | 他機能への影響確認 |
基本的な使い方とコマンド
package.json での設定
効率的な開発のため、よく使用するコマンドを package.json に登録しましょう:
javascript{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:watchAll": "jest --watchAll",
"test:coverage": "jest --coverage",
"test:watch:coverage": "jest --watch --coverage",
"test:silent": "jest --watchAll --silent",
"test:verbose": "jest --watchAll --verbose"
}
}
基本的な実行パターン
開発開始時
bash# プロジェクト開始時の推奨コマンド
yarn test:watch
# 出力例
Jest is running in watch mode.
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press q to quit watch mode.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press Enter to trigger a test run.
特定ファイルの集中作業
bash# 特定のファイルパターンに絞り込み
yarn test --watch --testPathPattern="Button"
# または正規表現を使用
yarn test --watch --testPathPattern="components/(Button|Input)"
エラーハンドリング
Watch モードでよく発生するエラーと対処法を確認しましょう。
Git 未初期化エラー
arduinoError: Test watch mode requires a git/hg repository. You have none
解決方法:
bash# Git リポジトリの初期化
git init
git add .
git commit -m "Initial commit"
# または --watchAll を使用
yarn test --watchAll
ファイル監視制限エラー
typescriptError: ENOSPC: System limit for number of file watchers reached
解決方法(Linux/WSL):
bash# ファイル監視制限を増加
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
メモリ不足エラー
csharpJavaScript heap out of memory
解決方法:
bash# Node.js のメモリ制限を増加
export NODE_OPTIONS="--max-old-space-size=4096"
yarn test --watch
または、package.json で設定:
javascript{
"scripts": {
"test:watch": "node --max-old-space-size=4096 node_modules/.bin/jest --watch"
}
}
具体例
開発ワークフローでの活用
React コンポーネント開発での実践例
実際の開発シーンでの --watch
オプションの効果を具体的に見てみましょう。
シーン:新しいコンポーネントの開発
javascript// src/components/UserCard.js
import React from 'react';
export const UserCard = ({ user }) => {
if (!user) {
return <div>ユーザー情報がありません</div>;
}
return (
<div className='user-card'>
<h3>{user.name}</h3>
<p>{user.email}</p>
<span
className={`status ${
user.isActive ? 'active' : 'inactive'
}`}
>
{user.isActive ? 'アクティブ' : '非アクティブ'}
</span>
</div>
);
};
対応するテストファイル
javascript// src/components/UserCard.test.js
import { render, screen } from '@testing-library/react';
import { UserCard } from './UserCard';
describe('UserCard', () => {
const mockUser = {
name: '田中太郎',
email: 'tanaka@example.com',
isActive: true,
};
test('ユーザー情報を正しく表示する', () => {
render(<UserCard user={mockUser} />);
expect(
screen.getByText('田中太郎')
).toBeInTheDocument();
expect(
screen.getByText('tanaka@example.com')
).toBeInTheDocument();
expect(
screen.getByText('アクティブ')
).toBeInTheDocument();
});
test('ユーザーが未定義の場合にエラーメッセージを表示する', () => {
render(<UserCard user={null} />);
expect(
screen.getByText('ユーザー情報がありません')
).toBeInTheDocument();
});
});
Watch モードでの開発プロセス
bash# ターミナル1: Watch モード開始
yarn test --watch
# Watch モードの出力
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press o to only run tests for changed files.
› Press p to filter by a filename regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
# ファイル変更時の自動実行
PASS src/components/UserCard.test.js
UserCard
✓ ユーザー情報を正しく表示する (25ms)
✓ ユーザーが未定義の場合にエラーメッセージを表示する (12ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.234s
Ran all test suites related to changed files.
API 開発での活用例
Node.js での API 開発における watch モードの活用例です。
javascript// src/controllers/userController.js
class UserController {
static async getUser(req, res) {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
error: 'ユーザーIDが必要です',
});
}
const user = await User.findById(id);
if (!user) {
return res.status(404).json({
error: 'ユーザーが見つかりません',
});
}
res.json({ user });
} catch (error) {
res.status(500).json({
error: 'サーバーエラーが発生しました',
});
}
}
}
テストファイル
javascript// src/controllers/userController.test.js
import request from 'supertest';
import app from '../app';
describe('GET /api/users/:id', () => {
test('有効なIDでユーザー情報を取得', async () => {
const response = await request(app)
.get('/api/users/123')
.expect(200);
expect(response.body).toHaveProperty('user');
expect(response.body.user.id).toBe('123');
});
test('IDが未指定の場合400エラーを返す', async () => {
const response = await request(app)
.get('/api/users/')
.expect(400);
expect(response.body.error).toBe(
'ユーザーIDが必要です'
);
});
test('存在しないIDの場合404エラーを返す', async () => {
const response = await request(app)
.get('/api/users/nonexistent')
.expect(404);
expect(response.body.error).toBe(
'ユーザーが見つかりません'
);
});
});
ファイル監視の仕組み
監視対象の自動判定
Jest の --watch
オプションは、以下のロジックで監視対象を決定します:
javascript// 監視対象の判定ロジック例
const changedFiles = ['src/components/Button.js'];
// 1. 直接的な関連ファイル
const directlyRelated = [
'src/components/Button.test.js',
'src/components/__tests__/Button.test.js',
];
// 2. インポートしているファイル
const importingFiles = [
'src/components/Header.js', // import { Button } from './Button'
'src/pages/Dashboard.js', // import { Button } from '../components/Button'
];
// 3. 間接的な関連ファイル
const indirectlyRelated = [
'src/components/Header.test.js',
'src/pages/Dashboard.test.js',
];
ファイル監視の除外設定
不要なファイルの監視を除外することで、パフォーマンスを改善できます:
javascript// jest.config.js
module.exports = {
// 監視対象から除外するパターン
watchPathIgnorePatterns: [
'/node_modules/',
'/build/',
'/dist/',
'/coverage/',
'\\.tmp$',
'\\.log$',
],
// テストファイルの検索パターン
testMatch: [
'**/__tests__/**/*.(js|jsx|ts|tsx)',
'**/*.(test|spec).(js|jsx|ts|tsx)',
],
// 監視対象のファイル拡張子
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json'],
};
インタラクティブモードの操作
基本的なキーコマンド
Watch モード中に使用できるインタラクティブコマンドを詳しく解説します:
bash# Watch モード開始
yarn test --watch
# 利用可能なコマンド一覧
Watch Usage
› Press a to run all tests. # 全テスト実行
› Press f to run only failed tests. # 失敗したテストのみ実行
› Press o to only run tests for changed files. # 変更ファイル関連のみ
› Press p to filter by filename regex pattern. # ファイル名でフィルタ
› Press t to filter by test name regex pattern. # テスト名でフィルタ
› Press q to quit watch mode. # 終了
› Press Enter to trigger a test run. # 手動実行
高度なフィルタリング
ファイル名によるフィルタリング(p キー)
bash# p キーを押した後の操作
Pattern Mode Usage
› Press Esc to exit pattern mode.
› Press Enter to filter by a filename regex pattern.
# 例:Buttonに関連するテストのみ実行
pattern › Button
# 実行結果
Pattern matches 3 files
› src/components/Button.test.js
› src/components/ButtonGroup.test.js
› src/components/__tests__/CustomButton.test.js
テスト名によるフィルタリング(t キー)
bash# t キーを押した後の操作
Test name pattern Mode Usage
› Press Esc to exit pattern mode.
› Press Enter to filter by a test name regex pattern.
# 例:バリデーションに関するテストのみ実行
testNamePattern › validation
# 実行結果
Test name pattern matches 5 tests
› email validation
› password validation
› form validation
› input validation
› user validation
失敗テストの効率的な対応
失敗テストのみの実行(f キー)
bash# 失敗テストがある場合の出力例
FAIL src/utils/validation.test.js
● Email validation › should validate email format
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
at Object.<anonymous> (src/utils/validation.test.js:12:23)
Test Suites: 1 failed, 2 passed, 3 total
Tests: 1 failed, 8 passed, 9 total
# f キーを押すと失敗したテストのみ再実行
Watch Usage
› Press f to run only failed tests.
› Press a to run all tests.
watch プラグインの活用
標準プラグインの紹介
Jest には、watch モードをさらに強化する標準プラグインが用意されています。
jest-watch-typeahead
ファイル名やテスト名の入力を自動補完してくれるプラグインです。
インストール
bashyarn add --dev jest-watch-typeahead
設定
javascript// jest.config.js
module.exports = {
// 他の設定...
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
};
使用例
bash# Watch モード開始
yarn test --watch
# 新しいオプションが追加される
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
# p キーを押すとタイプアヘッド機能が有効になる
pattern › But
Start typing to filter by a filename regex pattern.
# 候補が表示される
› Button.test.js
› ButtonGroup.test.js
› CustomButton.test.js
jest-watch-select-projects
モノレポ環境で特定のプロジェクトのみを選択実行できるプラグインです。
インストール
bashyarn add --dev jest-watch-select-projects
設定
javascript// jest.config.js
module.exports = {
projects: [
{
displayName: 'frontend',
testMatch: [
'<rootDir>/packages/frontend/**/*.test.js',
],
},
{
displayName: 'backend',
testMatch: [
'<rootDir>/packages/backend/**/*.test.js',
],
},
{
displayName: 'shared',
testMatch: ['<rootDir>/packages/shared/**/*.test.js'],
},
],
watchPlugins: ['jest-watch-select-projects'],
};
使用例
bash# Watch モード開始
yarn test --watch
# 新しいオプションが追加される
Watch Usage
› Press s to select projects.
› Press a to run all tests.
› Press f to run only failed tests.
# s キーを押すとプロジェクト選択画面が表示される
Select projects to run:
› ◯ frontend (3 test suites)
› ◯ backend (5 test suites)
› ◯ shared (2 test suites)
# スペースキーで選択・解除、Enterで決定
Select projects to run:
› ◉ frontend (3 test suites)
› ◯ backend (5 test suites)
› ◉ shared (2 test suites)
カスタムプラグインの作成
独自の watch プラグインを作成することで、プロジェクト固有のニーズに対応できます。
基本的なプラグイン構造
javascript// jest-watch-custom-plugin.js
class CustomWatchPlugin {
constructor({ stdin, stdout, config, testPathPattern }) {
this.stdin = stdin;
this.stdout = stdout;
this.config = config;
this.testPathPattern = testPathPattern;
}
// プラグインの名前
getUsageInfo() {
return {
key: 'c',
prompt: 'カスタムアクションを実行',
};
}
// キーが押された時の処理
run() {
return new Promise((resolve) => {
this.stdout.write(
'\nカスタムプラグインが実行されました!\n'
);
// ここにカスタムロジックを実装
this.customAction();
resolve();
});
}
customAction() {
// カスタムアクション例:カバレッジレポートの生成
const { spawn } = require('child_process');
const coverage = spawn('yarn', ['test', '--coverage'], {
stdio: 'inherit',
});
coverage.on('close', (code) => {
if (code === 0) {
this.stdout.write(
'カバレッジレポートが生成されました!\n'
);
} else {
this.stdout.write('エラーが発生しました\n');
}
});
}
}
module.exports = CustomWatchPlugin;
実用的なカスタムプラグイン例
Linting プラグイン
javascript// jest-watch-lint-plugin.js
class LintWatchPlugin {
getUsageInfo() {
return {
key: 'l',
prompt: 'ESLint を実行',
};
}
async run() {
const { spawn } = require('child_process');
return new Promise((resolve) => {
console.log('\n🔍 ESLint を実行中...\n');
const lint = spawn('yarn', ['lint'], {
stdio: 'inherit',
});
lint.on('close', (code) => {
if (code === 0) {
console.log('\n✅ ESLint チェック完了\n');
} else {
console.log(
'\n❌ ESLint エラーが発見されました\n'
);
}
resolve();
});
});
}
}
module.exports = LintWatchPlugin;
設定ファイルでの登録
javascript// jest.config.js
module.exports = {
// 他の設定...
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
'<rootDir>/jest-watch-custom-plugin.js',
'<rootDir>/jest-watch-lint-plugin.js',
],
};
パフォーマンス最適化
監視対象の絞り込み
大規模プロジェクトでは、監視対象を適切に絞り込むことが重要です。
ファイル除外設定の最適化
javascript// jest.config.js
module.exports = {
// 監視対象から除外するパターン
watchPathIgnorePatterns: [
// 基本的な除外
'/node_modules/',
'/build/',
'/dist/',
'/coverage/',
// 大容量ファイルの除外
'\\.bundle\\.js$',
'\\.chunk\\.js$',
'\\.map$',
// 一時ファイルの除外
'\\.tmp$',
'\\.temp$',
'\\.log$',
'\\.cache/',
// ドキュメント関連
'/docs/',
'/documentation/',
'\\.md$',
// 設定ファイル(頻繁に変更されない)
'webpack\\.config\\.js$',
'babel\\.config\\.js$',
'\\.eslintrc',
],
// テストファイルのパターンを限定
testMatch: [
'<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}',
'<rootDir>/src/**/*.{test,spec}.{js,jsx,ts,tsx}',
],
// 特定のディレクトリのみ監視
roots: ['<rootDir>/src'],
};
条件付き監視設定
javascript// jest.config.js
const isCI = process.env.CI === 'true';
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
// CI環境では監視を無効化
watchman: !isCI,
// 開発環境でのみ詳細な監視を有効化
watchPathIgnorePatterns: isProduction
? ['/node_modules/', '/build/', '/dist/']
: ['/node_modules/', '/build/', '/dist/', '/coverage/'],
// 環境に応じた並列実行数の調整
maxWorkers: isCI ? 2 : '50%',
};
メモリ使用量の最適化
Watch モードでのメモリ使用量を最適化するテクニックを紹介します。
Node.js メモリ設定
bash# package.json
{
"scripts": {
"test:watch": "node --max-old-space-size=4096 node_modules/.bin/jest --watch",
"test:watch:light": "node --max-old-space-size=2048 node_modules/.bin/jest --watch --maxWorkers=2"
}
}
Jest 設定の最適化
javascript// jest.config.js
module.exports = {
// キャッシュの有効化
cache: true,
cacheDirectory: '<rootDir>/.jest-cache',
// 並列実行の制限
maxWorkers: process.env.CI ? 2 : '50%',
// タイムアウトの設定
testTimeout: 10000,
// 不要な機能の無効化
collectCoverage: false, // Watch モードではカバレッジを無効化
verbose: false, // 詳細出力を無効化
// トランスフォームの最適化
transform: {
'^.+\\.(js|jsx|ts|tsx)$': [
'babel-jest',
{
// Babel キャッシュの有効化
cacheDirectory: true,
// 最小限の変換設定
presets: [
[
'@babel/preset-env',
{ targets: { node: 'current' } },
],
'@babel/preset-react',
],
},
],
},
};
メモリ監視とアラート
javascript// scripts/memory-monitor.js
const { spawn } = require('child_process');
function monitorMemory() {
const jest = spawn('yarn', ['test', '--watch'], {
stdio: 'inherit',
});
// メモリ使用量の監視
const memoryCheck = setInterval(() => {
const used = process.memoryUsage();
const usedMB = Math.round(used.heapUsed / 1024 / 1024);
if (usedMB > 1000) {
console.warn(
`⚠️ メモリ使用量が高くなっています: ${usedMB}MB`
);
}
if (usedMB > 2000) {
console.error(
`🚨 メモリ使用量が危険レベルです: ${usedMB}MB`
);
}
}, 5000);
jest.on('exit', () => {
clearInterval(memoryCheck);
});
}
if (require.main === module) {
monitorMemory();
}
チーム開発での運用
設定の共有方法
共通設定ファイルの作成
javascript// jest.config.base.js - チーム共通の基本設定
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
// 共通の監視設定
watchPathIgnorePatterns: [
'/node_modules/',
'/build/',
'/dist/',
'/coverage/',
],
// 共通のプラグイン
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
// 共通の変換設定
transform: {
'^.+\\.(js|jsx|ts|tsx)$': [
'babel-jest',
{ cacheDirectory: true },
],
},
};
javascript// jest.config.js - プロジェクト固有の設定
const baseConfig = require('./jest.config.base');
module.exports = {
...baseConfig,
// プロジェクト固有の設定を追加
moduleNameMapping: {
'^@/(.*)$': '<rootDir>/src/$1',
'^@components/(.*)$': '<rootDir>/src/components/$1',
},
};
開発環境の標準化
javascript// .vscode/settings.json - VS Code チーム設定
{
"jest.jestCommandLine": "yarn test --watch",
"jest.autoRun": {
"watch": true,
"onStartup": ["all-tests"]
},
"jest.showCoverageOnLoad": false,
"jest.enableInlineErrorMessages": true
}
新メンバーオンボーディング
markdown# 開発環境セットアップガイド
## 必要な設定
### 1. Jest Watch モードの開始
```bash
yarn test:watch
```
2. 推奨 VS Code 拡張機能
- Jest
- Jest Runner
- Test Explorer UI
3. 基本的な操作
p
キー: ファイル名でフィルタt
キー: テスト名でフィルタf
キー: 失敗テストのみ実行a
キー: 全テスト実行
4. トラブルシューティング
- メモリ不足の場合:
yarn test:watch:light
- Git エラーの場合:
git init && git add . && git commit -m "init"
arduino
## CI/CDとの使い分け
### 環境別設定の分離
```javascript
// jest.config.js
const isCI = process.env.CI === 'true';
module.exports = {
// CI環境では監視を無効化
watchman: !isCI,
// 開発環境でのみ watch プラグインを有効化
watchPlugins: isCI ? [] : [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
// CI環境では全テスト実行、開発環境では関連テストのみ
testPathIgnorePatterns: isCI ? [] : [
'/integration-tests/',
'/e2e-tests/',
],
// 環境別の並列実行設定
maxWorkers: isCI ? 2 : '50%',
};
GitHub Actions での設定例
yaml# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'yarn'
- name: Install dependencies
run: yarn install --frozen-lockfile
# CI環境では --watchAll=false を使用
- name: Run tests
run: yarn test --watchAll=false --coverage --maxWorkers=2
env:
CI: true
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
開発環境と CI 環境の使い分け
環境 | 推奨設定 | 目的 |
---|---|---|
開発 | --watch | 関連テストの高速実行 |
開発 | --watchAll | 全体的な影響確認 |
CI | --watchAll=false | 全テストの一回実行 |
CI | --coverage | カバレッジ測定 |
CI | --maxWorkers=2 | リソース制限への対応 |
本番前 | --watchAll --coverage | 最終的な品質確認 |
まとめ
Jest の --watch
オプションは、単なるファイル監視機能を超えて、開発体験を劇的に改善する強力なツールです。本記事で紹介した活用術を実践することで、以下のメリットを得られるでしょう。
主要な改善効果
開発効率の向上
- 手動でのテスト実行作業から解放
- フィードバックサイクルの短縮(数十秒 → 数秒)
- 集中力を維持した開発フローの実現
品質の向上
- バグの早期発見・修正
- リファクタリングに対する心理的障壁の軽減
- 継続的な品質保証
チーム開発の効率化
- 統一された開発体験の提供
- 新メンバーのオンボーディング支援
- コードレビューでの品質向上
実践のポイント
段階 | 重要なポイント | 期待される効果 |
---|---|---|
導入 | 基本的な --watch から始める | 即座に効果を実感 |
発展 | プラグインとフィルタリングの活用 | より精密な制御が可能 |
最適化 | パフォーマンスチューニング | 大規模プロジェクトでも快適な動作 |
チーム化 | 設定の標準化と共有 | チーム全体の生産性向上 |
今後の展望
Jest の --watch
オプションは、モダンなフロントエンド開発において欠かせない機能となっています。React、Vue、Angular などのフレームワークとの統合もさらに進化しており、開発者の体験は今後も向上し続けるでしょう。
実践への第一歩
この記事で学んだ内容を活かして、まずは日常の開発作業に --watch
オプションを取り入れてみてください。小さな改善の積み重ねが、大きな生産性向上につながります。快適な開発体験を通じて、より良いソフトウェアを作り上げていきましょう。
関連リンク
- review
新しい自分に会いに行こう!『自分の変え方』村岡大樹の認知科学コーチングで人生リセット
- review
科学革命から AI 時代へ!『サピエンス全史 下巻』ユヴァル・ノア・ハラリが予見する人類の未来
- review
人類はなぜ地球を支配できた?『サピエンス全史 上巻』ユヴァル・ノア・ハラリが解き明かす驚愕の真実
- review
え?世界はこんなに良くなってた!『FACTFULNESS』ハンス・ロスリングが暴く 10 の思い込みの正体
- review
瞬時に答えが出る脳に変身!『ゼロ秒思考』赤羽雄二が贈る思考力爆上げトレーニング
- review
関西弁のゾウに人生変えられた!『夢をかなえるゾウ 1』水野敬也が教えてくれた成功の本質