配置 Jest

Jest的理念在默认配置就能运行得很好,但有些时候我们还是需要发挥配置的功效。

建议编写一个专用的Javascript、Typescript 或 JSON格式的配置文件,这样方便对配置进行维护。 Jest会自动查找目录下文件名为 jest.config.js|ts|mjs|cjs|json 的配置文件, 你也可以使用 --config 参数传入配置文件的绝对路径。

配置 Jest - 图1note

注意配置文件最后导出的对象一定要是可被JSON序列化的

配置文件应该只导出一个对象,如下:

  • JavaScript
  • TypeScript
  1. // 第一种方式
  2. /** @type {import('jest').Config} */
  3. const config = {
  4. verbose: true,
  5. };
  6. module.exports = config;
  1. // 第二种方式
  2. import type {Config} from 'jest';
  3. const config: Config = {
  4. verbose: true,
  5. };
  6. export default config;

或者通过函数返回一个对象:

  • JavaScript
  • TypeScript
  1. // 第一种方式
  2. /** @returns {Promise<import('jest').Config>} */
  3. module.exports = async () => {
  4. return {
  5. verbose: true,
  6. };
  7. };
  1. // 第二种方式
  2. import type {Config} from 'jest';
  3. export default async (): Promise<Config> => {
  4. return {
  5. verbose: true,
  6. };
  7. };

配置 Jest - 图2tip

提示:使用 Typescript 配置文件的还需给 Jest 安装 ts-node, 请确保在项目中安装该依赖。

你也可以将配置作为一个普通对象保存在JSON格式的文件里:

jest.config.json

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

或者,可以在项目 package.json 里的 "jest" 键进行配置 Jest,如:

package.json

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

选项

配置 Jest - 图3info

你可以从 jest-config 获取 Jest 的默认配置,以便完成定制化配置:

  • JavaScript
  • TypeScript
  1. const {defaults} = require('jest-config');
  2. /** @type {import('jest').Config} */
  3. const config = {
  4. moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts', 'cts'],
  5. };
  6. module.exports = config;
  1. import type {Config} from 'jest';
  2. import {defaults} from 'jest-config';
  3. const config: Config = {
  4. moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts'],
  5. };
  6. export default config;

参考

automock [boolean]

默认: false

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

示例:

utils.js

  1. export default {
  2. authorize: () => 'token',
  3. isAuthorized: secret => secret === 'wizard',
  4. };

__tests__/automock.test.js

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

配置 Jest - 图4note

Node modules are automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js). More info here.

Node.js core modules, like fs, are not mocked by default. 它们可以像 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

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

Jest ships with two coverage providers: babel (default) and v8. See the coverageProvider option for more details.

配置 Jest - 图5info

The babel and v8 coverage providers use /* istanbul ignore next */ and /* c8 ignore next */ comments to exclude lines from coverage reports, respectively. For more information, you can view the istanbuljs documentation and the c8 documentation.

collectCoverageFrom [array]

Default: undefined

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

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. collectCoverageFrom: [
  4. '**/*.{js,jsx}',
  5. '!**/node_modules/**',
  6. '!**/vendor/**',
  7. ],
  8. };
  9. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. collectCoverageFrom: [
  4. '**/*.{js,jsx}',
  5. '!**/node_modules/**',
  6. '!**/vendor/**',
  7. ],
  8. };
  9. export default config;

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

配置 Jest - 图6tip

