配置 Jest

Jest的配置可以在 package.json 文件中定义或通过 jest.config.js, 与jest.config.ts 文件或通过 --config <path/to/file.js|ts|cjs|mjs|json> 选项。 如果您想要使用您的 package.json来存储 Jest的配置, "jest" 键值对应在顶层使用,这样Jest会知道如何找到您的设置:

  1. {
  2. "name": "my-project",
  3. "jest": {
  4. "verbose": true
  5. }
  6. }

或通过 JavaScript :

jest.config.js

  1. // Sync object
  2. /** @type {import('@jest/types').Config.InitialOptions} */
  3. const config = {
  4. verbose: true,
  5. };
  6. module.exports = config;
  7. // Or async function
  8. module.exports = async () => {
  9. return {
  10. verbose: true,
  11. };
  12. };

或者通过 TypeScript (如果 ts-node 已安装):

jest.config.ts

  1. import type {Config} from '@jest/types';
  2. // Sync object
  3. const config: Config.InitialOptions = {
  4. verbose: true,
  5. };
  6. export default config;
  7. // Or async function
  8. export default async (): Promise<Config.InitialOptions> => {
  9. return {
  10. verbose: true,
  11. };
  12. };

请记住,由此产生的配置必须是 JSON 序列化的。

当使用 --config 选项时,JSON 文件不能包含 “jest” 键:

  1. {
  2. "bail": 1,
  3. "verbose": true
  4. }

选项

这些选项让你可以通过package.json文件来控制Jest的行为。 Jest的理念在默认配置就能运行得很好,但有些时候我们还是需要发挥配置的功效。

默认值

您可以了解 Jest 的默认选项,以便在必要时扩展它们:

jest.config.js

  1. const {defaults} = require('jest-config');
  2. module.exports = {
  3. // ...
  4. moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  5. // ...
  6. };

参考

automock [boolean]

默认: false

此选项告诉Jest 您的测试中所有导入的模块都应该自动模拟。 在您测试中使用的所有模块都将有一个替换实现, 保留API表面。

示例:

utils.js

  1. export default {
  2. authorize: () => {
  3. return 'token';
  4. },
  5. isAuthorized: secret => secret === 'wizard',
  6. };
  1. //__tests__/automocking.test.js
  2. import utils from '../utils';
  3. test('if utils mocked automatically', () => {
  4. // Public methods of `utils` are now mock functions
  5. expect(utils.authorize.mock).toBeTruthy();
  6. expect(utils.isAuthorized.mock).toBeTruthy();
  7. // You can provide them with your own implementation
  8. // or pass the expected return value
  9. utils.authorize.mockReturnValue('mocked_token');
  10. utils.isAuthorized.mockReturnValue(true);
  11. expect(utils.authorize()).toBe('mocked_token');
  12. expect(utils.isAuthorized('not_wizard')).toBeTruthy();
  13. });

注意:当手动模拟到位时,节点模块会自动模拟(如 __mocks__/ lodash.js)。 更多信息 在这里

注意:类似 fs 这样的核心模块,默认是不模拟的。 它们可以像 jest.mock('fs') 这样被明显的指定模拟。

bail [number | boolean]

默认: 0

默认情况下,Jest运行所有测试,并在完成时将所有错误生成到控制台中。 此处可以使用bail config选项,使Jest在n失败后停止运行测试。 将bail设置为 true 等于将bail设置为 1

cacheDirectory [string]

默认: "/tmp/<path>"

Jest用来储存依赖信息缓存的目录。

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. 这一配置选项让你可以自定义Jest将缓存数据储存在磁盘的某个位置。

clearMocks [boolean]

默认: false

在每次测试之前自动清除模拟调用、实例和结果。 在每次测试之前调用 jest.clearAllMocks() 这不会删除可能已提供的任何模拟实现。

collectCoverage [boolean]

默认: false

