Watch Plugins

The Jest watch plugin system provides a way to hook into specific parts of Jest and to define watch mode menu prompts that execute code on key press. Combined, these features allow you to develop interactive experiences custom for your workflow. Combined, these features allow you to develop interactive experiences custom for your workflow.

Watch Plugin Interface

  1. class MyWatchPlugin {
  2. // Add hooks to Jest lifecycle events
  3. apply(jestHooks) {}
  4. // Get the prompt information for interactive plugins
  5. getUsageInfo(globalConfig) {}
  6. // Executed when the key from `getUsageInfo` is input
  7. run(globalConfig, updateConfigAndRun) {}
  8. }

Hooking into Jest

To connect your watch plugin to Jest, add its path under watchPlugins in your Jest configuration:

jest.config.js

  1. module.exports = {
  2. // ...
  3. // jest.config.js
  4. module.exports = {
  5. // ...
  6. watchPlugins: ['path/to/yourWatchPlugin'],
  7. };

Custom watch plugins can add hooks to Jest events. Custom watch plugins can add hooks to Jest events. These hooks can be added either with or without having an interactive key in the watch mode menu.

apply(jestHooks)

Jest hooks can be attached by implementing the apply method. 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.

  1. class MyWatchPlugin {
  2. apply(jestHooks) {}
  3. }

Below are the hooks available in Jest.

jestHooks.shouldRunTestSuite(testSuiteInfo)

Returns a boolean (or Promise<boolean> for handling asynchronous operations) to specify if a test should be run or not.

例如:

  1. class MyWatchPlugin {
  2. apply(jestHooks) {
  3. jestHooks.shouldRunTestSuite(testSuiteInfo => {
  4. return testSuiteInfo.testPath.includes('my-keyword');
  5. });
  6. // or a promise
  7. jestHooks.shouldRunTestSuite(testSuiteInfo => {
  8. return Promise.resolve(testSuiteInfo.testPath.includes('my-keyword'));
  9. });
  10. }
  11. }

jestHooks.onTestRunComplete(results)

Gets called at the end of every test run. It has the test results as an argument. It has the test results as an argument.

例如:

  1. class MyWatchPlugin {
  2. apply(jestHooks) {
  3. jestHooks.onTestRunComplete(results => {
  4. this._hasSnapshotFailure = results.snapshot.failure;
  5. });
  6. }
  7. }

jestHooks.onFileChange({projects})

Gets called whenever there is a change in the file system

  • projects: Array<config: ProjectConfig, testPaths: Array<string>: Includes all the test paths that Jest is watching.

例如:

  1. class MyWatchPlugin {
  2. apply(jestHooks) {
  3. jestHooks.onFileChange(({projects}) => {
  4. this._projects = projects;
  5. });
  6. }
  7. }

Watch Menu Integration

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:

  1. class MyWatchPlugin {
  2. getUsageInfo(globalConfig) {
  3. return {
  4. key: 's',
  5. prompt: 'do something',
  6. };
  7. }
  8. }

This will add a line in the watch mode menu (› Press s to do something.)

  1. Watch Usage
  2. Press p to filter by a filename regex pattern.
  3. Press t to filter by a test name regex pattern.
  4. Press q to quit watch mode.
  5. Press s to do something. // <-- This is our plugin
  6. Press Enter to trigger a test run.
  7. Press t to filter by a test name regex pattern.
  8. Press q to quit watch mode.
  9. Press s to do something. // <-- This is our plugin
  10. Press Enter to trigger a test run.

Note: 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. 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 configuration
  • updateConfigAndRun: Allows you to trigger a test run while the interactive plugin is running.
  1. class MyWatchPlugin {
  2. run(globalConfig, updateConfigAndRun) {
  3. // do something.
  4. }
  5. }
  6. }
  7. }

Note: If you do call updateConfigAndRun, your run method should not resolve to a truthy value, as that would trigger a double-run.

Authorized configuration keys

For stability and safety reasons, only part of the global configuration keys can be updated with updateConfigAndRun. The current white list is as follows: The current white list is as follows:

Customization

Plugins can be customized via your Jest configuration.

jest.config.js

  1. module.exports = {
  2. // ...
  3. // jest.config.js
  4. module.exports = {
  5. // ...
  6. watchPlugins: [
  7. [
  8. 'path/to/yourWatchPlugin',
  9. {
  10. key: 'k', // <- your custom key
  11. prompt: 'show a custom prompt',
  12. },
  13. ],
  14. ],
  15. };

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.

  1. class MyWatchPlugin {
  2. constructor({config}) {}
  3. }

Choosing a good key

Jest allows third-party plugins to override some of its built-in feature keys, but not all. Jest allows third-party plugins to override some of its built-in feature keys, but not all. 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)

Any key not used by built-in functionality can be claimed, as you would expect. 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.)

When a conflict happens

Should your plugin attempt to overwrite a reserved key, Jest will error out with a descriptive message, something like:

Watch plugin YourFaultyPlugin attempted to register key q, that is reserved internally for quitting watch mode. Please change the configuration key for this plugin. 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). When this happens, you’ll also get an error message that tries to help you fix that: When this happens, you’ll also get an error message that tries to help you fix that:

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. Please change the key configuration for one of the conflicting plugins to avoid overlap.