Each glob pattern is applied in the order they are specified in the config. For example ["!**/__tests__/**", "**/*.js"] will not exclude __tests__ because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after **/*.js.

配置 Jest - 图7note

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.

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.

配置 Jest - 图8tip

Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output.

Additional options can be passed using the tuple form. For example, you may hide coverage report lines for all fully-covered files:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
  4. };
  5. export default config;

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:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. coverageThreshold: {
  4. global: {
  5. branches: 80,
  6. functions: 80,
  7. lines: 80,
  8. statements: -10,
  9. },
  10. },
  11. };
  12. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. coverageThreshold: {
  4. global: {
  5. branches: 80,
  6. functions: 80,
  7. lines: 80,
  8. statements: -10,
  9. },
  10. },
  11. };
  12. export default config;

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:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. coverageThreshold: {
  4. global: {
  5. branches: 50,
  6. functions: 50,
  7. lines: 50,
  8. statements: 50,
  9. },
  10. './src/components/': {
  11. branches: 40,
  12. statements: 40,
  13. },
  14. './src/reducers/**/*.js': {
  15. statements: 90,
  16. },
  17. './src/api/very-important-module.js': {
  18. branches: 100,
  19. functions: 100,
  20. lines: 100,
  21. statements: 100,
  22. },
  23. },
  24. };
  25. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. coverageThreshold: {
  4. global: {
  5. branches: 50,
  6. functions: 50,
  7. lines: 50,
  8. statements: 50,
  9. },
  10. './src/components/': {
  11. branches: 40,
  12. statements: 40,
  13. },
  14. './src/reducers/**/*.js': {
  15. statements: 90,
  16. },
  17. './src/api/very-important-module.js': {
  18. branches: 100,
  19. functions: 100,
  20. lines: 100,
  21. statements: 100,
  22. },
  23. },
  24. };
  25. export default config;

Jest will fail if:

  • ./src/components 目录的分支(branch)或语句(statement)覆盖率低于40%
  • ./src/reducers/**/*.js 匹配的任何一个文件的语句覆盖率低于90%
  • 文件 ./src/api/very-important-module.js 的任意一种覆盖率低于 100%
  • 除了上述三种规则外的所有文件,任意一种覆盖率低于50%

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.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. displayName: 'CLIENT',
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. displayName: 'CLIENT',
  4. };
  5. export default config;

或者传入一个具有属性 namecolor 的对象。 This allows for a custom configuration of the background color of the displayName. displayName defaults to white when its value is a string. Jest 使用 chalk 来显示颜色。 因此,Jest 支持所有在 chalk 可用的选项。

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. displayName: {
  4. name: 'CLIENT',
  5. color: 'blue',
  6. },
  7. };
  8. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. displayName: {
  4. name: 'CLIENT',
  5. color: 'blue',
  6. },
  7. };
  8. export default config;

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.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. extensionsToTreatAsEsm: ['.ts'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. extensionsToTreatAsEsm: ['.ts'],
  4. };
  5. export default config;

配置 Jest - 图9caution

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

fakeTimers [object]

Default: {}

The fake timers may be useful when a piece of code sets a long timeout that we don’t want to wait for in a test. For additional details see Fake Timers guide and API documentation.

This option provides the default configuration of fake timers for all tests. Calling jest.useFakeTimers() in a test file will use these options or will override them if a configuration object is passed. For example, you can tell Jest to keep the original implementation of process.nextTick() and adjust the limit of recursive timers that will be run:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. fakeTimers: {
  4. doNotFake: ['nextTick'],
  5. timerLimit: 1000,
  6. },
  7. };
  8. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. fakeTimers: {
  4. doNotFake: ['nextTick'],
  5. timerLimit: 1000,
  6. },
  7. };
  8. export default config;

fakeTime.test.js

  1. // install fake timers for this file using the options from Jest configuration
  2. jest.useFakeTimers();
  3. test('increase the limit of recursive timers for this and following tests', () => {
  4. jest.useFakeTimers({timerLimit: 5000});
  5. // ...
  6. });

配置 Jest - 图10tip

除了在每个文件里使用 jest.useFakeTimers()之外,你还可以在全局 Jest 配置里启用 fake timers 选项:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. fakeTimers: {
  4. enableGlobally: true,
  5. },
  6. };
  7. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. fakeTimers: {
  4. enableGlobally: true,
  5. },
  6. };
  7. export default config;