指出是否收集测试时的覆盖率信息。 由于要带上覆盖率搜集语句重新访问所有执行过的文件,这可能会让你的测试执行速度被明显减慢。

collectCoverageFrom [array]

Default: undefined

可以用一个 通配模式 的数组来指出仅哪些文件需要收集覆盖率信息。 如果一个文件匹配上指定的模式,即使没有关于它的测试用例存在,或也没有任何测试用例依赖它,它的覆盖率信息也将被收集。

示例:

  1. {
  2. "collectCoverageFrom": [
  3. "**/*.{js,jsx}",
  4. "!**/node_modules/**",
  5. "!**/vendor/**"
  6. ]
  7. }

这个配置将收集项目的 rootDir 下的,除了能与 **/node_modules/****/vendor/** 匹配的所有文件的覆盖率信息。

注意:每个glob模式都是按照配置中指定的顺序应用的。 (例如, `[“!/tests/“, “**/.js”]不会排除tests,因为第二个模式会覆盖否定。 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…

  1. =============================== Coverage summary ===============================
  2. Statements : Unknown% ( 0/0 )
  3. Branches : Unknown% ( 0/0 )
  4. Functions : Unknown% ( 0/0 )
  5. Lines : Unknown% ( 0/0 )
  6. ================================================================================
  7. 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.

Note that using 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]>]

Default: ["clover", "json", "lcov", "text"]

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 "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:

  1. {
  2. "coverageReporters": ["clover", "json", "lcov", ["text", {"skipFull": true}]]
  3. }

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. 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.

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:

  1. {
  2. ...
  3. "jest": {
  4. "coverageThreshold": {
  5. "global": {
  6. "branches": 80,
  7. "functions": 80,
  8. "lines": 80,
  9. "statements": -10
  10. }
  11. }
  12. }
  13. }

If globs or paths are specified alongside global, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. Thresholds for globs are applied to all files matching the glob. If the file specified by path is not found, an error is returned.

For example, with the following configuration:

  1. {
  2. ...
  3. "jest": {
  4. "coverageThreshold": {
  5. "global": {
  6. "branches": 50,
  7. "functions": 50,
  8. "lines": 50,
  9. "statements": 50
  10. },
  11. "./src/components/": {
  12. "branches": 40,
  13. "statements": 40
  14. },
  15. "./src/reducers/**/*.js": {
  16. "statements": 90
  17. },
  18. "./src/api/very-important-module.js": {
  19. "branches": 100,
  20. "functions": 100,
  21. "lines": 100,
  22. "statements": 100
  23. }
  24. }
  25. }
  26. }

Jest will fail if:

  • The ./src/components directory has less than 40% branch or statement coverage.
  • One of the files matching the ./src/reducers/**/*.js glob has less than 90% statement coverage.
  • The ./src/api/very-important-module.js file has less than 100% coverage.
  • Every remaining file combined has 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.:

  1. const crypto = require('crypto');
  2. const fs = require('fs');
  3. module.exports = {
  4. extract(code, filePath, defaultExtract) {
  5. const deps = defaultExtract(code, filePath);
  6. // Scan the file and add dependencies in `deps` (which is a `Set`)
  7. return deps;
  8. },
  9. getCacheKey() {
  10. return crypto
  11. .createHash('md5')
  12. .update(fs.readFileSync(__filename))
  13. .digest('hex');
  14. },
  15. };

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. Here are sample valid values.

  1. module.exports = {
  2. displayName: 'CLIENT',
  3. };

or

  1. module.exports = {
  2. displayName: {
  3. name: 'CLIENT',
  4. color: 'blue',
  5. },
  6. };

As a secondary option, 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.

errorOnDeprecated [boolean]

默认: 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.

Note: Jest’s ESM support is still experimental, see its docs for more details.

  1. {
  2. ...
  3. "jest": {
  4. "extensionsToTreatAsEsm": [".ts"]
  5. }
  6. }

