Configuring Jest
Jest’s configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you’d like to use your package.json to store Jest’s config, the "jest" key should be used on the top level so Jest will know how to find your settings:
{ "name": "my-project", "jest": { "verbose": true }}
Or through JavaScript:
// jest.config.js// Sync object/** @type {import('@jest/types').Config.InitialOptions} */const config = { verbose: true,};module.exports = config;// Or async functionmodule.exports = async () => { return { verbose: true, };};
Or through TypeScript (if ts-node is installed):
// jest.config.tsimport type {Config} from '@jest/types';// Sync objectconst config: Config.InitialOptions = { verbose: true,};export default config;// Or async functionexport default async (): Promise<Config.InitialOptions> => { return { verbose: true, };};
Please keep in mind that the resulting configuration must be JSON-serializable.
When using the --config option, the JSON file must not contain a “jest” key:
{ "bail": 1, "verbose": true}
Options
These options let you control Jest’s behavior in your package.json file. The Jest philosophy is to work great by default, but sometimes you just need more configuration power.
Defaults
You can retrieve Jest’s default options to expand them if needed:
// jest.config.jsconst {defaults} = require('jest-config');module.exports = { // ... moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], // ...};
-
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>]
-
extraGlobals [array<string>]
-
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]
-
preset [string]
-
prettierPath [string]
-
projects [array<string | ProjectConfig>]
-
reporters [array<moduleName | [moduleName, options]>]
-
resetMocks [boolean]
-
resetModules [boolean]
-
resolver [string]
-
restoreMocks [boolean]
-
rootDir [string]
-
roots [array<string>]
-
runner [string]
-
setupFiles [array]
-
setupFilesAfterEnv [array]
-
slowTestThreshold [number]
-
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]
-
testURL [string]
-
timers [string]
-
transform [object<string, pathToTransformer | [pathToTransformer, object]>]
-
transformIgnorePatterns [array<string>]
-
unmockedModulePathPatterns [array<string>]
-
verbose [boolean]
-
watchPathIgnorePatterns [array<string>]
-
watchPlugins [array<string | [string, Object]>]
-
watchman [boolean]
-
// [string]
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:
// utils.jsexport default { authorize: () => { return 'token'; }, isAuthorized: secret => secret === 'wizard',};
//__tests__/automocking.test.jsimport 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();});
Note: Node modules are automatically mocked when you have a manual mock in place (e.g.: mocks/lodash.js). More info here.
Note: 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 raking 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 and instances 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.
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.
Example:
{ "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/.
Note: Each glob pattern is applied in the order they are specified in the config. (For example [“!/tests/“, “**/.js”]will not excludetestsbecause 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.)*
Note: 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.