配置选项

  1. type FakeableAPI =
  2. | 'Date'
  3. | 'hrtime'
  4. | 'nextTick'
  5. | 'performance'
  6. | 'queueMicrotask'
  7. | 'requestAnimationFrame'
  8. | 'cancelAnimationFrame'
  9. | 'requestIdleCallback'
  10. | 'cancelIdleCallback'
  11. | 'setImmediate'
  12. | 'clearImmediate'
  13. | 'setInterval'
  14. | 'clearInterval'
  15. | 'setTimeout'
  16. | 'clearTimeout';
  17. type ModernFakeTimersConfig = {
  18. /**
  19. * If set to `true` all timers will be advanced automatically by 20 milliseconds
  20. * every 20 milliseconds. 设置数字可以提供一个自定义的时间间隔
  21. * 默认为 false
  22. */
  23. advanceTimers?: boolean | number;
  24. /**
  25. * 传入不该被替换的API列表 默认是 [] 代表全部的API都被会替换
  26. */
  27. doNotFake?: Array<FakeableAPI>;
  28. /** Whether fake timers should be enabled for all test files. The default is `false`. */
  29. enableGlobally?: boolean;
  30. /**
  31. * Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.
  32. * 默认为 false
  33. */
  34. legacyFakeTimers?: boolean;
  35. /** 设置假定时器的当前系统时间 默认值是 `Date.now ()`。 */
  36. now?: number;
  37. /** Maximum number of recursive timers that will be run. The default is `100_000` timers. */
  38. timerLimit?: number;
  39. };

旧版本的假定时器

出于某些原因,你可能不得不使用旧版本的假定时器。 Here is how to enable it globally (additional options are not supported):

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. fakeTimers: {
  4. enableGlobally: true,
  5. legacyFakeTimers: true,
  6. },
  7. };
  8. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. fakeTimers: {
  4. enableGlobally: true,
  5. legacyFakeTimers: true,
  6. },
  7. };
  8. export default config;

:::

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.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. forceCoverageMatch: ['**/*.t.js'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. forceCoverageMatch: ['**/*.t.js'],
  4. };
  5. export default config;

globals [object]

Default: {}

A set of global variables that need to be available in all test environments.

For example, the following would create a global __DEV__ variable set to true in all test environments:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. globals: {
  4. __DEV__: true,
  5. },
  6. };
  7. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. globals: {
  4. __DEV__: true,
  5. },
  6. };
  7. export default config;

配置 Jest - 图11note

If you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will not be persisted across test runs for other test files. In addition, the globals object must be json-serializable, so it can’t be used to specify global functions. For that, you should use setupFiles.

globalSetup [string]

Default: undefined

This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest’s globalConfig and projectConfig.

配置 Jest - 图12info

A global setup module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.

Any global variables that are defined through globalSetup can only be read in globalTeardown. You cannot retrieve globals defined here in your test suites.

While code transformation is applied to the linked setup-file, Jest will not transform any code in node_modules. This is due to the need to load the actual transformers (e.g. babel or typescript) to perform transformation.

setup.js

  1. module.exports = async function (globalConfig, projectConfig) {
  2. console.log(globalConfig.testPathPattern);
  3. console.log(projectConfig.cache);
  4. // Set reference to mongod in order to close the server during teardown.
  5. globalThis.__MONGOD__ = mongod;
  6. };

teardown.js

  1. module.exports = async function (globalConfig, projectConfig) {
  2. console.log(globalConfig.testPathPattern);
  3. console.log(projectConfig.cache);
  4. await globalThis.__MONGOD__.stop();
  5. };

globalTeardown [string]

Default: undefined

This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest’s globalConfig and projectConfig.

配置 Jest - 图13info

A global teardown module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.

The same caveat concerning transformation of node_modules as for globalSetup applies to globalTeardown.

haste [object]

Default: undefined

This will be used to configure the behavior of jest-haste-map, Jest’s internal file crawler/cache system. The following options are supported:

  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. /** Whether to retain all files, allowing e.g. search for tests in `node_modules`. */
  23. retainAllFiles?: boolean;
  24. };

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

配置 Jest - 图14note