extraGlobals [array<string>]

Default: undefined

Test files run inside a vm, which slows calls to global context properties (e.g. Math). With this option you can specify extra properties to be defined inside the vm for faster lookups.

For example, if your tests call Math often, you can pass it by setting extraGlobals.

  1. {
  2. ...
  3. "jest": {
  4. "extraGlobals": ["Math"]
  5. }
  6. }

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:

sum.t.js

  1. export function sum(a, b) {
  2. return a + b;
  3. }
  4. if (process.env.NODE_ENV === 'test') {
  5. test('sum', () => {
  6. expect(sum(1, 2)).toBe(3);
  7. });
  8. }

You can collect coverage from those files with setting forceCoverageMatch.

  1. {
  2. ...
  3. "jest": {
  4. "forceCoverageMatch": ["**/*.t.js"]
  5. }
  6. }

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:

  1. {
  2. ...
  3. "jest": {
  4. "globals": {
  5. "__DEV__": true
  6. }
  7. }
  8. }

Note that, 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 exports an async function that is triggered once before all test suites. This function gets Jest’s globalConfig object as a parameter.

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 globalSetup can only be read in globalTeardown. You cannot retrieve globals defined here in your test suites.

Note: 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.

示例:

setup.js

  1. // can be synchronous
  2. module.exports = async () => {
  3. // ...
  4. // Set reference to mongod in order to close the server during teardown.
  5. global.__MONGOD__ = mongod;
  6. };

teardown.js

  1. module.exports = async function () {
  2. await global.__MONGOD__.stop();
  3. };

globalTeardown [string]

Default: undefined

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 globalConfig object as a parameter.

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 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:

  1. type HasteConfig = {
  2. /** Whether to hash files using SHA-1. */
  3. computeSha1?: boolean;
  4. /** The platform to use as the default, e.g. 'ios'. */
  5. defaultPlatform?: string | null;
  6. /** Force use of Node's `fs` APIs rather than shelling out to `find` */
  7. forceNodeFilesystemAPI?: boolean;
  8. /**
  9. * Whether to follow symlinks when crawling for files.
  10. * This options cannot be used in projects which use watchman.
  11. * Projects with `watchman` set to true will error if this option is set to true.
  12. */
  13. enableSymlinks?: boolean;
  14. /** Path to a custom implementation of Haste. */
  15. hasteImplModulePath?: string;
  16. /** All platforms to target, e.g ['ios', 'android']. */
  17. platforms?: Array<string>;
  18. /** Whether to throw on error on module collision. */
  19. throwOnModuleCollision?: boolean;
  20. /** Custom HasteMap module */
  21. hasteMapModulePath?: string;
  22. };

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.

  1. import {expect, jest, test} from '@jest/globals';
  2. jest.useFakeTimers();
  3. test('some test', () => {
  4. expect(Date.now()).toBe(0);
  5. });

Note: 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]

设定运行测试的最大工作池数目。 In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases.

For environments with variable CPUs available, you can use percentage based configuration: "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: ["node_modules", "bower_components"]

moduleFileExtensions [array<string>]

