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:
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;
});
}
}
Watch メニューの統合
Custom watch plugins can also add or override functionality to the watch menu by specifying a key/prompt pair in getUsageInfo method and a run method for the execution of the key.
getUsageInfo(globalConfig)
To add a key to the watch menu, implement the getUsageInfo method, returning a key and the prompt:
class MyWatchPlugin {
getUsageInfo(globalConfig) {
return {
key: 's',
prompt: '何かをする',
};
}
}
This will add a line in the watch mode menu (› Press s to do something.)
Watch Usage
› 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 s to do something. // <-- This is our plugin
› Press Enter to trigger a test run.
If the key for your plugin already exists as a default key, your plugin will override that key.
run(globalConfig, updateConfigAndRun)
To handle key press events from the key returned by getUsageInfo, you can implement the run method. This method returns a Promise<boolean> that can be resolved when the plugin wants to return control to Jest. The boolean specifies if Jest should rerun the tests after it gets the control back.
globalConfig: A representation of Jest's current global configurationupdateConfigAndRun: Allows you to trigger a test run while the interactive plugin is running.
class MyWatchPlugin {
run(globalConfig, updateConfigAndRun) {
// do something.
}
}
If you do call updateConfigAndRun, your run method should not resolve to a truthy value, as that would trigger a double-run.
認証済みの設定キー
For stability and safety reasons, only part of the global configuration keys can be updated with updateConfigAndRun. 現在のホワイト・リストは以下の通りです。
bailchangedSincecollectCoveragecollectCoverageFromcoverageDirectorycoverageReportersnotifynotifyModeonlyFailuresreporterstestNamePatterntestPathPatternsupdateSnapshotverbose
カスタマイズ
Plugins can be customized via your Jest configuration.
module.exports = {
// ...
watchPlugins: [
[
'path/to/yourWatchPlugin',
{
key: 'k', // <- your custom key
prompt: 'show a custom prompt',
},
],
],
};
Recommended config names:
key: Modifies the plugin key.prompt: Allows user to customize the text in the plugin prompt.
If the user provided a custom configuration, it will be passed as an argument to the plugin constructor.
class MyWatchPlugin {
constructor({config}) {}
}
良いキーの選択
Jestはサードパーティー製のプラグインによる、いくつかの組み込み機能キーを上書きを許可していますが、すべてではありません。 Specifically, the following keys are not overwritable :
c(clears filter patterns)i(updates non-matching snapshots interactively)q(quits)u(updates all non-matching snapshots)w(displays watch mode usage / available actions)
The following keys for built-in functionality can be overwritten :
p(test filename pattern)t(test name pattern)
組み込み機能で使用されていないキーは、すべて好きなように設定することができます。 Try to avoid using keys that are difficult to obtain on various keyboards (e.g. é, €), or not visible by default (e.g. many Mac keyboards do not have visual hints for characters such as |, \, [, etc.)
競合が発生するケース
プラグインが予約語のキーを上書きしようとすると、Jest は以下のような説明的文を表示してエラーになります。
Watch plugin YourFaultyPlugin attempted to register key `q`, that is reserved internally for quitting watch mode. Please change the configuration key for this plugin.
Third-party plugins are also forbidden to overwrite a key reserved already by another third-party plugin present earlier in the configured plugins list (watchPlugins array setting). この強豪が発生すると、次のようなエラーメッセージが表示されます。
Watch plugins YourFaultyPlugin and TheirFaultyPlugin both attempted to register key `x`. Please change the key configuration for one of the conflicting plugins to avoid overlap.