Aller au contenu principal
Version : 29.7

Plugins de surveillance

Le système de plugins de surveillance (NdT watch) de Jest permet d'accéder à des parties spécifiques de Jest et de définir des invites de menu en mode de surveillance qui exécutent du code en appuyant sur une touche. Combinées, ces fonctionnalités vous permettent de développer des expériences interactives personnalisées pour votre flux de travail.

Interface du plugin de surveillance

class MyWatchPlugin {
// Ajoute des hooks aux événements du cycle de vie de Jest
apply(jestHooks) {}

// Récupère les informations de l'invite pour les plugins interactifs
getUsageInfo(globalConfig) {}

// Exécuté lorsque la clé de `getUsageInfo` est entrée
run(globalConfig, updateConfigAndRun) {}
}

Faire des hooks dans 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'],
};

Les plugins de surveillance personnalisés peuvent ajouter des hooks aux événements Jest. Ces hooks peuvent être ajoutés avec ou sans touche interactive dans le menu du mode surveillance.

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) {}
}

Ci-dessous se trouvent les hooks disponibles en Jest.

jestHooks.shouldRunTestSuite(testSuiteInfo)

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

Par exemple :

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)

Est appelé à la fin de chaque test. Il a les résultats du test comme argument.

Par exemple :

class MyWatchPlugin {
apply(jestHooks) {
jestHooks.onTestRunComplete(results => {
this._hasSnapshotFailure = results.snapshot.failure;
});
}
}

jestHooks.onFileChange({projects})

Est appelé à chaque fois qu'il y a un changement dans le système de fichiers

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

Par exemple :

class MyWatchPlugin {
apply(jestHooks) {
jestHooks.onFileChange(({projects}) => {
this._projects = projects;
});
}
}

Intégration du menu de surveillance

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: 'do something',
};
}
}

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.
remarque

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

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

Touches de configuration autorisées

For stability and safety reasons, only part of the global configuration keys can be updated with updateConfigAndRun. La liste blanche actuelle est la suivante :

Personnalisation

Les plugins peuvent être personnalisés via votre configuration Jest.

jest.config.js
module.exports = {
// ...
watchPlugins: [
[
'path/to/yourWatchPlugin',
{
key: 'k', // <- your custom key
prompt: 'show a custom prompt',
},
],
],
};

Noms de configuration recommandés :

  • key: Modifies the plugin key.
  • prompt: Allows user to customize the text in the plugin prompt.

Si l'utilisateur a fourni une configuration personnalisée, elle sera passée comme argument au constructeur du plugin.

class MyWatchPlugin {
constructor({config}) {}
}

Choix d'une bonne touche

Jest permet aux plugins tiers de surcharger certaines de ses touches de fonctionnalités intégrées, mais pas toutes. 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)

Toute touche non utilisée par la fonctionnalité intégrée peut être invoquée, comme on peut s'y attendre. 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.)

Quand un conflit se produit

Si votre plugin tente d'écraser une touche réservée, Jest émettra une erreur avec un message descriptif, quelque chose du genre :


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). Lorsque cela se produit, vous recevrez également un message d’erreur qui tente de vous aider à corriger ceci :


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.