Default: ["js", "jsx", "ts", "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.

示例:

  1. {
  2. "moduleNameMapper": {
  3. "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
  4. "^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
  5. "module_name_(.*)": "<rootDir>/substituted_module_$1.js",
  6. "assets/(.*)": [
  7. "<rootDir>/images/$1",
  8. "<rootDir>/photos/$1",
  9. "<rootDir>/recipes/$1"
  10. ]
  11. }
  12. }

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 ^$ 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. Example: ["<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. Example: ["<rootDir>/app/"].

notify [boolean]

默认: false

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

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.

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 configured as follows:

  1. {
  2. "preset": "foo-bar"
  3. }

Presets may also be relative to filesystem paths.

  1. {
  2. "preset": "./node_modules/foo-bar/jest-preset.js"
  3. }

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.

  1. {
  2. "projects": ["<rootDir>", "<rootDir>/examples/*"]
  3. }

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:

  1. {
  2. "projects": [
  3. {
  4. "displayName": "test"
  5. },
  6. {
  7. "displayName": "lint",
  8. "runner": "jest-runner-eslint",
  9. "testMatch": ["<rootDir>/**/*.js"]
  10. }
  11. ]
  12. }

Note: 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.

reporters [array<moduleName | [moduleName, options]>]

Default: undefined

Use this configuration option to add custom reporters to Jest. A custom reporter is a class that implements onRunStart, onTestStart, onTestResult, onRunComplete methods that will be called when any of those events occurs.

If custom reporters are specified, the default Jest reporters will be overridden. To keep default reporters, default can be passed as a module name.

This will override default reporters:

  1. {
  2. "reporters": ["<rootDir>/my-custom-reporter.js"]
  3. }

This will use custom reporter in addition to default reporters that Jest provides:

  1. {
  2. "reporters": ["default", "<rootDir>/my-custom-reporter.js"]
  3. }

Additionally, custom reporters can be configured by passing an options object as a second argument:

  1. {
  2. "reporters": [
  3. "default",
  4. ["<rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]
  5. ]
  6. }

Custom reporter modules must define a class that takes a GlobalConfig and reporter options as constructor arguments:

Example reporter:

my-custom-reporter.js

  1. class MyCustomReporter {
  2. constructor(globalConfig, options) {
  3. this._globalConfig = globalConfig;
  4. this._options = options;
  5. }
  6. onRunComplete(contexts, results) {
  7. console.log('Custom reporter output:');
  8. console.log('GlobalConfig: ', this._globalConfig);
  9. console.log('Options: ', this._options);
  10. }
  11. }
  12. module.exports = MyCustomReporter;
  13. // or export default MyCustomReporter;

Custom reporters can also force Jest to exit with non-0 code by returning an Error from getLastError() methods

  1. class MyCustomReporter {
  2. // ...
  3. getLastError() {
  4. if (this._shouldFail) {
  5. return new Error('my-custom-reporter.js reported an error');
  6. }
  7. }
  8. }

For the full list of methods and argument types see Reporter interface in packages/jest-reporters/src/types.ts

resetMocks [boolean]

默认: 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]

默认: 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 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:

  1. {
  2. "basedir": string,
  3. "conditions": [string],
  4. "defaultResolver": "function(request, options)",
  5. "extensions": [string],
  6. "moduleDirectory": [string],
  7. "paths": [string],
  8. "packageFilter": "function(pkg, pkgdir)",
  9. "pathFilter": "function(pkg, path, relativePath)",
  10. "rootDir": [string]
  11. }

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. (request, options).

For example, if you want to respect Browserify’s “browser” field, you can use the following configuration:

  1. {
  2. ...
  3. "jest": {
  4. "resolver": "<rootDir>/resolver.js"
  5. }
  6. }

resolver.js

  1. const browserResolve = require('browser-resolve');
  2. module.exports = browserResolve.sync;

By combining defaultResolver and packageFilter we can implement a package.json “pre-processor” that allows us to change how the default resolver will resolve modules. For example, imagine we want to use the field "module" if it is present, otherwise fallback to "main":

  1. {
  2. ...
  3. "jest": {
  4. "resolver": "my-module-resolve"
  5. }
  6. }
  1. // my-module-resolve package
  2. module.exports = (request, options) => {
  3. // Call the defaultResolver, so we leverage its cache, error handling, etc.
  4. return options.defaultResolver(request, {
  5. ...options,
  6. // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
  7. packageFilter: pkg => {
  8. return {
  9. ...pkg,
  10. // Alter the value of `main` before resolving the package
  11. main: pkg.module || pkg.main,
  12. };
  13. },
  14. });
  15. };

Jest currently only supports the “main” (.) subpath from package exports. However, since Jest provides conditions as an option when calling custom resolvers, full support for exports can be implemented in userland. Jest will pass ['import', 'default'] when running a test in ESM mode, and ['require', 'default'] when running with CJS. Additionally, custom test environments can specify an exportConditions method which returns an array of conditions that will be passed along with Jest’s defaults.

restoreMocks [boolean]

默认: 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.

Note that using '<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>]

Default: ["<rootDir>"]

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 src/ directory in your repo), but prevent it from accessing the rest of the repo.

Note: While rootDir is mostly used as a token to be re-used in other configuration options, roots is used by the internals of Jest to locate test files and source files. This applies also when searching for manual mocks for modules from node_modules (__mocks__ will need to live in one of the roots).

Note: By default, roots has a single entry <rootDir> but there are cases where you may want to have multiple roots within one project, for example roots: ["<rootDir>/src/", "<rootDir>/tests/"].

runner [string]

Default: "jest-runner"

This option allows you to use a custom runner instead of Jest’s default test runner. Examples of runners include:

Note: The runner property value can omit the jest-runner- prefix of the package name.

To write a test-runner, export a class with which accepts globalConfig in the constructor, and has a runTests method with the signature:

  1. async function runTests(
  2. tests: Array<Test>,
  3. watcher: TestWatcher,
  4. onStart: OnTestStart,
  5. onResult: OnTestSuccess,
  6. onFailure: OnTestFailure,
  7. options: TestRunnerOptions,
  8. ): Promise<void>;

If you need to restrict your test-runner to only run in serial rather than being executed in parallel your class should have the property isSerial to be set as true.

setupFiles [array]

Default: []

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 before executing setupFilesAfterEnv and before the test code itself.

setupFilesAfterEnv [array]

Default: []

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 setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment but before the test code itself.

If you want a path to be relative to the root directory of your project, please include <rootDir> inside a path’s string, like "<rootDir>/a-configs-folder".

For example, Jest ships with several plug-ins to 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.

Example setupFilesAfterEnv array in a jest.config.js:

  1. module.exports = {
  2. setupFilesAfterEnv: ['./jest.setup.js'],
  3. };

Example jest.setup.js file

  1. jest.setTimeout(10000); // in milliseconds
  2. // you can even use the setup/teardown methods
  3. beforeAll(() => {
  4. // your code
  5. });
  6. beforeEach(() => {
  7. // your code
  8. });
  9. afterEach(() => {
  10. // your code
  11. });
  12. afterAll(() => {
  13. // your code
  14. });

slowTestThreshold [number]

Default: 5

The number of seconds after which a test is considered as slow and reported as such in the results.

snapshotFormat [object]

Default: undefined

Allows overriding specific snapshot formatting options documented in the pretty-format readme, with the exceptions of compareKeys and plugins. For example, this config would have the snapshot formatter not print a prefix for “Object” and “Array”:

  1. {
  2. "jest": {
  3. "snapshotFormat": {
  4. "printBasicPrototype": false
  5. }
  6. }
  7. }
  1. import {expect, test} from '@jest/globals';
  2. test('does not show prototypes for object and array inline', () => {
  3. const object = {
  4. array: [{hello: 'Danger'}],
  5. };
  6. expect(object).toMatchInlineSnapshot(`
  7. {
  8. "array": [
  9. {
  10. "hello": "Danger",
  11. },
  12. ],
  13. }
  14. `);
  15. });

snapshotResolver [string]

Default: undefined

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:

  1. module.exports = {
  2. // resolves from test to snapshot path
  3. resolveSnapshotPath: (testPath, snapshotExtension) =>
  4. testPath.replace('__tests__', '__snapshots__') + snapshotExtension,
  5. // resolves from snapshot to test path
  6. resolveTestPath: (snapshotFilePath, snapshotExtension) =>
  7. snapshotFilePath
  8. .replace('__snapshots__', '__tests__')
  9. .slice(0, -snapshotExtension.length),
  10. // Example test path, used for preflight consistency check of the implementation above
  11. testPathForConsistencyCheck: 'some/__tests__/example.test.js',
  12. };

snapshotSerializers [array<string>]

Default: []

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:

  1. // my-serializer-module
  2. module.exports = {
  3. serialize(val, config, indentation, depth, refs, printer) {
  4. return `Pretty foo: ${printer(val.foo)}`;
  5. },
  6. test(val) {
  7. return val && Object.prototype.hasOwnProperty.call(val, 'foo');
  8. },
  9. };

printer is a function that serializes a value using existing plugins.

To use my-serializer-module as a serializer, configuration would be as follows:

  1. {
  2. ...
  3. "jest": {
  4. "snapshotSerializers": ["my-serializer-module"]
  5. }
  6. }

Finally tests would look as follows:

  1. test(() => {
  2. const bar = {
  3. foo: {
  4. x: 1,
  5. y: 2,
  6. },
  7. };
  8. expect(bar).toMatchSnapshot();
  9. });

Rendered snapshot:

  1. Pretty foo: Object {
  2. "x": 1,
  3. "y": 2,
  4. }

To make a dependency explicit instead of implicit, you can call expect.addSnapshotSerializer to add a module for an individual test file instead of adding its path to snapshotSerializers in Jest configuration.

More about serializers API can be found here.

testEnvironment [string]

Default: "node"

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 jsdom instead.

By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file:

  1. /**
  2. * @jest-environment jsdom
  3. */
  4. test('use jsdom in this test file', () => {
  5. const element = document.createElement('div');
  6. expect(element).not.toBeNull();
  7. });

You can create your own module that will be used for setting up the test environment. The module must export a class with setup, teardown and getVmContext methods. You can also pass variables from this module to your test suites by assigning them to this.global object – this will make them available in your test suites as global variables.

The class may optionally expose an asynchronous handleTestEvent method to bind to events fired by jest-circus. Normally, jest-circus test runner would pause until a promise returned from handleTestEvent gets fulfilled, except for the next events: start_describe_definition, finish_describe_definition, add_hook, add_test or error (for the up-to-date list you can look at SyncEvent type in the types definitions). That is caused by backward compatibility reasons and process.on('unhandledRejection', callback) signature, but that usually should not be a problem for most of the use cases.

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 my-custom-environment.js in some subfolder of your project, then the annotation might look like this:

  1. /**
  2. * @jest-environment ./src/test/my-custom-environment
  3. */

Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.

示例:

  1. // my-custom-environment
  2. const NodeEnvironment = require('jest-environment-node');
  3. class CustomEnvironment extends NodeEnvironment {
  4. constructor(config, context) {
  5. super(config, context);
  6. this.testPath = context.testPath;
  7. this.docblockPragmas = context.docblockPragmas;
  8. }
  9. async setup() {
  10. await super.setup();
  11. await someSetupTasks(this.testPath);
  12. this.global.someGlobalObject = createGlobalObject();
  13. // Will trigger if docblock contains @my-custom-pragma my-pragma-value
  14. if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
  15. // ...
  16. }
  17. }
  18. async teardown() {
  19. this.global.someGlobalObject = destroyGlobalObject();
  20. await someTeardownTasks();
  21. await super.teardown();
  22. }
  23. getVmContext() {
  24. return super.getVmContext();
  25. }
  26. async handleTestEvent(event, state) {
  27. if (event.name === 'test_start') {
  28. // ...
  29. }
  30. }
  31. }
  32. module.exports = CustomEnvironment;
  1. // my-test-suite
  2. /**
  3. * @jest-environment ./my-custom-environment
  4. */
  5. let someGlobalObject;
  6. beforeAll(() => {
  7. someGlobalObject = global.someGlobalObject;
  8. });

