Налаштування Jest
The Jest philosophy is to work great by default, but sometimes you just need more configuration power.
Рекомендується визначити конфігурацію в спеціальному JavaScript, TypeScript або JSON файлі. The file will be discovered automatically, if it is named jest.config.js|ts|mjs|mts|cjs|cts|json. You can use --config flag to pass an explicit path to the file.
Майте на увазі, що отримана конфігурація має бути придатна для серіалізації в JSON.
Open Config Examples
- Using
defineConfigfromjestyou should follow this:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
// ... Specify options here.
});
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig} from 'jest';
export default defineConfig({
// ... Specify options here.
});
- You can retrieve Jest's defaults from
jest-configto extend them if needed:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
const {defaults} = require('jest-config');
module.exports = defineConfig({
moduleDirectories: [...defaults.moduleDirectories, 'bower_components'],
});
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig} from 'jest';
import {defaults} from 'jest-config';
export default defineConfig({
moduleDirectories: [...defaults.moduleDirectories, 'bower_components'],
});
export default config;
- When using a separate Jest config, you can also extend Jest's options from another config file if needed using
mergeConfigfromjest:
- JavaScript
- TypeScript
const {defineConfig, mergeConfig} = require('jest');
const jestConfig = require('./jest.config');
module.exports = mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
);
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig, mergeConfig} from 'jest';
import jestConfig from './jest.config';
export default mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
);
- If your Jest config needs to be defined as a function, you can define the config like this:
- JavaScript
- TypeScript
const {defineConfig, mergeConfig} = require('jest');
const jestConfig = require('./jest.config');
module.exports = defineConfig(() =>
mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
),
);
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig, mergeConfig} from 'jest';
import jestConfig from './jest.config';
export default defineConfig(() =>
mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
),
);
- Також, конфігурація може зберігатися у файлі JSON у вигляді звичайного об'єкту:
{
"bail": 1,
"verbose": true
}
- Alternatively Jest's configuration can be defined through the
"jest"key in thepackage.jsonof your project:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
- Also Jest's configuration json file can be referenced through the
"jest"key in thepackage.jsonof your project:
{
"name": "my-project",
"jest": "./path/to/config.json"
}
To read TypeScript configuration files Jest by default requires ts-node. You can override this behavior by adding a @jest-config-loader docblock at the top of the file. Currently, ts-node and esbuild-register is supported. Make sure ts-node or the loader you specify is installed.
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig} from 'jest';
export default defineConfig({
verbose: true,
});
You can also pass options to the loader, for instance to enable transpileOnly.
/** @jest-config-loader ts-node */
/** @jest-config-loader-options {"transpileOnly": true} */
import type {defineConfig} from 'jest';
export default defineConfig({
verbose: true,
});
Параметри
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 | [string, object]]sandboxInjectedGlobals[array<string>]setupFiles[array]setupFilesAfterEnv[array]showSeed[boolean]slowTestThreshold[number]snapshotFormat[object]snapshotResolver[string]snapshotSerializers[array<string>]testEnvironment[node | jsdom | 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]waitForUnhandledRejections[boolean]watchPathIgnorePatterns[array<string>]watchPlugins[array<string | [string, Object]>]watchman[boolean]workerGracefulExitTimeout[number]workerIdleMemoryLimit[number|string]//[string]workerThreads
Довідка
automock [boolean]
Default: false
This option tells Jest that all imported modules in your tests should be mocked automatically. All modules used in your tests will have a replacement implementation, keeping the API surface.
Example:
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
By default, Jest runs all tests and produces all errors into the console upon completion. 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>"
The directory where Jest should store its cached dependency information.
Jest attempts to scan your dependency tree once (up-front) and cache it in order to ease some of the filesystem churn that needs to happen while running tests. This config option lets you customize where Jest stores that cache data on disk.
clearMocks [boolean]
Default: false
Автоматично очищує імітації викликів, екземплярів, контекстів і результатів перед кожним тестом. Equivalent to calling jest.clearAllMocks() before each test. This does not remove any mock implementation that may have been provided.
collectCoverage [boolean]
Default: false
Indicates whether the coverage information should be collected while executing the test. Because this retrofits all executed files with coverage collection statements, it may significantly slow down your 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. If a file matches the specified glob pattern, coverage information will be collected for it even if no tests exist for this file and it's never required in the test suite.
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
});
import {defineConfig} from 'jest';
export default defineConfig({
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
});
This will collect coverage information for all the files inside the project's rootDir, except the ones that match **/node_modules/** or **/vendor/**.
Each glob pattern is applied in the order they are specified in the config. 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:
Якщо ви бачите вивід покриття, наприклад як...
=============================== 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.
Most likely your glob patterns are not matching any files. Refer to the micromatch documentation to ensure your globs are compatible.
coverageDirectory [string]
Default: undefined
The directory where Jest should output its coverage files.
coveragePathIgnorePatterns [array<string>]
Default: ["/node_modules/"]
An array of regexp pattern strings that are matched against all file paths before executing the test. If the file path matches any of the patterns, coverage information will be skipped.
These pattern strings match against the full path. 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]
Вказує, який постачальник повинен використовуватися для перевірки покриття коду. Allowed values are babel (default) or v8.
coverageReporters [array<string | [string, options]>]
Default: ["clover", "json", "lcov", "text"]
A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used.
Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output.
Additional options can be passed using the tuple form. For example, you may hide coverage report lines for all fully-covered files:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
});
import {defineConfig} from 'jest';
export default defineConfig({
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
});
For more information about the options object shape refer to CoverageReporterWithOptions type in the type definitions.
coverageThreshold [object]
Default: undefined
This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as global, as a glob, and as a directory or file path. If thresholds aren't met, jest will fail.
-
If a threshold is set to a positive number, it will be interpreted as the minimum percentage of coverage required.
-
If a threshold is set to a negative number, it will be treated as the maximum number of uncovered items allowed.
For example, with the following configuration jest will fail if there is less than 80% branch, line, and function coverage, or if there are more than 10 uncovered statements:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
coverageThreshold: {
global: {
// Requires 80% branch coverage
branches: 80,
// Requires 80% function coverage
functions: 80,
// Requires 80% line coverage
lines: 80,
// Require that no more than 10 statements are uncovered
statements: -10,
},
},
});
import {defineConfig} from 'jest';
export default defineConfig({
coverageThreshold: {
global: {
// Requires 80% branch coverage
branches: 80,
// Requires 80% function coverage
functions: 80,
// Requires 80% line coverage
lines: 80,
// Require that no more than 10 statements are uncovered
statements: -10,
},
},
});
coverageThreshold.global.lines [number]
Global threshold for lines.
coverageThreshold.global.functions [number]
Global threshold for functions.
coverageThreshold.global.statements [number]
Global threshold for statements.
coverageThreshold.global.branches [number]
Global threshold for branches.
coverageThreshold[glob-pattern] [object]
Default: undefined
Sets thresholds for files matching the glob pattern. This allows you to enforce a high global standard while also setting specific thresholds for critical files or directories.
When globs or paths are defined together with a global threshold, Jest applies each threshold independently — specific patterns use their own limits, while the global threshold applies to files not matched by any pattern. If all files are matched by path or glob patterns, the global threshold falls back to applying against all covered files.
If the file specified by path is not found, an error is returned.
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
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,
},
},
});
import {defineConfig} from 'jest';
export default defineConfig({
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,
},
},
});
Jest will fail if:
- The
./src/componentsdirectory has less than 40% branch/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. - All files that are not matched by
./src/components,./src/reducers/**/*.js, or./src/api/very-important-module.jshave less than 50% coverage (global).
dependencyExtractor [string]
Default: undefined
This option allows the use of a custom dependency extractor. It must be a node module that exports an object with an extract function. E.g.:
const crypto = require('crypto');
const fs = require('fs');
module.exports = {
extract(code, filePath, defaultExtract) {
const deps = defaultExtract(code, filePath);
// Scan the file and add dependencies in `deps` (which is a `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
Allows for a label to be printed alongside a test while it is running. This becomes more useful in multi-project repositories where there can be many jest configuration files. This visually tells which project a test belongs to.
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
displayName: 'CLIENT',
});
import {defineConfig} from 'jest';
export default defineConfig({
displayName: 'CLIENT',
});
Alternatively, an object with the properties name and color can be passed. This allows for a custom configuration of the background color of the 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
const {defineConfig} = require('jest');
module.exports = defineConfig({
displayName: {
name: 'CLIENT',
color: 'blue',
},
});
import {defineConfig} from 'jest';
export default defineConfig({
displayName: {
name: 'CLIENT',
color: 'blue',
},
});
errorOnDeprecated [boolean]
Default: false
Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.
extensionsToTreatAsEsm [array<string>]
Default: []
Jest will run .mjs and .js files with nearest package.json's type field set to module as ECMAScript Modules. If you have any other files that should run with native ESM, you need to specify their file extension here.
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
extensionsToTreatAsEsm: ['.ts'],
});
import {defineConfig} from 'jest';
export default defineConfig({
extensionsToTreatAsEsm: ['.ts'],
});
Jest's ESM support is still experimental, see its docs for more details.
fakeTimers [object]
Default: {}
The fake timers may be useful when a piece of code sets a long timeout that we don't want to wait for in a test. For additional details see Fake Timers guide and API documentation.
This option provides the default configuration of fake timers for all 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
const {defineConfig} = require('jest');
module.exports = defineConfig({
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
});
import {defineConfig} from 'jest';
export default defineConfig({
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
});
// 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
const {defineConfig} = require('jest');
module.exports = defineConfig({
fakeTimers: {
enableGlobally: true,
},
});
import {defineConfig} from 'jest';
export default defineConfig({
fakeTimers: {
enableGlobally: true,
},
});
Configuration options:
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;
};
For some reason you might have to use legacy implementation of fake timers. Here is how to enable it globally (additional options are not supported):
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
});
import {defineConfig} from 'jest';
export default defineConfig({
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
});
forceCoverageMatch [array<string>]
Default: ['']
Test files are normally ignored from collecting code coverage. With this option, you can overwrite this behavior and include otherwise ignored files in code coverage.
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
const {defineConfig} = require('jest');
module.exports = defineConfig({
forceCoverageMatch: ['**/*.t.js'],
});
import {defineConfig} from 'jest';
export default defineConfig({
forceCoverageMatch: ['**/*.t.js'],
});
globals [object]
Default: {}
A set of global variables that need to be available in all test environments.
For example, the following would create a global __DEV__ variable set to true in all test environments:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
globals: {
__DEV__: true,
},
});
import {defineConfig} from 'jest';
export default defineConfig({
globals: {
__DEV__: true,
},
});
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
This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's globalConfig and projectConfig.
A global setup module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
Any global variables that are defined through globalSetup can only be read in globalTeardown. You cannot retrieve globals defined here in your test suites.
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.testPathPatterns);
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.testPathPatterns);
console.log(projectConfig.cache);
await globalThis.__MONGOD__.stop();
};
globalTeardown [string]
Default: undefined
This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's globalConfig and projectConfig.
A global teardown module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
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. The following options are supported:
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. Any test above this limit will be queued and executed once a slot is released.
maxWorkers [number | string]
Вказує максимальну кількість робочих процесів, які можуть бути створені під час виконання тестів. В одиничному режимі, це значення за замовчуванням дорівнює кількості ядер доступних на вашому комп'ютері мінус один для головного процесу. У режимі перегляду, це за замовчуванням половина доступних ядер на вашому комп’ютері для того, щоб Jest був ненав'язливим і не зупинив роботу вашої машини. Це може бути корисно в оточеннях з обмеженими ресурсами, таких, як CI, але значення за замовчуванням повинно бути адекватним для більшості випадків.
For environments with variable CPUs available, you can use percentage based configuration:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
maxWorkers: '50%',
});
import {defineConfig} from 'jest';
export default defineConfig({
maxWorkers: '50%',
});
moduleDirectories [array<string>]
Default: ["node_modules"]
An array of directory names to be searched recursively up from the requiring module's location. 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
const {defineConfig} = require('jest');
module.exports = defineConfig({
moduleDirectories: ['node_modules', 'bower_components'],
});
import {defineConfig} from 'jest';
export default defineConfig({
moduleDirectories: ['node_modules', 'bower_components'],
});
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", "mts", "cts", "tsx", "json", "node"]
An array of file extensions your modules use. If you require modules without specifying a file extension, these are the extensions Jest will look for, in left-to-right order.
We recommend placing the extensions most commonly used in your project on the left, so if you are using TypeScript, you may want to consider moving "ts" and/or "tsx" to the beginning of the array.
moduleNameMapper [object<string, string | array<string>>]
Default: null
A map from regular expressions to module names or to arrays of module names that allow to stub out resources, like images or styles with a single module.
Modules that are mapped to an alias are unmocked by default, regardless of whether automocking is enabled or not.
Use <rootDir> string token to refer to rootDir value if you want to use file paths.
Additionally, you can substitute captured regex groups using numbered backreferences.
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
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',
],
},
});
import {defineConfig} from 'jest';
export default defineConfig({
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',
],
},
});
The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first. This is true for arrays of module names as well.
If you provide module names without boundaries ^$ it may cause hard to spot errors. E.g. 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: []
An array of regexp pattern strings that are matched against all module paths before those paths are to be considered 'visible' to the module loader. If a given module's path matches any of the patterns, it will not be require()-able in the test environment.
These pattern strings match against the full path. 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
const {defineConfig} = require('jest');
module.exports = defineConfig({
modulePathIgnorePatterns: ['<rootDir>/build/'],
});
import {defineConfig} from 'jest';
export default defineConfig({
modulePathIgnorePatterns: ['<rootDir>/build/'],
});
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
const {defineConfig} = require('jest');
module.exports = defineConfig({
modulePaths: ['<rootDir>/app/'],
});
import {defineConfig} from 'jest';
export default defineConfig({
modulePaths: ['<rootDir>/app/'],
});
notify [boolean]
Default: false
Activates native OS notifications for test results. 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. Notifications will be properly displayed on subsequent runs.
notifyMode [string]
Default: failure-change
Specifies notification mode. 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
Виводить попередження, що означає можливі відкриті елементи керування, якщо Jest не завершує роботу без проблем певну кількість мілісекунд після повного виконання. Use 0 to disable the warning.
preset [string]
Default: undefined
A preset that is used as a base for Jest's configuration. 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 used as follows:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
preset: 'foo-bar',
});
import {defineConfig} from 'jest';
export default defineConfig({
preset: 'foo-bar',
});
Presets may also be relative to filesystem paths:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
preset: './node_modules/foo-bar/jest-preset.js',
});
import {defineConfig} from 'jest';
export default defineConfig({
preset: './node_modules/foo-bar/jest-preset.js',
});
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.
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. This is great for monorepos or when working on multiple projects at the same time.
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
projects: ['<rootDir>', '<rootDir>/examples/*'],
});
import {defineConfig} from 'jest';
export default defineConfig({
projects: ['<rootDir>', '<rootDir>/examples/*'],
});
This example configuration will run Jest in the root directory as well as in every folder in the examples directory. You can have an unlimited amount of projects running in the same Jest instance.
The projects feature can also be used to run multiple configurations or multiple runners. For this purpose, you can pass an array of configuration objects. For example, to run both tests and ESLint (via jest-runner-eslint) in the same invocation of Jest:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
});
import {defineConfig} from 'jest';
export default defineConfig({
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
});
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.
Some options only take effect at the root (global) config level and are ignored when set inside a project config. These include: bail, changedSince, ci, coverageReporters, coverageThreshold, forceExit, maxConcurrency, passWithNoTests, reporters, testResultsProcessor, testSequencer, watch, watchAll, and watchPlugins. If you need to use any of these options, define them in the root config instead of a project config.
The jest package exports the ProjectConfig and GlobalConfig TypeScript types if you need to distinguish between the two:
import type {GlobalConfig, ProjectConfig} from 'jest';
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
Use this configuration option to add reporters to Jest. It must be a list of reporter names, additional options can be passed to a reporter using the tuple form:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
});
import {defineConfig} from 'jest';
export default defineConfig({
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
});
Default Reporter
If custom reporters are specified, the default Jest reporter will be overridden. If you wish to keep it, 'default' must be passed as a reporters name:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
});
import {defineConfig} from 'jest';
export default defineConfig({
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
});
GitHub Actions Reporter
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
const {defineConfig} = require('jest');
module.exports = defineConfig({
reporters: [['github-actions', {silent: false}], 'summary'],
});
import {defineConfig} from 'jest';
export default defineConfig({
reporters: [['github-actions', {silent: false}], 'summary'],
});
Summary Reporter
Summary reporter prints out summary of all 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
const {defineConfig} = require('jest');
module.exports = defineConfig({
reporters: ['jest-silent-reporter', 'summary'],
});
import {defineConfig} from 'jest';
export default defineConfig({
reporters: ['jest-silent-reporter', 'summary'],
});
The summary reporter accepts options. Since it is included in the default reporter you may also pass the options there.
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
reporters: [['default', {summaryThreshold: 10}]],
});
import {defineConfig} from 'jest';
export default defineConfig({
reporters: [['default', {summaryThreshold: 10}]],
});
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.
Custom Reporters
Hungry for reporters? 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
Automatically reset mock state before every test. Equivalent to calling jest.resetAllMocks() before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.
resetModules [boolean]
Default: false
By default, each test file gets its own independent module registry. Enabling resetModules goes a step further and resets the module registry before running each individual test. This is useful to isolate modules for every test so that the local module state doesn't conflict between tests. This can be done programmatically using jest.resetModules().
resolver [string]
Default: undefined
This option allows the use of a custom resolver. This resolver must be a module that exports either:
- a function expecting a string as the first argument for the path to resolve and an options object as the second argument. The function should either return a path to the module that should be resolved or throw an error if the module can't be found. 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.
The options object provided to resolvers has the shape:
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>;
/** 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;
And add it to Jest configuration:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
resolver: '<rootDir>/resolver.js',
});
import {defineConfig} from 'jest';
export default defineConfig({
resolver: '<rootDir>/resolver.js',
});
Jest's jest-resolve relies on unrs-resolver. We can pass additional options, for example modifying mainFields for resolution. For example, for React Native projects, you might want to use this config:
module.exports = (path, options) => {
// Call the defaultResolver, so we leverage its cache, error handling, etc.
return options.defaultResolver(path, {
...options,
// `unrs-resolver` option: https://github.com/unrs/unrs-resolver#main-field
mainFields: ['react-native', 'main'],
});
};
You can also use defaultResolver to implement a "pre-processor" that allows us to change how the default resolver will resolve modules. For example, suppose a TypeScript project needs to reference .js files at runtime but runs Jest on the .ts files.
module.exports = (path, options) => {
// Dynamic imports within our codebase that reference .js need to reference
// .ts during tests.
if (
!options.basedir.includes('node_modules') &&
path.endsWith('.js') &&
(path.startsWith('../') || path.startsWith('./'))
) {
path = path.replace(/\.js$/, '.ts');
}
// Call the defaultResolver, so we leverage its cache, error handling, etc.
return options.defaultResolver(path, options);
};
restoreMocks [boolean]
Default: false
Automatically restore mock state and implementation before every test. Equivalent to calling jest.restoreAllMocks() before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation.
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
The root directory that Jest should scan for tests and modules within. 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'.