这个选项仅在使用jest-circus进行测试时生效

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.

如果测试环境的CPU数量是不确定的,你可以使用百分比进行配置:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. maxWorkers: '50%',
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. maxWorkers: '50%',
  4. };
  5. export default config;

moduleDirectories [array<string>]

Default: ["node_modules"]

An array of directory names to be searched recursively up from the requiring module’s location. 设置此选项将 覆盖 默认值。如果你想继续搜索 node_modules 中的模块,就把它和其他选项一起保留。例如:["node_modules"、"bower_components"]

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. moduleDirectories: ['node_modules', 'bower_components'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. moduleDirectories: ['node_modules', 'bower_components'],
  4. };
  5. export default config;

moduleFileExtensions [array<string>]

Default: ["js", "mjs", "cjs", "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.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. moduleNameMapper: {
  4. '^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
  5. '^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
  6. 'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
  7. 'assets/(.*)': [
  8. '<rootDir>/images/$1',
  9. '<rootDir>/photos/$1',
  10. '<rootDir>/recipes/$1',
  11. ],
  12. },
  13. };
  14. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. moduleNameMapper: {
  4. '^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
  5. '^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
  6. 'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
  7. 'assets/(.*)': [
  8. '<rootDir>/images/$1',
  9. '<rootDir>/photos/$1',
  10. '<rootDir>/recipes/$1',
  11. ],
  12. },
  13. };
  14. export default config;

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.

配置 Jest - 图15info

If you provide module names without boundaries ^$ it may cause hard to spot errors. E.g. relay will replace all modules which contain relay as a substring in its name: relay, react-relay and graphql-relay will all be pointed to your stub.

modulePathIgnorePatterns [array<string>]

Default: []

An array of regexp pattern strings that are matched against all module paths before those paths are to be considered ‘visible’ to the module loader. If a given module’s path matches any of the patterns, it will not be require()-able in the test environment.

These pattern strings match against the full path. Use the <rootDir> string token to include the path to your project’s root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. modulePathIgnorePatterns: ['<rootDir>/build/'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. modulePathIgnorePatterns: ['<rootDir>/build/'],
  4. };
  5. export default config;

modulePaths [array<string>]

Default: []

An alternative API to setting the NODE_PATH env variable, modulePaths is an array of absolute paths to additional locations to search when resolving modules. Use the <rootDir> string token to include the path to your project’s root directory.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. modulePaths: ['<rootDir>/app/'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. modulePaths: ['<rootDir>/app/'],
  4. };
  5. export default config;

notify [boolean]

默认: false

Activates native OS notifications for test results. To display the notifications Jest needs node-notifier package, which must be installed additionally:

  • npm
  • Yarn
  1. npm install --save-dev node-notifier
  1. yarn add --dev node-notifier

配置 Jest - 图16tip

On macOS, remember to allow notifications from terminal-notifier under System Preferences > Notifications & Focus.

On Windows, node-notifier creates a new start menu entry on the first use and not display the notification. Notifications will be properly displayed on subsequent runs.

notifyMode [string]

Default: failure-change

Specifies notification mode. Requires notify: true.

Modes

  • always: always send a notification.
  • failure: send a notification when tests fail.
  • success: send a notification when tests pass.
  • change: send a notification when the status changed.
  • success-change: send a notification when tests pass or once when it fails.
  • failure-change: send a notification when tests fail or once when it passes.

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:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. preset: 'foo-bar',
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. preset: 'foo-bar',
  4. };
  5. export default config;

preset 也可以是相对于文件系统路径:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. preset: './node_modules/foo-bar/jest-preset.js',
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. preset: './node_modules/foo-bar/jest-preset.js',
  4. };
  5. export default config;

配置 Jest - 图17info

If you also have specified rootDir, the resolution of this file will be relative to that root directory.

prettierPath [string]

Default: 'prettier'

Sets the path to the prettier node module used to update inline snapshots.

projects [array<string | ProjectConfig>]

Default: undefined