testEnvironmentOptions [Object]

Default: {}

Test environment options that will be passed to the testEnvironment. The relevant options depend on the environment. For example, you can override options given to jsdom such as {html: "<html lang="zh-cmn-Hant"></html>", userAgent: "Agent/007"}.

testFailureExitCode [number]

Default: 1

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).

testMatch [array<string>]

(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ])

The glob patterns Jest uses to detect test files. By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js.

See the micromatch package for details of the patterns you can specify.

See also testRegex [string | array<string>], but note that you cannot specify both options.

注意:每个glob模式都是按照配置中指定的顺序应用的。 (For example `[“!/fixtures/“, “/tests//.js”]will not excludefixturesbecause the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after/tests//.js`.)

testPathIgnorePatterns [array<string>]

Default: ["/node_modules/"]

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 <rootDir> string token to include the path to your project’s root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/", "<rootDir>/node_modules/"].

testRegex [string | array<string>]

Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$

The pattern or patterns Jest uses to detect test files. By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js. See also testMatch [array<string>], but note that you cannot specify both options.

The following is a visualization of the default regex:

  1. ├── __tests__
  2. └── component.spec.js # test
  3. └── anything # test
  4. ├── package.json # not test
  5. ├── foo.test.js # test
  6. ├── bar.spec.jsx # test
  7. └── component.js # not test

