Configuration de Jest
La philosophie de Jest est de fonctionner parfaitement par défaut, mais parfois vous avez besoin de plus de possibilités de configuration.
Il est recommandé de définir la configuration dans un fichier JavaScript dédié, TypeScript ou JSON. The file will be discovered automatically, if it is named jest.config.js|ts|mjs|cjs|json. You can use --config flag to pass an explicit path to the file.
Gardez à l'esprit que l'objet de configuration qui en résulte doit toujours être sérialisable en JSON.
Le fichier de configuration devrait simplement exporter un objet :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
verbose: true,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
verbose: true,
};
export default config;
Ou une fonction renvoyant un objet :
- JavaScript
- TypeScript
/** @returns {Promise<import('jest').Config>} */
module.exports = async () => {
return {
verbose: true,
};
};
import type {Config} from 'jest';
export default async (): Promise<Config> => {
return {
verbose: true,
};
};
To read TypeScript configuration files Jest requires ts-node. Assurez-vous qu'il soit installé dans votre projet.
La configuration peut également être stockée dans un fichier JSON en tant qu'objet simple :
{
"bail": 1,
"verbose": true
}
Alternatively Jest's configuration can be defined through the "jest" key in the package.json of your project:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
Options
You can retrieve Jest's defaults from jest-config to extend them if needed:
- JavaScript
- TypeScript
const {defaults} = require('jest-config');
/** @type {import('jest').Config} */
const config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts', 'cts'],
};
module.exports = config;
import type {Config} from 'jest';
import {defaults} from 'jest-config';
const config: Config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts'],
};
export default config;
automock[boolean]bail[number | boolean]cacheDirectory[string]clearMocks[boolean]collectCoverage[boolean]collectCoverageFrom[array]coverageDirectory[string]coveragePathIgnorePatterns[array<string>]coverageProvider[string]coverageReporters[array<string | [string, options]>]coverageThreshold[object]dependencyExtractor[string]displayName[string, object]errorOnDeprecated[boolean]extensionsToTreatAsEsm[array<string>]fakeTimers[object]forceCoverageMatch[array<string>]globals[object]globalSetup[string]globalTeardown[string]haste[object]injectGlobals[boolean]maxConcurrency[number]maxWorkers[number | string]moduleDirectories[array<string>]moduleFileExtensions[array<string>]moduleNameMapper[object<string, string | array<string>>]modulePathIgnorePatterns[array<string>]modulePaths[array<string>]notify[boolean]notifyMode[string]openHandlesTimeout[number]preset[string]prettierPath[string]projects[array<string | ProjectConfig>]randomize[boolean]reporters[array<moduleName | [moduleName, options]>]resetMocks[boolean]resetModules[boolean]resolver[string]restoreMocks[boolean]rootDir[string]roots[array<string>]runtime[string]runner[string]sandboxInjectedGlobals[array<string>]setupFiles[array]setupFilesAfterEnv[array]showSeed[boolean]slowTestThreshold[number]snapshotFormat[object]snapshotResolver[string]snapshotSerializers[array<string>]testEnvironment[string]testEnvironmentOptions[Object]testFailureExitCode[number]testMatch[array<string>]testPathIgnorePatterns[array<string>]testRegex[string | array<string>]testResultsProcessor[string]testRunner[string]testSequencer[string]testTimeout[number]transform[object<string, pathToTransformer | [pathToTransformer, object]>]transformIgnorePatterns[array<string>]unmockedModulePathPatterns[array<string>]verbose[boolean]watchPathIgnorePatterns[array<string>]watchPlugins[array<string | [string, Object]>]watchman[boolean]workerIdleMemoryLimit[number|string]//[string]workerThreads
Référence
automock [boolean]
Default: false
Cette option indique à Jest que tous les modules importés dans vos tests doivent être simulés automatiquement. Tous les modules utilisés dans vos tests auront une implémentation de remplacement, en conservant la surface de l'API.
Exemple :
export default {
authorize: () => 'token',
isAuthorized: secret => secret === 'wizard',
};
import utils from '../utils';
test('if utils mocked automatically', () => {
// Public methods of `utils` are now mock functions
expect(utils.authorize.mock).toBeTruthy();
expect(utils.isAuthorized.mock).toBeTruthy();
// You can provide them with your own implementation
// or pass the expected return value
utils.authorize.mockReturnValue('mocked_token');
utils.isAuthorized.mockReturnValue(true);
expect(utils.authorize()).toBe('mocked_token');
expect(utils.isAuthorized('not_wizard')).toBeTruthy();
});
Node modules are automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js). More info here.
Node.js core modules, like fs, are not mocked by default. They can be mocked explicitly, like jest.mock('fs').
bail [number | boolean]
Default: 0
Par défaut, Jest exécute tous les tests et produit toutes les erreurs dans la console à la fin. The bail config option can be used here to have Jest stop running tests after n failures. Setting bail to true is the same as setting bail to 1.
cacheDirectory [string]
Default: "/tmp/<path>"
Le répertoire où Jest doit stocker ses informations de dépendance en cache.
Avant d'exécuter les tests, Jest tente d’analyser votre arborescence de dépendances (en amont) et met ces résultats en cache afin d’alléger les accès au système de fichiers qui doivent se produire lors de l’exécution des tests. Cette option de configuration vous permet de personnaliser le répertoire où Jest stocke ces données.
clearMocks [boolean]
Default: false
Efface automatiquement les appels, les instances, les contextes et les résultats des simulations avant chaque test. Equivalent to calling jest.clearAllMocks() before each test. Cela ne supprime aucune implémentation simulée qui aurait pu être fournie.
collectCoverage [boolean]
Default: false
Indique si les informations de couverture doivent être collectées lors de l'exécution du test. Étant donné que cette opération modifie tous les fichiers exécutés avec des instructions de collecte de couverture, elle peut ralentir considérablement vos tests.
Jest ships with two coverage providers: babel (default) and v8. See the coverageProvider option for more details.
The babel and v8 coverage providers use /* istanbul ignore next */ and /* c8 ignore next */ comments to exclude lines from coverage reports, respectively. For more information, you can view the istanbuljs documentation and the c8 documentation.
collectCoverageFrom [array]
Default: undefined
An array of glob patterns indicating a set of files for which coverage information should be collected. Si un fichier correspond au pattern glob spécifié, des informations de couverture seront collectées pour ce fichier, même si aucun test n'existe pour ce fichier et qu'il n'est jamais requis dans la suite de tests.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
export default config;
This will collect coverage information for all the files inside the project's rootDir, except the ones that match **/node_modules/** or **/vendor/**.
Chaque pattern glob est appliqué dans l'ordre dans lequel ils sont spécifiés dans la configuration. For example ["!**/__tests__/**", "**/*.js"] will not exclude __tests__ because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after **/*.js.
This option requires collectCoverage to be set to true or Jest to be invoked with --coverage.
Help:
If you are seeing coverage output such as...
=============================== Coverage summary ===============================
Statements : Unknown% ( 0/0 )
Branches : Unknown% ( 0/0 )
Functions : Unknown% ( 0/0 )
Lines : Unknown% ( 0/0 )
================================================================================
Jest: Coverage data for global was not found.
Il est très probable que vos patterns glob ne correspondent à aucun fichier. Refer to the micromatch documentation to ensure your globs are compatible.
coverageDirectory [string]
Default: undefined
Le répertoire où Jest doit écrire les fichiers de couverture.
coveragePathIgnorePatterns [array<string>]
Default: ["/node_modules/"]
Un tableau de chaînes de patterns regexp qui sont comparées à tous les chemins de fichiers avant d'exécuter le test. Si le chemin du fichier correspond à l'un des patterns, l'information de couverture sera ignorée.
Ces chaînes de patterns correspondent au chemin d'accès complet. Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/", "<rootDir>/node_modules/"].
coverageProvider [string]
Indique quel fournisseur doit être utilisé pour instrumenter le code pour la couverture. Allowed values are babel (default) or v8.
coverageReporters [array<string | [string, options]>]
Default: ["clover", "json", "lcov", "text"]
Une liste de noms de rapporteurs que Jest utilise lors de la rédaction de rapports de couverture. Any istanbul reporter can be used.
La configuration de cette option remplace les valeurs par défaut. Add "text" or "text-summary" to see a coverage summary in the console output.
Des options supplémentaires peuvent être passées en utilisant la forme tuple. Par exemple, vous pouvez cacher les lignes de déclaration de couverture pour tous les fichiers couverts :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
export default config;
For more information about the options object shape refer to CoverageReporterWithOptions type in the type definitions.
coverageThreshold [object]
Default: undefined
Cela servira à configurer le seuil minimum pour les résultats de la couverture. Thresholds can be specified as global, as a glob, and as a directory or file path. Si les seuils ne sont pas atteints, jest échouera. Les seuils spécifiés en tant que nombre positif sont considérés comme le pourcentage minimum requis. Les seuils spécifiés comme un nombre négatif représentent le nombre maximum d'entités non couvertes autorisées.
Par exemple, avec la configuration suivante, jest échouera si la couverture des branches, des lignes et des fonctions est inférieure à 80%, ou s'il y a plus de 10 déclarations non couvertes :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
export default config;
If globs or paths are specified alongside global, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. Les seuils pour les globs sont appliqués à tous les fichiers correspondant à la glob. Si le fichier spécifié par le chemin d'accès n'est pas trouvé, une erreur sera retournée.
Par exemple, avec la configuration suivante :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
coverageThreshold: {
global: {
branches: 50,
functions: 50,
lines: 50,
statements: 50,
},
'./src/components/': {
branches: 40,
statements: 40,
},
'./src/reducers/**/*.js': {
statements: 90,
},
'./src/api/very-important-module.js': {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageThreshold: {
global: {
branches: 50,
functions: 50,
lines: 50,
statements: 50,
},
'./src/components/': {
branches: 40,
statements: 40,
},
'./src/reducers/**/*.js': {
statements: 90,
},
'./src/api/very-important-module.js': {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
};
export default config;
Jest échouera si :
- The
./src/componentsdirectory has less than 40% branch or statement coverage. - One of the files matching the
./src/reducers/**/*.jsglob has less than 90% statement coverage. - The
./src/api/very-important-module.jsfile has less than 100% coverage. - Every remaining file combined has less than 50% coverage (
global).
dependencyExtractor [string]
Default: undefined
Cette option permet l'utilisation d'un extracteur de dépendance personnalisé. It must be a node module that exports an object with an extract function. Par exemple :
const crypto = require('crypto');
const fs = require('fs');
module.exports = {
extract(code, filePath, defaultExtract) {
const deps = defaultExtract(code, filePath);
// Scanne le fichier et ajoute les dépendances dans `deps` (qui est un `Set`)
return deps;
},
getCacheKey() {
return crypto
.createHash('md5')
.update(fs.readFileSync(__filename))
.digest('hex');
},
};
The extract function should return an iterable (Array, Set, etc.) with the dependencies found in the code.
That module can also contain a getCacheKey function to generate a cache key to determine if the logic has changed and any cached artifacts relying on it should be discarded.
displayName [string, object]
default: undefined
Permet de placer un libellé à côté d'un test en cours d'exécution. Cela devient plus utile dans les dépôts multi-projets où il peut y avoir de nombreux fichiers de configuration jest. Ceci indique visuellement à quel projet appartient un test.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
displayName: 'CLIENT',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: 'CLIENT',
};
export default config;
Alternatively, an object with the properties name and color can be passed. Cela permet une configuration personnalisée de la couleur de fond de displayName. displayName defaults to white when its value is a string. Jest uses chalk to provide the color. As such, all of the valid options for colors supported by chalk are also supported by Jest.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
export default config;
errorOnDeprecated [boolean]
Default: false
Fait en sorte que l'appel d'API obsolètes génère des messages d'erreur utiles. Utile pour faciliter le processus de mise à jour.
extensionsToTreatAsEsm [array<string>]
Default: []
Jest will run .mjs and .js files with nearest package.json's type field set to module as ECMAScript Modules. Si vous avez d'autres fichiers qui devraient s'exécuter avec ESM natif, vous devez spécifier leur extension de fichier ici.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
extensionsToTreatAsEsm: ['.ts'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
extensionsToTreatAsEsm: ['.ts'],
};
export default config;
Jest's ESM support is still experimental, see its docs for more details.
fakeTimers [object]
Default: {}
Les faux temporisateurs peuvent être utiles lorsqu'un morceau de code définit un long délai d'attente que nous ne voulons pas attendre dans un test. For additional details see Fake Timers guide and API documentation.
Cette option fournit la configuration par défaut des faux temporisateurs pour tous les tests. Calling jest.useFakeTimers() in a test file will use these options or will override them if a configuration object is passed. For example, you can tell Jest to keep the original implementation of process.nextTick() and adjust the limit of recursive timers that will be run:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
export default config;
// install fake timers for this file using the options from Jest configuration
jest.useFakeTimers();
test('increase the limit of recursive timers for this and following tests', () => {
jest.useFakeTimers({timerLimit: 5000});
// ...
});
Instead of including jest.useFakeTimers() in each test file, you can enable fake timers globally for all tests in your Jest configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
},
};
export default config;
Options de configuration :
type FakeableAPI =
| 'Date'
| 'hrtime'
| 'nextTick'
| 'performance'
| 'queueMicrotask'
| 'requestAnimationFrame'
| 'cancelAnimationFrame'
| 'requestIdleCallback'
| 'cancelIdleCallback'
| 'setImmediate'
| 'clearImmediate'
| 'setInterval'
| 'clearInterval'
| 'setTimeout'
| 'clearTimeout';
type ModernFakeTimersConfig = {
/**
* If set to `true` all timers will be advanced automatically by 20 milliseconds
* every 20 milliseconds. A custom time delta may be provided by passing a number.
* The default is `false`.
*/
advanceTimers?: boolean | number;
/**
* List of names of APIs that should not be faked. The default is `[]`, meaning
* all APIs are faked.
*/
doNotFake?: Array<FakeableAPI>;
/** Whether fake timers should be enabled for all test files. The default is `false`. */
enableGlobally?: boolean;
/**
* Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.
* The default is `false`.
*/
legacyFakeTimers?: boolean;
/** Sets current system time to be used by fake timers, in milliseconds. The default is `Date.now()`. */
now?: number;
/** Maximum number of recursive timers that will be run. The default is `100_000` timers. */
timerLimit?: number;
};
Pour certaines raisons, il se peut que vous deviez utiliser une ancienne implémentation de faux temporisateurs. Voici comment l'activer globalement (les options supplémentaires ne sont pas prises en charge) :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
export default config;
forceCoverageMatch [array<string>]
Default: ['']
Les fichiers de test sont normalement ignorés de la collecte de la couverture de code. Avec cette option, vous pouvez écraser ce comportement et inclure les fichiers ignorés dans la couverture de code.
For example, if you have tests in source files named with .t.js extension as following:
export function sum(a, b) {
return a + b;
}
if (process.env.NODE_ENV === 'test') {
test('sum', () => {
expect(sum(1, 2)).toBe(3);
});
}
You can collect coverage from those files with setting forceCoverageMatch.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
forceCoverageMatch: ['**/*.t.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
forceCoverageMatch: ['**/*.t.js'],
};
export default config;
globals [object]
Default: {}
Un ensemble de variables globales qui doivent être disponibles dans tous les environnements de test.
For example, the following would create a global __DEV__ variable set to true in all test environments:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
globals: {
__DEV__: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
globals: {
__DEV__: true,
},
};
export default config;
If you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will not be persisted across test runs for other test files. In addition, the globals object must be json-serializable, so it can't be used to specify global functions. For that, you should use setupFiles.
globalSetup [string]
Default: undefined
Cette option permet l'utilisation d'un module de configuration global personnalisé, qui doit exporter une fonction (elle peut être sync ou async). The function will be triggered once before all test suites and it will receive two arguments: Jest's globalConfig and projectConfig.
Un module de configuration global configuré dans un projet (à l'aide d'un runner multi-projets) ne sera déclenché que lorsque vous exécuterez au moins un test de ce projet.
Any global variables that are defined through globalSetup can only be read in globalTeardown. Vous ne pouvez pas récupérer les globales définies ici dans vos suites de test.
While code transformation is applied to the linked setup-file, Jest will not transform any code in node_modules. This is due to the need to load the actual transformers (e.g. babel or typescript) to perform transformation.
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
// Set reference to mongod in order to close the server during teardown.
globalThis.__MONGOD__ = mongod;
};
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
await globalThis.__MONGOD__.stop();
};
globalTeardown [string]
Default: undefined
Cette option permet l'utilisation d'un module de nettoyage global personnalisé, qui doit exporter une fonction (elle peut être sync ou async). The function will be triggered once after all test suites and it will receive two arguments: Jest's globalConfig and projectConfig.
Un module de nettoyage global configuré dans un projet (à l'aide d'un runner multi-projets) ne sera déclenché que lorsque vous exécuterez au moins un test de ce projet.
The same caveat concerning transformation of node_modules as for globalSetup applies to globalTeardown.
haste [object]
Default: undefined
This will be used to configure the behavior of jest-haste-map, Jest's internal file crawler/cache system. Les options suivantes sont prises en charges :
type HasteConfig = {
/** Whether to hash files using SHA-1. */
computeSha1?: boolean;
/** The platform to use as the default, e.g. 'ios'. */
defaultPlatform?: string | null;
/** Force use of Node's `fs` APIs rather than shelling out to `find` */
forceNodeFilesystemAPI?: boolean;
/**
* Whether to follow symlinks when crawling for files.
* This options cannot be used in projects which use watchman.
* Projects with `watchman` set to true will error if this option is set to true.
*/
enableSymlinks?: boolean;
/** Path to a custom implementation of Haste. */
hasteImplModulePath?: string;
/** All platforms to target, e.g ['ios', 'android']. */
platforms?: Array<string>;
/** Whether to throw an error on module collision. */
throwOnModuleCollision?: boolean;
/** Custom HasteMap module */
hasteMapModulePath?: string;
/** Whether to retain all files, allowing e.g. search for tests in `node_modules`. */
retainAllFiles?: boolean;
};
injectGlobals [boolean]
Default: true
Insert Jest's globals (expect, test, describe, beforeEach etc.) into the global environment. If you set this to false, you should import from @jest/globals, e.g.
import {expect, jest, test} from '@jest/globals';
jest.useFakeTimers();
test('some test', () => {
expect(Date.now()).toBe(0);
});
This option is only supported using the default jest-circus test runner.
maxConcurrency [number]
Default: 5
A number limiting the number of tests that are allowed to run at the same time when using test.concurrent. Tout test dépassant cette limite sera mis en file d'attente et exécuté dès qu'un sera libéré.
maxWorkers [number | string]
Spécifie le maximum de processus que l'orchestrateur de processus lancera pour exécuter les tests. En mode d'exécution simple, il s'agit par défaut du nombre de cœurs disponibles sur votre machine, moins un pour le thread principal. En mode surveillance, il s'agit par défaut de la moitié des cœurs disponibles sur votre machine afin de s'assurer que Jest reste discret et ne paralyse pas votre machine. Il peut être utile d'utiliser cette option dans les environnements avec des ressources limitées comme les environnements de CI, mais la valeur par défaut devrait être suffisante pour la plupart des cas d’utilisation.
Pour les environnements avec des processeurs disponibles variables, vous pouvez utiliser une configuration basée sur le pourcentage :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
maxWorkers: '50%',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
maxWorkers: '50%',
};
export default config;
moduleDirectories [array<string>]
Default: ["node_modules"]
Un tableau de noms de répertoires à rechercher de manière récursive à partir de l'emplacement du module requis. Setting this option will override the default, if you wish to still search node_modules for packages include it along with any other options:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
export default config;
It is discouraged to use '.' as one of the moduleDirectories, because this prevents scoped packages such as @emotion/react from accessing packages with the same subdirectory name (react). See this issue for more details. In most cases, it is preferable to use the moduleNameMapper configuration instead.
moduleFileExtensions [array<string>]
Default: ["js", "mjs", "cjs", "jsx", "ts", "tsx", "json", "node"]
Un tableau d'extensions de fichiers que vos modules utilisent. Si vous demandez des modules sans spécifier d'extension de fichier, voici les extensions que Jest recherchera, dans l'ordre de gauche à droite.
Nous recommandons de placer les extensions les plus couramment utilisées dans votre projet sur la gauche, donc si vous utilisez TypeScript, vous pouvez envisager de déplacer "ts" et/ou "tsx" au début du tableau.
moduleNameMapper [object<string, string | array<string>>]
Default: null
Une correspondance entre les expressions régulières et les noms de modules ou les tableaux de noms de modules, qui permet d'extraire des ressources, comme des images ou des styles, avec un seul module.
Les modules qui sont associés à un alias sont dé-simulés par défaut, que la simulation automatique soit activé ou non.
Use <rootDir> string token to refer to rootDir value if you want to use file paths.
En outre, vous pouvez substituer des groupes de regex capturés en utilisant des rétro références numérotées.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
export default config;
L'ordre dans lequel les correspondances sont définies est important. Les patterns sont vérifiés un par un jusqu'à ce qu'il y en ait un qui convienne. La règle la plus spécifique doit être citée en premier. C'est également vrai pour les tableaux de noms de modules.
If you provide module names without boundaries ^$ it may cause hard to spot errors. Par exemple : relay will replace all modules which contain relay as a substring in its name: relay, react-relay and graphql-relay will all be pointed to your stub.
modulePathIgnorePatterns [array<string>]
Default: []
Un tableau de chaînes de patterns regexp qui sont comparées à tous les chemins de modules avant que ces chemins ne soient considérés comme « visibles » par le chargeur de modules. If a given module's path matches any of the patterns, it will not be require()-able in the test environment.
Ces chaînes de patterns correspondent au chemin d'accès complet. Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
export default config;
modulePaths [array<string>]
Default: []
An alternative API to setting the NODE_PATH env variable, modulePaths is an array of absolute paths to additional locations to search when resolving modules. Use the <rootDir> string token to include the path to your project's root directory.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
modulePaths: ['<rootDir>/app/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
modulePaths: ['<rootDir>/app/'],
};
export default config;
notify [boolean]
Default: false
Active les notifications de l'OS pour les résultats de test. To display the notifications Jest needs node-notifier package, which must be installed additionally:
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev node-notifier
yarn add --dev node-notifier
pnpm add --save-dev node-notifier
bun add --dev node-notifier
On macOS, remember to allow notifications from terminal-notifier under System Preferences > Notifications & Focus.
On Windows, node-notifier creates a new start menu entry on the first use and not display the notification. Les notifications seront affichées correctement lors des exécutions suivantes.
notifyMode [string]
Default: failure-change
Spécifie le mode de notification. Requires notify: true.
Modes
always: always send a notification.failure: send a notification when tests fail.success: send a notification when tests pass.change: send a notification when the status changed.success-change: send a notification when tests pass or once when it fails.failure-change: send a notification when tests fail or once when it passes.
openHandlesTimeout [number]
Default: 1000
Print a warning indicating that there are probable open handles if Jest does not exit cleanly this number of milliseconds after it completes. Use 0 to disable the warning.
preset [string]
Default: undefined
Un preset qui est utilisé comme base pour la configuration de Jest. A preset should point to an npm module that has a jest-preset.json, jest-preset.js, jest-preset.cjs or jest-preset.mjs file at the root.
For example, this preset foo-bar/jest-preset.js will be configured as follows:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
preset: 'foo-bar',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
preset: 'foo-bar',
};
export default config;
Les presets peuvent également être relatifs aux chemins du système de fichiers:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
preset: './node_modules/foo-bar/jest-preset.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
preset: './node_modules/foo-bar/jest-preset.js',
};
export default config;
If you also have specified rootDir, the resolution of this file will be relative to that root directory.
prettierPath [string]
Default: 'prettier'
Sets the path to the prettier node module used to update inline snapshots.
Prettier version 3 is not supported!
You can either pass prettierPath: null in your config to disable using prettier if you don't need it, or use v2 of Prettier solely for Jest.
{
"devDependencies": {
"prettier-2": "npm:prettier@^2"
}
}
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
prettierPath: require.resolve('prettier-2'),
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
prettierPath: require.resolve('prettier-2'),
};
export default config;
Nous espérons prendre en charge Prettier v3 de manière transparente dans une prochaine version de Jest. See this tracking issue.
projects [array<string | ProjectConfig>]
Default: undefined
When the projects configuration is provided with an array of paths or glob patterns, Jest will run tests in all of the specified projects at the same time. C'est idéal pour les monorepos ou lorsque vous travaillez sur plusieurs projets en même temps.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
projects: ['<rootDir>', '<rootDir>/examples/*'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
projects: ['<rootDir>', '<rootDir>/examples/*'],
};
export default config;
Cet exemple de configuration exécutera Jest dans le répertoire racine ainsi que dans tous les dossiers du répertoire examples. Vous pouvez avoir un nombre illimité de projets en cours d'exécution dans la même instance Jest.
The projects feature can also be used to run multiple configurations or multiple runners. Pour cela, vous pouvez passer un tableau d'objets de configuration. For example, to run both tests and ESLint (via jest-runner-eslint) in the same invocation of Jest:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
};
export default config;
When using multi-project runner, it's recommended to add a displayName for each project. This will show the displayName of a project next to its tests.
With the projects option enabled, Jest will copy the root-level configuration options to each individual child configuration during the test run, resolving its values in the child's context. This means that string tokens like <rootDir> will point to the child's root directory even if they are defined in the root-level configuration.
randomize [boolean]
Default: false
The equivalent of the --randomize flag to randomize the order of the tests in a file.
reporters [array<moduleName | [moduleName, options]>]
Default: undefined
Utilisez cette option de configuration pour ajouter des rapporteurs à Jest. Il doit s'agir d'une liste de noms de rapporteurs, des options supplémentaires peuvent être passées à un rapporteur en utilisant la forme tuple :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
};
export default config;
Rapporteur par défaut
Si des rapporteurs personnalisés sont spécifiés, le rapporteur par défaut de Jest sera écrasé. If you wish to keep it, 'default' must be passed as a reporters name:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
};
export default config;
Rapporteur GitHub Actions
If included in the list, the built-in GitHub Actions Reporter will annotate changed files with test failure messages and (if used with 'silent: false') print logs with github group features for easy navigation. Note that 'default' should not be used in this case as 'github-actions' will handle that already, so remember to also include 'summary'. If you wish to use it only for annotations simply leave only the reporter without options as the default value of 'silent' is 'true':
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [['github-actions', {silent: false}], 'summary'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [['github-actions', {silent: false}], 'summary'],
};
export default config;
Rapporteur summary
Le rapport summary affiche le résumé de tous les tests. It is a part of default reporter, hence it will be enabled if 'default' is included in the list. For instance, you might want to use it as stand-alone reporter instead of the default one, or together with Silent Reporter:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: ['jest-silent-reporter', 'summary'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: ['jest-silent-reporter', 'summary'],
};
export default config;
The summary reporter accepts options. Since it is included in the default reporter you may also pass the options there.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [['default', {summaryThreshold: 10}]],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [['default', {summaryThreshold: 10}]],
};
export default config;
The summaryThreshold option behaves in the following way, if the total number of test suites surpasses this threshold, a detailed summary of all failed tests will be printed after executing all the tests. It defaults to 20.
Rapporteurs personnalisés
Vous avez faim de rapporteurs ? Take a look at long list of awesome reporters from Awesome Jest.
Custom reporter module must export a class that takes globalConfig, reporterOptions and reporterContext as constructor arguments:
class CustomReporter {
constructor(globalConfig, reporterOptions, reporterContext) {
this._globalConfig = globalConfig;
this._options = reporterOptions;
this._context = reporterContext;
}
onRunComplete(testContexts, results) {
console.log('Custom reporter output:');
console.log('global config:', this._globalConfig);
console.log('options for this reporter from Jest config:', this._options);
console.log('reporter context passed from test scheduler:', this._context);
}
// Optionally, reporters can force Jest to exit with non zero code by returning
// an `Error` from `getLastError()` method.
getLastError() {
if (this._shouldFail) {
return new Error('Custom error reported!');
}
}
}
module.exports = CustomReporter;
For the full list of hooks and argument types see the Reporter interface in packages/jest-reporters/src/types.ts.
resetMocks [boolean]
Default: false
Réinitialisation automatique de l'état de la simulation avant chaque test. Equivalent to calling jest.resetAllMocks() before each test. Cela conduira à la destruction des implémentations fictives des simulations, mais ne rétablira pas leur implémentation initiale.
resetModules [boolean]
Default: false
Par défaut, chaque fichier de test obtient son propre registre de modules indépendant. Enabling resetModules goes a step further and resets the module registry before running each individual test. Ceci est utile pour isoler les modules pour chaque test afin que l'état du module local n'entre pas en conflit entre les tests. This can be done programmatically using jest.resetModules().
resolver [string]
Default: undefined
Cette option permet d'utiliser un résolveur personnalisé. This resolver must be a module that exports either:
- une fonction qui attend une chaîne comme premier argument pour le chemin à résoudre et un objet d'options comme second argument. La fonction doit soit retourner un chemin d'accès au module qui doit être résolu, soit lancer une erreur si le module est introuvable. or
- an object containing
asyncand/orsyncproperties. Thesyncproperty should be a function with the shape explained above, and theasyncproperty should also be a function that accepts the same arguments, but returns a promise which resolves with the path to the module or rejects with an error.
L'objet d'options fourni aux résolveurs a la forme suivante :
type ResolverOptions = {
/** Directory to begin resolving from. */
basedir: string;
/** List of export conditions. */
conditions?: Array<string>;
/** Instance of default resolver. */
defaultResolver: (path: string, options: ResolverOptions) => string;
/** List of file extensions to search in order. */
extensions?: Array<string>;
/** List of directory names to be looked up for modules recursively. */
moduleDirectory?: Array<string>;
/** List of `require.paths` to use if nothing is found in `node_modules`. */
paths?: Array<string>;
/** Allows transforming parsed `package.json` contents. */
packageFilter?: (pkg: PackageJSON, file: string, dir: string) => PackageJSON;
/** Allows transforms a path within a package. */
pathFilter?: (pkg: PackageJSON, path: string, relativePath: string) => string;
/** Current root directory. */
rootDir?: string;
};
The defaultResolver passed as an option is the Jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom synchronous one, e.g. (path, options) and returns a string or throws.
For example, if you want to respect Browserify's "browser" field, you can use the following resolver:
const browserResolve = require('browser-resolve');
module.exports = browserResolve.sync;
Et ajoutez-le à la configuration de Jest :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
resolver: '<rootDir>/resolver.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
resolver: '<rootDir>/resolver.js',
};
export default config;
By combining defaultResolver and packageFilter we can implement a package.json "pre-processor" that allows us to change how the default resolver will resolve modules. For example, imagine we want to use the field "module" if it is present, otherwise fallback to "main":
module.exports = (path, options) => {
// Call the defaultResolver, so we leverage its cache, error handling, etc.
return options.defaultResolver(path, {
...options,
// Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
packageFilter: pkg => {
return {
...pkg,
// Alter the value of `main` before resolving the package
main: pkg.module || pkg.main,
};
},
});
};
restoreMocks [boolean]
Default: false
Restauration automatique de l'état de la simulation et l'implémentation avant chaque test. Equivalent to calling jest.restoreAllMocks() before each test. Cela conduira à la destruction des implémentations de tous les simulations et rétablira leur implémentation initiale.
rootDir [string]
Default: The root of the directory containing your Jest config file or the package.json or the pwd if no package.json is found
Le répertoire racine dans lequel Jest doit rechercher les tests et les modules. If you put your Jest config inside your package.json and want the root directory to be the root of your repo, the value for this config param will default to the directory of the package.json.
Oftentimes, you'll want to set this to 'src' or 'lib', corresponding to where in your repository the code is stored.
Using '<rootDir>' as a string token in any other path-based configuration settings will refer back to this value. For example, if you want a setupFiles entry to point at the some-setup.js file at the root of the project, set its value to: '<rootDir>/some-setup.js'.
roots [array<string>]
Default: ["<rootDir>"]
Une liste de chemins vers des répertoires que Jest devrait utiliser pour rechercher des fichiers.
There are times where you only want Jest to search in a single sub-directory (such as cases where you have a src/ directory in your repo), but prevent it from accessing the rest of the repo.
While rootDir is mostly used as a token to be re-used in other configuration options, roots is used by the internals of Jest to locate test files and source files. This applies also when searching for manual mocks for modules from node_modules (__mocks__ will need to live in one of the roots).
By default, roots has a single entry <rootDir> but there are cases where you may want to have multiple roots within one project, for example roots: ["<rootDir>/src/", "<rootDir>/tests/"].
runtime [string]
Default: "jest-runtime"
This option allows the use of a custom runtime to execute test files. A custom runtime can be provided by specifying a path to a runtime implementation.
The runtime module must export a class that extends Jest's default Runtime class or implements a compatible interface with the same constructor signature and methods.
Creating a custom runtime is an advanced use case. Most users should not need to customize the runtime. Consider whether your use case might be better addressed with custom transformers, test environments, or module mocks.
Exemple :
const {default: Runtime} = require('jest-runtime');
class CustomRuntime extends Runtime {
//...custom logic
}
module.exports = CustomRuntime;
import Runtime from 'jest-runtime';
export default class CustomRuntime extends Runtime {
//...custom logic
}
Add the custom runtime to your Jest configuration:
- JavaScript
- TypeScript
module.exports = {
runtime: './custom-runtime.js',
};
export default {
runtime: './custom-runtime.ts',
};
runner [string]
Default: "jest-runner"
Cette option vous permet d'utiliser un runner personnalisé au lieu du runner de test par défaut de Jest. Exemples de runners inclus :
The runner property value can omit the jest-runner- prefix of the package name.
To write a test-runner, export a class with which accepts globalConfig in the constructor, and has a runTests method with the signature:
async function runTests(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
options: TestRunnerOptions,
): Promise<void>;
If you need to restrict your test-runner to only run in serial rather than being executed in parallel your class should have the property isSerial to be set as true.
sandboxInjectedGlobals [array<string>]
Renamed from extraGlobals in Jest 28.
Default: undefined
Test files run inside a vm, which slows calls to global context properties (e.g. Math). Avec cette option, vous pouvez spécifier des propriétés supplémentaires à définir à l'intérieur de la vm pour des recherches plus rapides.
For example, if your tests call Math often, you can pass it by setting sandboxInjectedGlobals.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
sandboxInjectedGlobals: ['Math'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
sandboxInjectedGlobals: ['Math'],
};
export default config;
This option has no effect if you use native ESM.
setupFiles [array]
Default: []
Une liste de chemins vers des modules qui exécutent du code pour configurer ou mettre en place l'environnement de test. Chaque setupFile sera exécuté une fois par fichier de test. Since every test runs in its own environment, these scripts will be executed in the testing environment before executing setupFilesAfterEnv and before the test code itself.
Si votre script de configuration est un module CJS, il peut exporter une fonction asynchrone. Jest appellera la fonction et attendra son résultat. Cela peut être utile pour récupérer des données de manière asynchrone. Si le fichier est un module ESM, il suffit d'utiliser le await de niveau supérieur pour obtenir le même résultat.
setupFilesAfterEnv [array]
Default: []
Une liste de chemins vers des modules qui exécutent du code pour configurer ou paramétrer le framework de test avant l'exécution de chaque fichier de test de la suite. Since setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment but before the test code itself.
In other words, setupFilesAfterEnv modules are meant for code which is repeating in each test file. Having the test framework installed makes Jest globals, jest object and expect accessible in the modules. For example, you can add extra matchers from jest-extended library or call setup and teardown hooks:
const matchers = require('jest-extended');
expect.extend(matchers);
afterEach(() => {
jest.useRealTimers();
});
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
};
export default config;
showSeed [boolean]
Default: false
The equivalent of the --showSeed flag to print the seed in the test report summary.
slowTestThreshold [number]
Default: 5
Le nombre de secondes après lequel un test est considéré comme lent et signalé comme tel dans les résultats.
snapshotFormat [object]
Default: {escapeString: false, printBasicPrototype: false}
Allows overriding specific snapshot formatting options documented in the pretty-format readme, with the exceptions of compareKeys and plugins. Par exemple, cette configuration permet au formateur de snapshot de ne pas afficher de préfixe pour "Object" et "Array" :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
snapshotFormat: {
printBasicPrototype: false,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
snapshotFormat: {
printBasicPrototype: false,
},
};
export default config;
test('does not show prototypes for object and array inline', () => {
const object = {
array: [{hello: 'Danger'}],
};
expect(object).toMatchInlineSnapshot(`
{
"array": [
{
"hello": "Danger",
},
],
}
`);
});
snapshotResolver [string]
Default: undefined
The path to a module that can resolve test<->snapshot path. Cette option de configuration vous permet de personnaliser l'endroit où Jest stocke les fichiers snapshot sur le disque.
module.exports = {
// resolves from test to snapshot path
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath.replace('__tests__', '__snapshots__') + snapshotExtension,
// resolves from snapshot to test path
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath
.replace('__snapshots__', '__tests__')
.slice(0, -snapshotExtension.length),
// Example test path, used for preflight consistency check of the implementation above
testPathForConsistencyCheck: 'some/__tests__/example.test.js',
};
snapshotSerializers [array<string>]
Default: []
Une liste de chemins d'accès aux modules de sérialisation des snapshots que Jest doit utiliser pour tester les snapshots.
Jest possède des sérialiseurs par défaut pour les types JavaScript intégrés, les éléments HTML (Jest 20.0.0+), ImmutableJS (Jest 20.0.0+) et pour les éléments React. See snapshot test tutorial for more information.
- JavaScript
- TypeScript
module.exports = {
serialize(val, config, indentation, depth, refs, printer) {
return `Pretty foo: ${printer(val.foo, config, indentation, depth, refs)}`;
},
test(val) {
return val && Object.prototype.hasOwnProperty.call(val, 'foo');
},
};
import type {Plugin} from 'pretty-format';
const plugin: Plugin = {
serialize(val, config, indentation, depth, refs, printer): string {
return `Pretty foo: ${printer(val.foo, config, indentation, depth, refs)}`;
},
test(val): boolean {
return val && Object.prototype.hasOwnProperty.call(val, 'foo');
},
};
export default plugin;
printer is a function that serializes a value using existing plugins.
Add custom-serializer to your Jest configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
snapshotSerializers: ['path/to/custom-serializer.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
snapshotSerializers: ['path/to/custom-serializer.ts'],
};
export default config;
Enfin les tests ressembleraient à ceci :
test(() => {
const bar = {
foo: {
x: 1,
y: 2,
},
};
expect(bar).toMatchSnapshot();
});
Snapshot rendu :
Pretty foo: Object {
"x": 1,
"y": 2,
}
To make a dependency explicit instead of implicit, you can call expect.addSnapshotSerializer to add a module for an individual test file instead of adding its path to snapshotSerializers in Jest configuration.
More about serializers API can be found here.
testEnvironment [string]
Default: "node"
L'environnement de test qui sera utilisé pour les tests. L'environnement par défaut dans Jest est un environnement Node.js. If you are building a web app, you can use a browser-like environment through jsdom instead.
By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file:
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div');
expect(element).not.toBeNull();
});
Vous pouvez créer votre propre module qui sera utilisé pour configurer l'environnement de test. The module must export a class with setup, teardown and getVmContext methods. You can also pass variables from this module to your test suites by assigning them to this.global object – this will make them available in your test suites as global variables. The constructor is passed globalConfig and projectConfig as its first argument, and testEnvironmentContext as its second.
The class may optionally expose an asynchronous handleTestEvent method to bind to events fired by jest-circus. Normally, jest-circus test runner would pause until a promise returned from handleTestEvent gets fulfilled, except for the next events: start_describe_definition, finish_describe_definition, add_hook, add_test or error (for the up-to-date list you can look at SyncEvent type in the types definitions). That is caused by backward compatibility reasons and process.on('unhandledRejection', callback) signature, but that usually should not be a problem for most of the use cases.
Tous les directives du docblock dans les fichiers de test seront transmises au constructeur de l'environnement et peuvent être utilisées pour la configuration de chaque test. Si la directive n'a pas de valeur, elle sera présente dans l'objet avec sa valeur égale à une chaîne vide. Si la directive n'est pas présente, elle ne sera pas présente dans l'objet.
Pour utiliser cette classe comme environnement personnalisé, faites-y référence par son chemin complet dans le projet. For example, if your class is stored in my-custom-environment.js in some subfolder of your project, then the annotation might look like this:
/**
* @jest-environment ./src/test/my-custom-environment
*/
TestEnvironment est un environnement de type bac à sable. Chaque suite de test déclenchera l'installation et le nettoyage dans son propre TestEnvironment.
Exemple :
// my-custom-environment
const NodeEnvironment = require('jest-environment-node').TestEnvironment;
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
console.log(config.globalConfig);
console.log(config.projectConfig);
this.testPath = context.testPath;
this.docblockPragmas = context.docblockPragmas;
}
async setup() {
await super.setup();
await someSetupTasks(this.testPath);
this.global.someGlobalObject = createGlobalObject();
// Will trigger if docblock contains @my-custom-pragma my-pragma-value
if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
// ...
}
}
async teardown() {
this.global.someGlobalObject = destroyGlobalObject();
await someTeardownTasks();
await super.teardown();
}
getVmContext() {
return super.getVmContext();
}
async handleTestEvent(event, state) {
if (event.name === 'test_start') {
// ...
}
}
}
module.exports = CustomEnvironment;
// my-test-suite
/**
* @jest-environment ./my-custom-environment
*/
let someGlobalObject;
beforeAll(() => {
someGlobalObject = globalThis.someGlobalObject;
});
testEnvironmentOptions [Object]
Default: {}
Test environment options that will be passed to the testEnvironment. Les options pertinentes dépendent de l'environnement.
For example, you can override options passed to jsdom:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
html: '<html lang="zh-cmn-Hant"></html>',
url: 'https://jestjs.io/',
userAgent: 'Agent/007',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
html: '<html lang="zh-cmn-Hant"></html>',
url: 'https://jestjs.io/',
userAgent: 'Agent/007',
},
};
export default config;
Both jest-environment-jsdom and jest-environment-node allow specifying customExportConditions, which allow you to control which versions of a library are loaded from exports in package.json. jest-environment-jsdom defaults to ['browser']. jest-environment-node defaults to ['node', 'node-addons'].
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['react-native'],
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['react-native'],
},
};
export default config;
These options can also be passed in a docblock, similar to testEnvironment. The string with options must be parseable by JSON.parse:
/**
* @jest-environment jsdom
* @jest-environment-options {"url": "https://jestjs.io/"}
*/
test('use jsdom and set the URL in this test file', () => {
expect(window.location.href).toBe('https://jestjs.io/');
});
testFailureExitCode [number]
Default: 1
Le code de sortie que Jest renvoie en cas d'échec du test.
Cela ne change pas le code de sortie en cas d'erreurs de Jest (par exemple, une configuration invalide).
testMatch [array<string>]
(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ])
Les patterns de glob que Jest utilise pour détecter les fichiers de test. By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js.
See the micromatch package for details of the patterns you can specify.
See also testRegex [string | array<string>], but note that you cannot specify both options.
Chaque pattern glob est appliqué dans l'ordre dans lequel ils sont spécifiés dans la configuration. For example ["!**/__fixtures__/**", "**/__tests__/**/*.js"] will not exclude __fixtures__ because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after **/__tests__/**/*.js.
testPathIgnorePatterns [array<string>]
Default: ["/node_modules/"]
Un tableau de chaînes de patterns regexp qui sont comparées à tous les chemins de tests avant d'exécuter le test. Si le chemin du test correspond à un des patterns, il sera ignoré.
Ces chaînes de patterns correspondent au chemin d'accès complet. Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/", "<rootDir>/node_modules/"].
testRegex [string | array<string>]
Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
Le ou les patterns que Jest utilise pour détecter les fichiers de test. By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js. See also testMatch [array<string>], but note that you cannot specify both options.
Ce qui suit est une visualisation des expressions régulières par défaut :
├── __tests__
│ └── component.spec.js # test
│ └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test
testRegex will try to detect test files using the absolute file path, therefore, having a folder with a name that matches it will run all the files as tests.
testResultsProcessor [string]
Default: undefined
Cette option permet l'utilisation d'un processeur de résultats personnalisé. Ce processeur doit être un module de node qui exporte une fonction qui attend un objet avec la structure suivante comme premier argument et le retourne :
{
"success": boolean,
"startTime": epoch,
"numTotalTestSuites": number,
"numPassedTestSuites": number,
"numFailedTestSuites": number,
"numRuntimeErrorTestSuites": number,
"numTotalTests": number,
"numPassedTests": number,
"numFailedTests": number,
"numPendingTests": number,
"numTodoTests": number,
"openHandles": Array<Error>,
"testResults": [{
"numFailingTests": number,
"numPassingTests": number,
"numPendingTests": number,
"testResults": [{
"title": string (message in it block),
"status": "failed" | "pending" | "passed",
"ancestorTitles": [string (message in describe blocks)],
"failureMessages": [string],
"numPassingAsserts": number,
"location": {
"column": number,
"line": number
},
"duration": number | null
},
...
],
"perfStats": {
"start": epoch,
"end": epoch
},
"testFilePath": absolute path to test file,
"coverage": {}
},
"testExecError:" (exists if there was a top-level failure) {
"message": string
"stack": string
}
...
]
}
testResultsProcessor and reporters are very similar to each other. Une différence est que le processeur de résultats de test n'est appelé qu'une fois après que tous les tests soient terminés. Alors qu'un rapporteur a la possibilité de recevoir les résultats des tests après que les tests individuels et/ou les suites de tests soient terminés.
testRunner [string]
Default: jest-circus/runner
Cette option permet d'utiliser un runner de test personnalisé. The default is jest-circus. Un runner de test personnalisé peut être fourni en spécifiant un chemin vers une implémentation d'un runner de test.
Le module de runner de test doit exporter une fonction avec la signature suivante :
function testRunner(
globalConfig: GlobalConfig,
config: ProjectConfig,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
An example of such function can be found in our default jasmine2 test runner package.
testSequencer [string]
Default: @jest/test-sequencer
Cette option vous permet d'utiliser un séquenceur personnalisé au lieu de celui par défaut de Jest.
Both sort and shard may optionally return a Promise.
Par exemple, vous pouvez trier les chemins de test par ordre alphabétique :
const Sequencer = require('@jest/test-sequencer').default;
class CustomSequencer extends Sequencer {
/**
* Select tests for shard requested via --shard=shardIndex/shardCount
* Sharding is applied before sorting
*/
shard(tests, {shardIndex, shardCount}) {
const shardSize = Math.ceil(tests.length / shardCount);
const shardStart = shardSize * (shardIndex - 1);
const shardEnd = shardSize * shardIndex;
return [...tests]
.sort((a, b) => (a.path > b.path ? 1 : -1))
.slice(shardStart, shardEnd);
}
/**
* Sort test to determine order of execution
* Sorting is applied after sharding
*/
sort(tests) {
// Test structure information
// https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
const copyTests = [...tests];
return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
}
}
module.exports = CustomSequencer;
Add custom-sequencer to your Jest configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testSequencer: 'path/to/custom-sequencer.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testSequencer: 'path/to/custom-sequencer.js',
};
export default config;
testTimeout [number]
Default: 5000
Délai par défaut d'un test en millisecondes.
transform [object<string, pathToTransformer | [pathToTransformer, object]>]
Default: {"\\.[jt]sx?$": "babel-jest"}
Une correspondance entre les expressions régulières, les chemins et les transformateurs. Optionally, a tuple with configuration options can be passed as second argument: {filePattern: ['path-to-transformer', {options}]}. For example, here is how you can configure babel-jest for non-default behavior: {'\\.js$': ['babel-jest', {rootMode: 'upward'}]}.
Jest exécute le code de votre projet en tant que JavaScript, donc un transformateur est nécessaire si vous utilisez une syntaxe non supportée par Node hors de la boîte (comme les modèles JSX, TypeScript, Vue). By default, Jest will use babel-jest transformer, which will load your project's Babel configuration and transform any file matching the /\.[jt]sx?$/ RegExp (in other words, any .js, .jsx, .ts or .tsx file). In addition, babel-jest will inject the Babel plugin necessary for mock hoisting talked about in ES Module mocking.
See the Code Transformation section for more details and instructions on building your own transformer.
Gardez à l'esprit qu'un transformateur n'est exécuté qu'une seule fois par fichier, sauf si le fichier a changé.
Remember to include the default babel-jest transformer explicitly, if you wish to use it alongside with additional code preprocessors:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transform: {
'\\.[jt]sx?$': 'babel-jest',
'\\.css$': 'some-css-transformer',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transform: {
'\\.[jt]sx?$': 'babel-jest',
'\\.css$': 'some-css-transformer',
},
};
export default config;
transformIgnorePatterns [array<string>]
Default: ["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
Un tableau de chaînes de patterns regexp qui sont comparées à tous les chemins de fichier source avant transformation. If the file path matches any of the patterns, it will not be transformed.
Fournir des patterns regexp qui se chevauchent les uns avec les autres peut avoir pour conséquence que les fichiers que vous vous attendiez à être transformés ne le soient pas. Par exemple :
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
};
export default config;
The first pattern will match (and therefore not transform) files inside /node_modules except for those in /node_modules/foo/ and /node_modules/bar/. The second pattern will match (and therefore not transform) files inside any path with /bar/ in it. With the two together, files in /node_modules/bar/ will not be transformed because it does match the second pattern, even though it was excluded by the first.
Parfois, il arrive (en particulier dans les projets React Native ou TypeScript) que des modules tiers soient publiés comme du code non transpilés. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns to allow transpiling such modules. You'll find a good example of this use case in React Native Guide.
Ces chaînes de patterns correspondent au chemin d'accès complet. Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: [
'<rootDir>/bower_components/',
'<rootDir>/node_modules/',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: [
'<rootDir>/bower_components/',
'<rootDir>/node_modules/',
],
};
export default config;
If you use pnpm and need to convert some packages under node_modules, you need to note that the packages in this folder (e.g. node_modules/package-a/) have been symlinked to the path under .pnpm (e.g. node_modules/.pnpm/[email protected]/node_modules/package-a/), so using <rootDir>/node_modules/(?!(package-a|@scope/pkg-b)/) directly will not be recognized, while is to use:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: [
'<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
/* if config file is under '~/packages/lib-a/' */
`${path.join(
__dirname,
'../..',
)}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
/* or using relative pattern to match the second 'node_modules/' in 'node_modules/.pnpm/@[email protected]/node_modules/@scope/pkg-b/' */
'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: [
'<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
/* if config file is under '~/packages/lib-a/' */
`${path.join(
__dirname,
'../..',
)}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
/* or using relative path to match the second 'node_modules/' in 'node_modules/.pnpm/@[email protected]/node_modules/@scope/pkg-b/' */
'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
],
};
export default config;
It should be noted that the folder name of pnpm under .pnpm is the package name plus @ and version number, so writing / will not be recognized, but using @ can.
unmockedModulePathPatterns [array<string>]
Default: []
Un tableau de chaînes de patterns regexp qui sont comparées à tous les modules avant que le chargeur de modules ne retourne automatiquement une simulation pour eux. Si le chemin d'un module correspond à l'un des patterns de cette liste, il ne sera pas automatiquement simulé par le chargeur de module.
This is useful for some commonly used 'utility' modules that are almost always used as implementation details almost all the time (like underscore, lodash, etc). It's generally a best practice to keep this list as small as possible and always use explicit jest.mock()/jest.unmock() calls in individual tests. La configuration explicite par test est beaucoup plus facile pour les autres lecteurs du test pour comprendre sur quel environnement le test s'exécutera.
It is possible to override this setting in individual tests by explicitly calling jest.mock() at the top of the test file.
verbose [boolean]
Default: false or true if there is only one test file to run
Indique si chaque test individuel doit être reporté pendant l'exécution. Toutes les erreurs seront également affichées en bas après l'exécution.
watchPathIgnorePatterns [array<string>]
Default: []
Un tableau de patterns RegExp qui sont comparés à tous les chemins des fichiers sources avant de réexécuter les tests en mode surveillance (watch). Si le chemin du fichier correspond à l'un des patterns, quand il est mis à jour, il ne déclenchera pas une nouvelle exécution de tests.
Ces patterns correspondent au chemin complet. Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/node_modules/"].
Even if nothing is specified here, the watcher will ignore changes to the version control folders (.git, .hg, .sl). Other hidden files and directories, i.e. those that begin with a dot (.), are watched by default. Remember to escape the dot when you add them to watchPathIgnorePatterns as it is a special RegExp character.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
};
export default config;
watchPlugins [array<string | [string, Object]>]
Default: []
Cette option vous permet d'utiliser des plugins de surveillance personnalisés. Read more about watch plugins here.
Les exemples de plugins de surveillance incluent :
jest-watch-masterjest-watch-select-projectsjest-watch-suspendjest-watch-typeaheadjest-watch-yarn-workspaces
The values in the watchPlugins property value can omit the jest-watch- prefix of the package name.
watchman [boolean]
Default: true
Whether to use watchman for file crawling.
workerIdleMemoryLimit [number|string]
Default: undefined
Specifies the memory limit for workers before they are recycled and is primarily a work-around for this issue;
Après que le worker a exécuté un test, l'utilisation de la mémoire de celui-ci est vérifiée. S'il dépasse la valeur spécifiée, le worker est tué et redémarré. The limit can be specified in a number of different ways and whatever the result is Math.floor is used to turn it into an integer value:
0- Always restart the worker between tests.<= 1- The value is assumed to be a percentage of system memory. Donc 0,5 établit la limite de mémoire du worker à la moitié de la mémoire totale du système\> 1- Assumed to be a fixed byte value. Because of the previous rule if you wanted a value of 1 byte (I don't know why) you could use1.1.- Avec des unités
50%- As above, a percentage of total system memory100KB,65MB, etc - With units to denote a fixed memory limit.K/KB- Kilobytes (x1000)KiB- Kibibytes (x1024)M/MB- MegabytesMiB- MebibytesG/GB- GigabytesGiB- Gibibytes
Percentage based memory limit does not work on Linux CircleCI workers due to incorrect system memory being reported.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
workerIdleMemoryLimit: 0.2,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
workerIdleMemoryLimit: 0.2,
};
export default config;
// [string]
This option allows comments in package.json. Incluez le texte du commentaire comme valeur de cette clé :
{
"name": "my-project",
"jest": {
"//": "Le commentaire est ici",
"verbose": true
}
}
workerThreads
Default: false
Whether to use worker threads for parallelization. Child processes are used by default.
Using worker threads may help to improve performance.
This is experimental feature. Keep in mind that the worker threads use structured clone instead of JSON.stringify() to serialize messages. This means that built-in JavaScript objects as BigInt, Map or Set will get serialized properly. However extra properties set on Error, Map or Set will not be passed on through the serialization step. For more details see the article on structured clone.