When the projects configuration is provided with an array of paths or glob patterns, Jest will run tests in all of the specified projects at the same time. This is great for monorepos or when working on multiple projects at the same time.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. projects: ['<rootDir>', '<rootDir>/examples/*'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. projects: ['<rootDir>', '<rootDir>/examples/*'],
  4. };
  5. export default config;

This example configuration will run Jest in the root directory as well as in every folder in the examples directory. You can have an unlimited amount of projects running in the same Jest instance.

The projects feature can also be used to run multiple configurations or multiple runners. For this purpose, you can pass an array of configuration objects. For example, to run both tests and ESLint (via jest-runner-eslint) in the same invocation of Jest:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. projects: [
  4. {
  5. displayName: 'test',
  6. },
  7. {
  8. displayName: 'lint',
  9. runner: 'jest-runner-eslint',
  10. testMatch: ['<rootDir>/**/*.js'],
  11. },
  12. ],
  13. };
  14. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. projects: [
  4. {
  5. displayName: 'test',
  6. },
  7. {
  8. displayName: 'lint',
  9. runner: 'jest-runner-eslint',
  10. testMatch: ['<rootDir>/**/*.js'],
  11. },
  12. ],
  13. };
  14. export default config;

配置 Jest - 图18tip

当使用多项目runner时,建议为每个项目添加 displayName。 This will show the displayName of a project next to its tests.

配置 Jest - 图19note

With the projects option enabled, Jest will copy the root-level configuration options to each individual child configuration during the test run, resolving its values in the child’s context. This means that string tokens like <rootDir> will point to the child’s root directory even if they are defined in the root-level configuration.

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

Default: undefined

使用此配置选项将reporters添加到Jest。 It must be a list of reporter names, additional options can be passed to a reporter using the tuple form:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. reporters: [
  4. 'default',
  5. ['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
  6. ],
  7. };
  8. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. reporters: [
  4. 'default',
  5. ['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
  6. ],
  7. };
  8. export default config;

Default Reporter

If custom reporters are specified, the default Jest reporter will be overridden. If you wish to keep it, 'default' must be passed as a reporters name:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. reporters: [
  4. 'default',
  5. ['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
  6. ],
  7. };
  8. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. reporters: [
  4. 'default',
  5. ['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
  6. ],
  7. };
  8. export default config;

GitHub Actions Reporter

If included in the list, the built-in GitHub Actions Reporter will annotate changed files with test failure messages and (if used with 'silent: false') print logs with github group features for easy navigation. Note that 'default' should not be used in this case as 'github-actions' will handle that already, so remember to also include 'summary'. If you wish to use it only for annotations simply leave only the reporter without options as the default value of 'silent' is 'true':

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. reporters: [['github-actions', {silent: false}], 'summary'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. reporters: [['github-actions', {silent: false}], 'summary'],
  4. };
  5. export default config;

Summary Reporter

Summary reporter prints out summary of all tests. It is a part of default reporter, hence it will be enabled if 'default' is included in the list. For instance, you might want to use it as stand-alone reporter instead of the default one, or together with Silent Reporter:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. reporters: ['jest-silent-reporter', 'summary'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. reporters: ['jest-silent-reporter', 'summary'],
  4. };
  5. export default config;

Custom Reporters

配置 Jest - 图20tip

Hungry for reporters? Take a look at long list of awesome reporters from Awesome Jest.

Custom reporter module must export a class that takes globalConfig, reporterOptions and reporterContext as constructor arguments and implements at least onRunComplete() method (for the full list of methods and argument types see Reporter interface in packages/jest-reporters/src/types.ts):