Note: testRegex will try to detect test files using the absolute file path, therefore, having a folder with a name that matches it will run all the files as tests

testResultsProcessor [string]

Default: undefined

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:

  1. {
  2. "success": boolean,
  3. "startTime": epoch,
  4. "numTotalTestSuites": number,
  5. "numPassedTestSuites": number,
  6. "numFailedTestSuites": number,
  7. "numRuntimeErrorTestSuites": number,
  8. "numTotalTests": number,
  9. "numPassedTests": number,
  10. "numFailedTests": number,
  11. "numPendingTests": number,
  12. "numTodoTests": number,
  13. "openHandles": Array<Error>,
  14. "testResults": [{
  15. "numFailingTests": number,
  16. "numPassingTests": number,
  17. "numPendingTests": number,
  18. "testResults": [{
  19. "title": string (message in it block),
  20. "status": "failed" | "pending" | "passed",
  21. "ancestorTitles": [string (message in describe blocks)],
  22. "failureMessages": [string],
  23. "numPassingAsserts": number,
  24. "location": {
  25. "column": number,
  26. "line": number
  27. }
  28. },
  29. ...
  30. ],
  31. "perfStats": {
  32. "start": epoch,
  33. "end": epoch
  34. },
  35. "testFilePath": absolute path to test file,
  36. "coverage": {}
  37. },
  38. "testExecError:" (exists if there was a top-level failure) {
  39. "message": string
  40. "stack": string
  41. }
  42. ...
  43. ]
  44. }

