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
}
}
或者通过 JavaScript:
// jest.config.js
// Sync object
module.exports = {
verbose: true,
};
// Or async function
module.exports = async () => {
return {
verbose: true,
};
};
Or through TypeScript (if ts-node
is installed):
// jest.config.ts
import type {Config} from '@jest/types';
// Sync object
const config: Config.InitialOptions = {
verbose: true,
};
export default config;
// Or async function
export default async (): Promise<Config.InitialOptions> => {
return {
verbose: true,
};
};
请记住最后拿到的配置必须是可被 JSON 序列化的。
使用--config
配置选项时,JSON 文件绝不能有"jest"键值︰
{
"bail": 1,
"verbose": true
}
选项
这些选项让你可以通过package.json
文件来控制Jest的行为。Jest的理念是希望默认配置就能运行得很好,但有些时候我们还是需要发挥配置的功效。
Defaults
您可以了解 Jest 的默认选项,以便在必要时扩展它们:
// jest.config.js
const {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]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]
参考
automock
[boolean]
默认值︰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.
示例:
// utils.js
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
//__tests__/automocking.test.js
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();
});
Note: Node modules are automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js
). More info here.
注意:类似 fs
这样的核心模块,默认是不模拟的。它们可以像 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]
默认值︰ "/tmp/<path>"
Jest用来储存依赖信息缓存的目录。
Jest 尝试去扫描你的依赖树一次(前期)并且把依赖树缓存起来,其目的就是抹去某些在运行测试时需要进行的文件系统排序。 这一配置选项让你可以自定义Jest将缓存数据储存在磁盘的那个位置。
clearMocks
[boolean]
默认值︰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]
默认值︰false
指出是否收集测试时的覆盖率信息。 由于要带上覆盖率搜集语句重新访问所有执行过的文件,这可能会让你的测试执行速度被明显减慢。
collectCoverageFrom
[array]
默认值: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.
示例:
{
"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/**
.
注意:该选项要求 collectCoverage
被设成true,或者通过 --coverage
参数来调用 Jest。
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]
默认值:undefined
Jest输出覆盖信息文件的目录。
coveragePathIgnorePatterns
[array<string>]
默认值︰["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]
指定应使用哪个程序来检测覆盖范围的代码。 允许的值为` babel </ code>(默认)或 v8 </ code>。
Note that using Default: A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used. Note: Setting this option overwrites the default values. Add Note: You can pass additional options to the istanbul reporter using the tuple form. For example: For the additional information about the options object shape you can refer to 默认值: This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as 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: If globs or paths are specified alongside 例如,基于下面的配置: Jest 在以下情况下将失败: 默认值: This option allows the use of a custom dependency extractor. It must be a node module that exports an object with an The That module can also contain a 默认值: 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. Here are sample valid values. 或 As a secondary option, an object with the properties 默认值︰ Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process. 默认值: Jest will run Note: Jest's ESM support is still experimental, see its docs for more details. 默认值: Test files run inside a vm, which slows calls to global context properties (e.g. For example, if your tests call 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 你可以通过设置 默认值: 一组全局变量,在所有测试环境下都可以访问。 例如,下面这段代码将为所有测试环境创建一个值为 注意,如果你在这指定了一个全局引用值(例如,对象或者数组),之后在测试运行中有些代码改变了这个被引用的值,这个改动对于其他测试不会生效。 In addition, the 默认值: This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's Note: 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. Note: Any global variables that are defined through Note: While code transformation is applied to the linked setup-file, Jest will not transform any code in 示例: 默认值: This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's Note: 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. Note: The same caveat concerning transformation of 默认值: This will be used to configure the behavior of Default: Insert Jest's globals ( Note: This option is only supported using the default Default: A number limiting the number of tests that are allowed to run at the same time when using 默认值︰ 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 Default: 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. 默认值︰ 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 Additionally, you can substitute captured regex groups using numbered backreferences. 示例: 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. Note: If you provide module name without boundaries 默认值: 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 These pattern strings match against the full path. Use the 默认值: An alternative API to setting the 默认值︰ Activates notifications for test results. Beware: Jest uses node-notifier to display desktop notifications. On Windows, it creates a new start menu entry on the first use and not display the notification. Notifications will be properly displayed on subsequent runs Default: Specifies notification mode. Requires 默认值: A preset that is used as a base for Jest's configuration. A preset should point to an npm module that has a For example, this preset Presets may also be relative to filesystem paths. Default: Sets the path to the 默认值: When the 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: Note: When using multi-project runner, it's recommended to add a 默认值: Use this configuration option to add custom reporters to Jest. A custom reporter is a class that implements If custom reporters are specified, the default Jest reporters will be overridden. To keep default reporters, This will override default reporters: This will use custom reporter in addition to default reporters that Jest provides: Additionally, custom reporters can be configured by passing an Custom reporter modules must define a class that takes a Example reporter: Custom reporters can also force Jest to exit with non-0 code by returning an Error from For the full list of methods and argument types see 默认值︰ Automatically reset mock state before every test. Equivalent to calling 默认值︰ By default, each test file gets its own independent module registry. Enabling 默认值: This option allows the use of a custom resolver. This resolver must be a node module that exports a function expecting a string as the first argument for the path to resolve and an object with the following structure 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. Note: 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 one, e.g. For example, if you want to respect Browserify's By combining 默认值︰ Automatically restore mock state before every test. Equivalent to calling Default: The root of the directory containing your Jest config file or the The root directory that Jest should scan for tests and modules within. If you put your Jest config inside your Oftentimes, you'll want to set this to Note that using 默认值︰ A list of paths to directories that Jest should use to search for files in. There are times where you only want Jest to search in a single sub-directory (such as cases where you have a Note: While Note: By default, Default: This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include: Note: The To write a test-runner, export a class with which accepts 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 默认值: A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself. It's also worth noting that 默认值: A list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed. Since If you want a path to be relative to the root directory of your project, please include For example, Jest ships with several plug-ins to Note: Example Example Default: The number of seconds after which a test is considered as slow and reported as such in the results. 默认值: The path to a module that can resolve test<->snapshot path. This config option lets you customize where Jest stores snapshot files on disk. Example snapshot resolver module: 默认值: A list of paths to snapshot serializer modules Jest should use for snapshot testing. Jest has default serializers for built-in JavaScript types, HTML elements (Jest 20.0.0+), ImmutableJS (Jest 20.0.0+) and for React elements. See snapshot test tutorial for more information. Example serializer module: To use Finally tests would look as follows: Rendered snapshot: To make a dependency explicit instead of implicit, you can call More about serializers API can be found here. Default: The test environment that will be used for testing. The default environment in Jest is a Node.js environment. If you are building a web app, you can use a browser-like environment through By adding a You can create your own module that will be used for setting up the test environment. The module must export a class with The class may optionally expose an asynchronous Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. To use this class as your custom environment, refer to it by its full path within the project. For example, if your class is stored in Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment. 示例: 默认值: Test environment options that will be passed to the Default: The exit code Jest returns on test failure. Note: This does not change the exit code in the case of Jest errors (e.g. invalid configuration). (default: The glob patterns Jest uses to detect test files. By default it looks for See the micromatch package for details of the patterns you can specify. See also 默认值︰ An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped. These pattern strings match against the full path. Use the Default: The pattern or patterns Jest uses to detect test files. By default it looks for The following is a visualization of the default regex: Note: 默认值: This option allows the use of a custom results processor. This processor must be a node module that exports a function expecting an object with the following structure as the first argument and return it: Default: This option allows the use of a custom test runner. The default is The test runner module must export a function with the following signature: An example of such function can be found in our default jasmine2 test runner package. Default: This option allows you to use a custom sequencer instead of Jest's default. 示例: Sort test path alphabetically. Use it in your Jest config file like this: Default: 默认测试超时时间单位为毫秒。 Default: This option sets the URL for the jsdom environment. It is reflected in properties such as 默认值︰ Setting this value to If the value is Default: A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the examples/typescript example or the webpack tutorial. Examples of such compilers include: You can pass configuration to a transformer like Note: a transformer is only run once per file unless the file has changed. During the development of a transformer it can be useful to run Jest with Note: when adding additional code transformers, this will overwrite the default config and A transformer must be an object with at least a Default: An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed. These pattern strings match against the full path. Use the Example: Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside 默认值: An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns in this list, it will not be automatically mocked by the module loader. This is useful for some commonly used 'utility' modules that are almost always used as implementation details almost all the time (like underscore/lo-dash, etc). It's generally a best practice to keep this list as small as possible and always use explicit It is possible to override this setting in individual tests by explicitly calling 默认值︰ Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. Note that if there is only one test file being run it will default to 默认值: An array of RegExp patterns that are matched against all source file paths before re-running tests in watch mode. If the file path matches any of the patterns, when it is updated, it will not trigger a re-run of tests. These patterns match against the full path. Use the Even if nothing is specified here, the watcher will ignore changes to any hidden files and directories, i.e. files and folders that begin with a dot ( 默认值: This option allows you to use custom watch plugins. Read more about watch plugins here. Examples of watch plugins include: Note: The values in the Default: Whether to use No default This option allows comments in 示例:v8` is considered experimental. This uses V8's builtin code coverage rather than one based on Babel. It is not as well tested, and it has also improved in the last few releases of Node. Using the latest versions of node (v14 at the time of this writing) will yield better results.
coverageReporters
[array<string | [string, options]>]["json", "lcov", "text", "clover"]
"text"
or "text-summary"
to see a coverage summary in the console output.["json", ["lcov", {"projectRoot": "../../"}]]
CoverageReporterWithOptions
type in the type definitions.coverageThreshold
[object]undefined
global
, as a glob, and as a directory or file path. 如果没有达到阈值,Jest 执行测试时将会失败。 Thresholds specified as a positive number are taken to be the minimum percentage required. Thresholds specified as a negative number represent the maximum number of uncovered entities allowed.{
...
"jest": {
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
}
}
}
global
, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. 通配符模式设置的阈值将应用到所匹配的所有文件上并单独计算。 If the file specified by path is not found, an error is returned.{
...
"jest": {
"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
}
}
}
}
./src/components
directory has less than 40% branch or statement coverage../src/reducers/**/*.js
glob has less than 90% statement coverage../src/api/very-important-module.js
的任意一种覆盖率低于 100%global
)dependencyExtractor
[string]undefined
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');
},
};
extract
function should return an iterable (Array
, Set
, etc.) with the dependencies found in the code.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]undefined
module.exports = {
displayName: 'CLIENT',
};
module.exports = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
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.errorOnDeprecated
[boolean]false
extensionsToTreatAsEsm
[array<string>][]
.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.
{
...
"jest": {
"extensionsToTreatAsEsm": [".ts"]
}
}
extraGlobals
[array<string>]undefined
Math
). With this option you can specify extra properties to be defined inside the vm for faster lookups.Math
often, you can pass it by setting extraGlobals
.{
...
"jest": {
"extraGlobals": ["Math"]
}
}
forceCoverageMatch
[array<string>]['']
.t.js
extension as following:// sum.t.js
export function sum(a, b) {
return a + b;
}
if (process.env.NODE_ENV === 'test') {
test('sum', () => {
expect(sum(1, 2)).toBe(3);
});
}
forceCoverageMatch
从这些文件中收集覆盖率。{
...
"jest": {
"forceCoverageMatch": ["**/*.t.js"]
}
}
globals
[object]{}
true
的全局变量__DEV__
:{
...
"jest": {
"globals": {
"__DEV__": true
}
}
}
globals
object must be json-serializable, so it can't be used to specify global functions. For that, you should use setupFiles
.globalSetup
[string]undefined
globalConfig
object as a parameter.globalSetup
can only be read in globalTeardown
. You cannot retrieve globals defined here in your test suites.node_modules
. This is due to the need to load the actual transformers (e.g. babel
or typescript
) to perform transformation.// setup.js
module.exports = async () => {
// ...
// Set reference to mongod in order to close the server during teardown.
global.__MONGOD__ = mongod;
};
// teardown.js
module.exports = async function () {
await global.__MONGOD__.stop();
};
globalTeardown
[string]undefined
globalConfig
object as a parameter.node_modules
as for globalSetup
applies to globalTeardown
.haste
[object]undefined
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;
// Path to a custom implementation of Haste.
hasteImplModulePath?: string;
// All platforms to target, e.g ['ios', 'android'].
platforms?: Array<string>;
// Whether to throw on error on module collision.
throwOnModuleCollision?: boolean;
};
injectGlobals
[boolean]true
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);
});
jest-circus
. test runnermaxConcurrency
[number]5
test.concurrent
. Any test above this limit will be queued and executed once a slot is released.moduleDirectories
[array<string>]["node_modules"]
node_modules
for packages include it along with any other options: ["node_modules", "bower_components"]
moduleFileExtensions
[array<string>]["js", "jsx", "ts", "tsx", "json", "node"]
moduleNameMapper
[object<string, string | array<string>>]null
<rootDir>
string token to refer to rootDir
value if you want to use file paths.{
"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"
]
}
}
^$
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>][]
require()
-able in the test environment.<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/"]
.modulePaths
[array<string>][]
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. Example: ["<rootDir>/app/"]
.notify
[boolean]false
notifyMode
[string]failure-change
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.preset
[string]undefined
jest-preset.json
or jest-preset.js
file at the root.foo-bar/jest-preset.js
will be configured as follows:{
"preset": "foo-bar"
}
{
"preset": "./node_modules/foo-bar/jest-preset.js"
}
prettierPath
[string]'prettier'
prettier
node module used to update inline snapshots.projects
[array<string | projectconfig>]undefined
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.{
"projects": ["<rootDir>", "<rootDir>/examples/*"]
}
{
"projects": [
{
"displayName": "test"
},
{
"displayName": "lint",
"runner": "jest-runner-eslint",
"testMatch": ["<rootDir>/**/*.js"]
}
]
}
displayName
for each project. This will show the displayName
of a project next to its tests.reporters
[array<modulename | [modulename, options]>]undefined
onRunStart
, onTestStart
, onTestResult
, onRunComplete
methods that will be called when any of those events occurs.default
can be passed as a module name.{
"reporters": ["<rootDir>/my-custom-reporter.js"]
}
{
"reporters": ["default", "<rootDir>/my-custom-reporter.js"]
}
options
object as a second argument:{
"reporters": [
"default",
["<rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]
]
}
GlobalConfig
and reporter options as constructor arguments:// my-custom-reporter.js
class MyCustomReporter {
constructor(globalConfig, options) {
this._globalConfig = globalConfig;
this._options = options;
}
onRunComplete(contexts, results) {
console.log('Custom reporter output:');
console.log('GlobalConfig: ', this._globalConfig);
console.log('Options: ', this._options);
}
}
module.exports = MyCustomReporter;
// or export default MyCustomReporter;
getLastError()
methodsclass MyCustomReporter {
// ...
getLastError() {
if (this._shouldFail) {
return new Error('my-custom-reporter.js reported an error');
}
}
}
Reporter
interface in packages/jest-reporters/src/types.tsresetMocks
[boolean]false
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]false
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]undefined
{
"basedir": string,
"defaultResolver": "function(request, options)",
"extensions": [string],
"moduleDirectory": [string],
"paths": [string],
"packageFilter": "function(pkg, pkgdir)",
"rootDir": [string]
}
(request, options)
."browser"
field, you can use the following configuration:{
...
"jest": {
"resolver": "<rootDir>/resolver.js"
}
}
// resolver.js
const browserResolve = require('browser-resolve');
module.exports = browserResolve.sync;
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"
:{
...
"jest": {
"resolver": "my-module-resolve"
}
}
// my-module-resolve package
module.exports = (request, options) => {
// Call the defaultResolver, so we leverage its cache, error handling, etc.
return options.defaultResolver(request, {
...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]false
jest.restoreAllMocks()
before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation.rootDir
[string]package.json
or the pwd
if no package.json
is foundpackage.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
.'src'
or 'lib'
, corresponding to where in your repository the code is stored.'<rootDir>'
as a string token in any other path-based config settings will refer back to this value. So, for example, if you want your setupFiles
config entry to point at the env-setup.js
file at the root of your project, you could set its value to ["<rootDir>/env-setup.js"]
.roots
[array<string>]["<rootDir>"]
src/
directory in your repo), but prevent it from accessing the rest of the repo.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
).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/"]
.runner
[string]"jest-runner"
runner
property value can omit the jest-runner-
prefix of the package name.globalConfig
in the constructor, and has a runTests
method with the signature:async runTests(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
options: TestRunnerOptions,
): Promise<void>
isSerial
to be set as true
.setupFiles
[array][]
setupFiles
will execute before setupFilesAfterEnv
.setupFilesAfterEnv
[array][]
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.<rootDir>
inside a path's string, like "<rootDir>/a-configs-folder"
.jasmine
that work by monkey-patching the jasmine API. If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in these modules.setupTestFrameworkScriptFile
is deprecated in favor of setupFilesAfterEnv
.setupFilesAfterEnv
array in a jest.config.js:module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
};
jest.setup.js
filejest.setTimeout(10000); // in milliseconds
slowTestThreshold
[number]5
snapshotResolver
[string]undefined
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>][]
// my-serializer-module
module.exports = {
serialize(val, config, indentation, depth, refs, printer) {
return 'Pretty foo: ' + printer(val.foo);
},
test(val) {
return val && val.hasOwnProperty('foo');
},
};
printer
is a function that serializes a value using existing plugins.my-serializer-module
as a serializer, configuration would be as follows:{
...
"jest": {
"snapshotSerializers": ["my-serializer-module"]
}
}
test(() => {
const bar = {
foo: {
x: 1,
y: 2,
},
};
expect(bar).toMatchSnapshot();
});
Pretty foo: Object {
"x": 1,
"y": 2,
}
expect.addSnapshotSerializer
to add a module for an individual test file instead of adding its path to snapshotSerializers
in Jest configuration.testEnvironment
[string]"node"
jsdom
instead.@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();
});
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.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.my-custom-environment.js
in some subfolder of your project, then the annotation might looke like this:/**
* @jest-environment ./src/test/my-custom-environment
*/
// my-custom-environment
const NodeEnvironment = require('jest-environment-node');
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
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 = global.someGlobalObject;
});
testEnvironmentOptions
[Object]{}
testEnvironment
. The relevant options depend on the environment. For example, you can override options given to jsdom such as {userAgent: "Agent/007"}
.testFailureExitCode
[number]1
testMatch
[array<string>][ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
).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
.testRegex
[string | array<string>], but note that you cannot specify both options.testPathIgnorePatterns
[array<string>]["node_modules"]
<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>](/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
.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.├── __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 teststestResultsProcessor
[string]undefined
{
"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
}
},
...
],
"perfStats": {
"start": epoch,
"end": epoch
},
"testFilePath": absolute path to test file,
"coverage": {}
},
...
]
}
testRunner
[string]jest-circus/runner
jest-circus
. A custom test runner can be provided by specifying a path to a test runner implementation.function testRunner(
globalConfig: GlobalConfig,
config: ProjectConfig,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
testSequencer
[string]@jest/test-sequencer
sort
may optionally return a Promise.// testSequencer.js
const Sequencer = require('@jest/test-sequencer').default;
class CustomSequencer extends Sequencer {
sort(tests) {
// Test structure information
// https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
const copyTests = Array.from(tests);
return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
}
}
module.exports = CustomSequencer;
{
"testSequencer": "path/to/testSequencer.js"
}
testTimeout
[number]5000
testURL
[string]http://localhost
location.href
.timers
[string]real
legacy
or fake
allows the use of fake timers for functions such as setTimeout
. Fake timers are useful when a piece of code sets a long timeout that we don't want to wait for in a test.modern
, @sinonjs/fake-timers
will be used as implementation instead of Jest's own legacy implementation. This will be the default fake implementation in Jest 27.transform
[object<string, pathToTransformer | [pathToTransformer, object]>]{"\\.[jt]sx?$": "babel-jest"}
{filePattern: ['path-to-transformer', {options}]}
For example, to configure babel-jest for non-default behavior, {"\\.js$": ['babel-jest', {rootMode: "upward"}]}
--no-cache
to frequently delete Jest's cache.babel-jest
is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding {"\\.[jt]sx?$": "babel-jest"}
to the transform property. See babel-jest pluginprocess
function, and it's also recommended to include a getCacheKey
function. If your transformer is written in ESM you should have a default export with that object.transformIgnorePatterns
[array<string>]["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
<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.["<rootDir>/bower_components/", "<rootDir>/node_modules/"]
.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.unmockedModulePathPatterns
[array<string>][]
jest.mock()
/jest.unmock()
calls in individual tests. Explicit per-test setup is far easier for other readers of the test to reason about the environment the test will run in.jest.mock()
at the top of the test file.verbose
[boolean]false
true
.watchPathIgnorePatterns
[array<string>][]
<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/"]
..
).watchPlugins
[array<string | [string, object]>][]
jest-watch-master
jest-watch-select-projects
jest-watch-suspend
jest-watch-typeahead
jest-watch-yarn-workspaces
watchPlugins
property value can omit the jest-watch-
prefix of the package name.watchman
[boolean]true
watchman
for file crawling.//
[string]package.json
. Include the comment text as the value of this key anywhere in package.json
.{
"name": "my-project",
"jest": {
"//": "Comment goes here",
"verbose": true
}
}