custom-reporter.js

  1. class CustomReporter {
  2. constructor(globalConfig, reporterOptions, reporterContext) {
  3. this._globalConfig = globalConfig;
  4. this._options = reporterOptions;
  5. this._context = reporterContext;
  6. }
  7. onRunComplete(testContexts, results) {
  8. console.log('Custom reporter output:');
  9. console.log('global config: ', this._globalConfig);
  10. console.log('options for this reporter from Jest config: ', this._options);
  11. console.log('reporter context passed from test scheduler: ', this._context);
  12. }
  13. // Optionally, reporters can force Jest to exit with non zero code by returning
  14. // an `Error` from `getLastError()` method.
  15. getLastError() {
  16. if (this._shouldFail) {
  17. return new Error('Custom error reported!');
  18. }
  19. }
  20. }
  21. module.exports = CustomReporter;

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 module that exports either:

  1. a function expecting a string as the first argument for the path to resolve and an options object as the second argument. The function should either return a path to the module that should be resolved or throw an error if the module can’t be found. or
  2. an object containing async and/or sync properties. The sync property should be a function with the shape explained above, and the async property should also be a function that accepts the same arguments, but returns a promise which resolves with the path to the module or rejects with an error.

The options object provided to resolvers has the shape:

  1. type ResolverOptions = {
  2. /** Directory to begin resolving from. */
  3. basedir: string;
  4. /** List of export conditions. */
  5. conditions?: Array<string>;
  6. /** Instance of default resolver. */
  7. defaultResolver: (path: string, options: ResolverOptions) => string;
  8. /** List of file extensions to search in order. */
  9. extensions?: Array<string>;
  10. /** List of directory names to be looked up for modules recursively. */
  11. moduleDirectory?: Array<string>;
  12. /** List of `require.paths` to use if nothing is found in `node_modules`. */
  13. paths?: Array<string>;
  14. /** Allows transforming parsed `package.json` contents. */
  15. packageFilter?: (pkg: PackageJSON, file: string, dir: string) => PackageJSON;
  16. /** Allows transforms a path within a package. */
  17. pathFilter?: (pkg: PackageJSON, path: string, relativePath: string) => string;
  18. /** Current root directory. */
  19. rootDir?: string;
  20. };

配置 Jest - 图21tip

The defaultResolver passed as an option is the Jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom synchronous one, e.g. (path, options) and returns a string or throws.

例如,如果你想要遵循 Browserify 的 “browser” field, 你可以使用以下 resolver :

resolver.js

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

然后加入到配置里:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. resolver: '<rootDir>/resolver.js',
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. resolver: '<rootDir>/resolver.js',
  4. };
  5. export default config;

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

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.

配置 Jest - 图22tip

Using '<rootDir>' as a string token in any other path-based configuration settings will refer back to this value. For example, if you want a setupFiles entry to point at the some-setup.js file at the root of the project, set its value to: '<rootDir>/some-setup.js'.

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.

配置 Jest - 图23info

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

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:

配置 Jest - 图24info

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.

sandboxInjectedGlobals [array<string>]

配置 Jest - 图25tip

Renamed from extraGlobals in Jest 28.

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

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. sandboxInjectedGlobals: ['Math'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. sandboxInjectedGlobals: ['Math'],
  4. };
  5. export default config;

配置 Jest - 图26note

This option has no effect if you use native ESM.

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.

配置 Jest - 图27tip

If your setup script is a CJS module, it may export an async function. Jest will call the function and await its result. This might be useful to fetch some data asynchronously. If the file is an ESM module, simply use top-level await to achieve the same result.

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.

In other words, setupFilesAfterEnv modules are meant for code which is repeating in each test file. Having the test framework installed makes Jest globals, jest object and expect accessible in the modules. For example, you can add extra matchers from jest-extended library or call setup and teardown hooks:

setup-jest.js

  1. const matchers = require('jest-extended');
  2. expect.extend(matchers);
  3. afterEach(() => {
  4. jest.useRealTimers();
  5. });
  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. setupFilesAfterEnv: ['<rootDir>/setup-matchers.js'],
  4. };
  5. export default config;

showSeed [boolean]

默认: false

The equivalent of the --showSeed flag to print the seed in the test report summary.

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: {escapeString: false, printBasicPrototype: false}

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

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. snapshotFormat: {
  4. printBasicPrototype: false,
  5. },
  6. };
  7. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. snapshotFormat: {
  4. printBasicPrototype: false,
  5. },
  6. };
  7. export default config;