testResultsProcessor and reporters are very similar to each other. One difference is that a test result processor only gets called after all tests finished. Whereas a reporter has the ability to receive test results after individual tests and/or test suites are finished.

testRunner [string]

Default: jest-circus/runner

This option allows the use of a custom test runner. The default is jest-circus. A custom test runner can be provided by specifying a path to a test runner implementation.

The test runner module must export a function with the following signature:

  1. function testRunner(
  2. globalConfig: GlobalConfig,
  3. config: ProjectConfig,
  4. environment: Environment,
  5. runtime: Runtime,
  6. testPath: string,
  7. ): Promise<TestResult>;

An example of such function can be found in our default jasmine2 test runner package.

testSequencer [string]

Default: @jest/test-sequencer

This option allows you to use a custom sequencer instead of Jest’s default. sort may optionally return a Promise.

示例:

Sort test path alphabetically.

testSequencer.js

  1. const Sequencer = require('@jest/test-sequencer').default;
  2. class CustomSequencer extends Sequencer {
  3. sort(tests) {
  4. // Test structure information
  5. // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
  6. const copyTests = Array.from(tests);
  7. return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
  8. }
  9. }
  10. module.exports = CustomSequencer;

Use it in your Jest config file like this:

  1. {
  2. "testSequencer": "path/to/testSequencer.js"
  3. }

