Configuring Jest
The Jest philosophy is to work great by default, but sometimes you just need more configuration power.
It is recommended to define the configuration in a dedicated JavaScript, TypeScript or JSON file. The file will be discovered automatically, if it is named jest.config.js|ts|mjs|cjs|cts|json. You can use --config flag to pass an explicit path to the file.
Keep in mind that the resulting configuration object must always be JSON-serializable.
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.
}),
),
);
- The configuration also can be stored in a JSON file as a plain object:
{
"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,
});
Options
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]waitForUnhandledRejections[boolean]watchPathIgnorePatterns[array<string>]watchPlugins[array<string | [string, Object]>]watchman[boolean]workerIdleMemoryLimit[number|string]//[string]workerThreads
Reference
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
Automatically clear mock calls, instances, contexts and results before every test. 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:
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.
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]
Indicates which provider should be used to instrument code for coverage. Allowed values are babel (default) or v8.