some.test.js

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

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.

custom-resolver.js

  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.

custom-serializer.js

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

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

custom-serializer 加入到配置里:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. snapshotSerializers: ['path/to/custom-serializer.js'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. snapshotSerializers: ['path/to/custom-serializer.js'],
  4. };
  5. export default config;

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

配置 Jest - 图28tip

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 constructor is passed globalConfig and projectConfig as its first argument, and testEnvironmentContext as its second.

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

配置 Jest - 图29info

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

testEnvironmentOptions [Object]

Default: {}

Test environment options that will be passed to the testEnvironment. The relevant options depend on the environment.

For example, in jest-environment-jsdom, you can override options given to jsdom such as {html: "<html lang="zh-cmn-Hant"></html>", url: 'https://jestjs.io/', userAgent: "Agent/007"}.

Both jest-environment-jsdom and jest-environment-node allow specifying customExportConditions, which allow you to control which versions of a library are loaded from exports in package.json. jest-environment-jsdom defaults to ['browser']. jest-environment-node defaults to ['node', 'node-addons'].

These options can also be passed in a docblock, similar to testEnvironment. The string with options must be parseable by JSON.parse:

  1. /**
  2. * @jest-environment jsdom
  3. * @jest-environment-options {"url": "https://jestjs.io/"}
  4. */
  5. test('use jsdom and set the URL in this test file', () => {
  6. expect(window.location.href).toBe('https://jestjs.io/');
  7. });

testFailureExitCode [number]

Default: 1

The exit code Jest returns on test failure.

配置 Jest - 图30info

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.

配置 Jest - 图31tip

Each glob pattern is applied in the order they are specified in the config. For example ["!**/__fixtures__/**", "**/__tests__/**/*.js"] will not exclude __fixtures__ because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after **/__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

配置 Jest - 图32info

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. "duration": number | null
  29. },
  30. ...
  31. ],
  32. "perfStats": {
  33. "start": epoch,
  34. "end": epoch
  35. },
  36. "testFilePath": absolute path to test file,
  37. "coverage": {}
  38. },
  39. "testExecError:" (exists if there was a top-level failure) {
  40. "message": string
  41. "stack": string
  42. }
  43. ...
  44. ]
  45. }

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.

配置 Jest - 图33tip

Both sort and shard may optionally return a Promise.

比如,可以按字母顺序将路径排序:

custom-sequencer.js

  1. const Sequencer = require('@jest/test-sequencer').default;
  2. class CustomSequencer extends Sequencer {
  3. /**
  4. * 通过 --shard=shardIndex/shardCount 选择所有的测试
  5. * 排序前会完成测试分片的工作
  6. */
  7. shard(tests, {shardIndex, shardCount}) {
  8. const shardSize = Math.ceil(tests.length / shardCount);
  9. const shardStart = shardSize * (shardIndex - 1);
  10. const shardEnd = shardSize * shardIndex;
  11. return [...tests]
  12. .sort((a, b) => (a.path > b.path ? 1 : -1))
  13. .slice(shardStart, shardEnd);
  14. }
  15. /**
  16. * Sort test to determine order of execution
  17. * Sorting is applied after sharding
  18. */
  19. sort(tests) {
  20. // Test structure information
  21. // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
  22. const copyTests = Array.from(tests);
  23. return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
  24. }
  25. }
  26. module.exports = CustomSequencer;

custom-serializer 加入到配置里:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. testSequencer: 'path/to/custom-sequencer.js',
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. testSequencer: 'path/to/custom-sequencer.js',
  4. };
  5. export default config;

testTimeout [number]

Default: 5000

Default timeout of a test in milliseconds.

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

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