testTimeout [number]

Default: 5000

Default timeout of a test in milliseconds.

testURL [string]

Default: http://localhost

This option sets the URL for the jsdom environment. It is reflected in properties such as location.href.

timers [string]

Default: real

Setting this value to fake or modern enables fake timers for all tests by default. Fake timers are useful when a piece of code sets a long timeout that we don’t want to wait for in a test. You can learn more about fake timers here.

If the value is legacy, the old implementation will be used as implementation instead of one backed by @sinonjs/fake-timers.

transform [object<string, pathToTransformer | [pathToTransformer, object]>]

Default: {"\\.[jt]sx?$": "babel-jest"}

A map from regular expressions to paths to transformers. 转换器是为转换源文件提供同步功能的模块。 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 {filePattern: ['path-to-transformer', {options}]} For example, to configure babel-jest for non-default behavior, {"\\.js$": ['babel-jest', {rootMode: "upward"}]}

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 --no-cache to frequently delete Jest’s cache.

Note: when adding additional code transformers, this will overwrite the default config and 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 plugin

A transformer must be an object with at least a process 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.

If the tests are written using native ESM the transformer can export processAsync and getCacheKeyAsync instead or in addition to the synchronous variants.

transformIgnorePatterns [array<string>]

Default: ["/node_modules/", "\\.pnp\\.[^\\\/]+$"]

An array of regexp pattern strings that are matched against all source file paths before transformation. If the file path matches any of the patterns, it will not be transformed.

Providing regexp patterns that overlap with each other may result in files not being transformed that you expected to be transformed. 例如:

  1. {
  2. "transformIgnorePatterns": ["/node_modules/(?!(foo|bar)/)", "/bar/"]
  3. }

The first pattern will match (and therefore not transform) files inside /node_modules except for those in /node_modules/foo/ and /node_modules/bar/. The second pattern will match (and therefore not transform) files inside any path with /bar/ in it. With the two together, files in /node_modules/bar/ will not be transformed because it does match the second pattern, even though it was excluded by the first.

Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled code. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns to allow transpiling such modules. You’ll find a good example of this use case in React Native Guide.

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.

示例:

  1. {
  2. "transformIgnorePatterns": [
  3. "<rootDir>/bower_components/",
  4. "<rootDir>/node_modules/"
  5. ]
  6. }

unmockedModulePathPatterns [array<string>]

Default: []

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 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.

It is possible to override this setting in individual tests by explicitly calling jest.mock() at the top of the test file.

verbose [boolean]

默认: false

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 true.

watchPathIgnorePatterns [array<string>]

Default: []

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 <rootDir> string token to include the path to your project’s root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/node_modules/"].

Even if nothing is specified here, the watcher will ignore changes to the version control folders (.git, .hg). Other hidden files and directories, i.e. those that begin with a dot (.), are watched by default. Remember to escape the dot when you add them to watchPathIgnorePatterns as it is a special RegExp character.

示例:

  1. {
  2. "watchPathIgnorePatterns": ["<rootDir>/\\.tmp/", "<rootDir>/bar/"]
  3. }

watchPlugins [array<string | [string, Object]>]

Default: []

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 watchPlugins property value can omit the jest-watch- prefix of the package name.

watchman [boolean]

Default: true

Whether to use watchman for file crawling.

// [string]

No default

This option allows comments in package.json. Include the comment text as the value of this key anywhere in package.json.

示例:

  1. {
  2. "name": "my-project",
  3. "jest": {
  4. "//": "Comment goes here",
  5. "verbose": true
  6. }
  7. }