Watch プラグイン
JestのWatchプラグイン機能は、Jestの指定した箇所にフックする方法を提供し、キーの押下時にコードを実行するwatchモードのメニュープロンプトを定義します。 これらの機能を組み合わせることで、あなたのワークフロー向けにカスタマイズされた対話型な開発環境を作成できます。
Watchプラグインインターフェース
class MyWatchPlugin {
// Add hooks to Jest lifecycle events
apply(jestHooks) {}
// Get the prompt information for interactive plugins
getUsageInfo(globalConfig) {}
// Executed when the key from `getUsageInfo` is input
run(globalConfig, updateConfigAndRun) {}
}
Jest にフックする
To connect your watch plugin to Jest, add its path under watchPlugins in your Jest configuration:
jest.config.js
module.exports = {
// ...
watchPlugins: ['path/to/yourWatchPlugin'],
};
独自のwatchプラグインはJestイベントにフックを追加できます。 これらのフックは、watchモードメニューでインタラクティブキーの有無にかかわらず追加できます。
apply(jestHooks)
Jest hooks can be attached by implementing the apply method. This method receives a jestHooks argument that allows the plugin to hook into specific parts of the lifecycle of a test run.
class MyWatchPlugin {
apply(jestHooks) {}
}
以下で、Jest で使用可能なフックを紹介します。
jestHooks.shouldRunTestSuite(testSuiteInfo)
Returns a boolean (or Promise<boolean> for handling asynchronous operations) to specify if a test should be run or not.
例:
class MyWatchPlugin {
apply(jestHooks) {
jestHooks.shouldRunTestSuite(testSuiteInfo => {
return testSuiteInfo.testPath.includes('my-keyword');
});
// or a promise
jestHooks.shouldRunTestSuite(testSuiteInfo => {
return Promise.resolve(testSuiteInfo.testPath.includes('my-keyword'));
});
}
}
jestHooks.onTestRunComplete(results)
各テストの実行の終わりに呼ばれます。 テスト結果が引数として渡されます。
例:
class MyWatchPlugin {
apply(jestHooks) {
jestHooks.onTestRunComplete(results => {
this._hasSnapshotFailure = results.snapshot.failure;
});
}
}
jestHooks.onFileChange({projects})
ファイルシステムに変更があるたびに呼ばれます。
projects: Array<config: ProjectConfig, testPaths: Array<string>: Includes all the test paths that Jest is watching.
例:
class MyWatchPlugin {
apply(jestHooks) {
jestHooks.onFileChange(({projects}) => {
this._projects = projects;
});
}
}