A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: {filePattern: ['path-to-transformer', {options}]}. For example, here is how you can configure babel-jest for non-default behavior: {'\\.js$': ['babel-jest', {rootMode: 'upward'}]}.

Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use babel-jest transformer, which will load your project’s Babel configuration and transform any file matching the /\.[jt]sx?$/ RegExp (in other words, any .js, .jsx, .ts or .tsx file). 此外,babel-jest还将会注入 ES Module mocking中所提到的Babel插件。

See the Code Transformation section for more details and instructions on building your own transformer.

配置 Jest - 图34tip

Keep in mind that a transformer only runs once per file unless the file has changed.

记住,如果你想将它和其他代码预处理器一起使用,那必须要显式地引入默认的 babel-jest 转译器,

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. transform: {
  4. '\\.[jt]sx?$': 'babel-jest',
  5. '\\.css$': 'some-css-transformer',
  6. },
  7. };
  8. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. transform: {
  4. '\\.[jt]sx?$': 'babel-jest',
  5. '\\.css$': 'some-css-transformer',
  6. },
  7. };
  8. export default config;

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. 例如:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
  4. };
  5. export default config;

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.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. transformIgnorePatterns: [
  4. '<rootDir>/bower_components/',
  5. '<rootDir>/node_modules/',
  6. ],
  7. };
  8. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. transformIgnorePatterns: [
  4. '<rootDir>/bower_components/',
  5. '<rootDir>/node_modules/',
  6. ],
  7. };
  8. export default config;

配置 Jest - 图35tip

If you use pnpm and need to convert some packages under node_modules, you need to note that the packages in this folder (e.g. node_modules/package-a/) have been symlinked to the path under .pnpm (e.g. node_modules/.pnpm/package-a@x.x.x/node_modules/package-a/), so using <rootDir>/node_modules/(?!(package-a|@scope/pkg-b)/) directly will not be recognized, while is to use:

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. transformIgnorePatterns: [
  4. '<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
  5. /* if config file is under '~/packages/lib-a/' */
  6. `${path.join(
  7. __dirname,
  8. '../..',
  9. )}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
  10. /* or using relative pattern to match the second 'node_modules/' in 'node_modules/.pnpm/@scope+pkg-b@x.x.x/node_modules/@scope/pkg-b/' */
  11. 'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
  12. ],
  13. };
  14. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. transformIgnorePatterns: [
  4. '<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
  5. /* if config file is under '~/packages/lib-a/' */
  6. `${path.join(
  7. __dirname,
  8. '../..',
  9. )}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
  10. /* or using relative path to match the second 'node_modules/' in 'node_modules/.pnpm/@scope+pkg-b@x.x.x/node_modules/@scope/pkg-b/' */
  11. 'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
  12. ],
  13. };
  14. export default config;

It should be noted that the folder name of pnpm under .pnpm is the package name plus @ and version number, so writing / will not be recognized, but using @ can.

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, lodash, 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]

Default: false or true if there is only one test file to run

Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution.

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

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
  4. };
  5. export default config;

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:

配置 Jest - 图36info

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.

workerIdleMemoryLimit [number|string]

Default: undefined

Specifies the memory limit for workers before they are recycled and is primarily a work-around for this issue;

After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is Math.floor is used to turn it into an integer value:

  • <= 1 - The value is assumed to be a percentage of system memory. So 0.5 sets the memory limit of the worker to half of the total system memory
  • \> 1 - Assumed to be a fixed byte value. Because of the previous rule if you wanted a value of 1 byte (I don’t know why) you could use 1.1.
  • With units
    • 50% - As above, a percentage of total system memory
    • 100KB, 65MB, etc - With units to denote a fixed memory limit.
      • K / KB - Kilobytes (x1000)
      • KiB - Kibibytes (x1024)
      • M / MB - Megabytes
      • MiB - Mebibytes
      • G / GB - Gigabytes
      • GiB - Gibibytes

配置 Jest - 图37caution

Percentage based memory limit does not work on Linux CircleCI workers due to incorrect system memory being reported.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. workerIdleMemoryLimit: 0.2,
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. workerIdleMemoryLimit: 0.2,
  4. };
  5. export default config;

// [string]

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

package.json

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