配置 Jest
Jest 的理念是默认情况下可以很好地工作,但有时你只需要更多的配置能力。
¥The Jest philosophy is to work great by default, but sometimes you just need more configuration power.
建议在专用的 JavaScript、TypeScript 或 JSON 文件中定义配置。如果文件名为 jest.config.js|ts|mjs|cjs|json
,系统会自动发现该文件。你可以使用 --config
标志来传递文件的显式路径。
¥It is recommended to define the configuration in a dedicated JavaScript, TypeScript or JSON file. The file will be discovered automatically, if it is named jest.config.js|ts|mjs|cjs|json
. You can use --config
flag to pass an explicit path to the file.
请记住,生成的配置对象必须始终是 JSON 可序列化的。
¥Keep in mind that the resulting configuration object must always be JSON-serializable.
配置文件应该简单地导出一个对象:
¥The configuration file should simply export an object:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
verbose: true,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
verbose: true,
};
export default config;
或者返回一个对象的函数:
¥Or a function returning an object:
- JavaScript
- TypeScript
/** @returns {Promise<import('jest').Config>} */
module.exports = async () => {
return {
verbose: true,
};
};
import type {Config} from 'jest';
export default async (): Promise<Config> => {
return {
verbose: true,
};
};
配置也可以作为普通对象存储在 JSON 文件中:
¥The configuration also can be stored in a JSON file as a plain object:
{
"bail": 1,
"verbose": true
}
或者,可以通过项目的 package.json
中的 "jest"
键定义 Jest 的配置:
¥Alternatively Jest's configuration can be defined through the "jest"
key in the package.json
of your project:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
选项
¥Options
如果需要,你可以从 jest-config
检索 Jest 的默认值以扩展它们:
¥You can retrieve Jest's defaults from jest-config
to extend them if needed:
- JavaScript
- TypeScript
const {defaults} = require('jest-config');
/** @type {import('jest').Config} */
const config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts', 'cts'],
};
module.exports = config;
import type {Config} from 'jest';
import {defaults} from 'jest-config';
const config: Config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts'],
};
export default config;
automock
[boolean]bail
[number | boolean]cacheDirectory
[string]clearMocks
[boolean]collectCoverage
[boolean]collectCoverageFrom
[array]coverageDirectory
[string]coveragePathIgnorePatterns
[array<string>]coverageProvider
[string]coverageReporters
[array<string | [string, options]>]coverageThreshold
[object]dependencyExtractor
[string]displayName
[string, object]errorOnDeprecated
[boolean]extensionsToTreatAsEsm
[array<string>]fakeTimers
[object]forceCoverageMatch
[array<string>]globals
[object]globalSetup
[string]globalTeardown
[string]haste
[object]injectGlobals
[boolean]maxConcurrency
[number]maxWorkers
[number | string]moduleDirectories
[array<string>]moduleFileExtensions
[array<string>]moduleNameMapper
[object<string, string | array<string>>]modulePathIgnorePatterns
[array<string>]modulePaths
[array<string>]notify
[boolean]notifyMode
[string]openHandlesTimeout
[number]preset
[string]prettierPath
[string]projects
[array<string | ProjectConfig>]randomize
[boolean]reporters
[array<moduleName | [moduleName, options]>]resetMocks
[boolean]resetModules
[boolean]resolver
[string]restoreMocks
[boolean]rootDir
[string]roots
[array<string>]runner
[string]sandboxInjectedGlobals
[array<string>]setupFiles
[array]setupFilesAfterEnv
[array]showSeed
[boolean]slowTestThreshold
[number]snapshotFormat
[object]snapshotResolver
[string]snapshotSerializers
[array<string>]testEnvironment
[string]testEnvironmentOptions
[Object]testFailureExitCode
[number]testMatch
[array<string>]testPathIgnorePatterns
[array<string>]testRegex
[string | array<string>]testResultsProcessor
[string]testRunner
[string]testSequencer
[string]testTimeout
[number]transform
[object<string, pathToTransformer | [pathToTransformer, object]>]transformIgnorePatterns
[array<string>]unmockedModulePathPatterns
[array<string>]verbose
[boolean]watchPathIgnorePatterns
[array<string>]watchPlugins
[array<string | [string, Object]>]watchman
[boolean]workerIdleMemoryLimit
[number|string]//
[string]workerThreads
参考
¥Reference
automock
[boolean]
默认:false
¥Default: false
此选项告诉 Jest 测试中的所有导入模块都应该自动模拟。测试中使用的所有模块都将有一个替换实现,保留 API 表面。
¥This option tells Jest that all imported modules in your tests should be mocked automatically. All modules used in your tests will have a replacement implementation, keeping the API surface.
示例:
¥Example:
export default {
authorize: () => 'token',
isAuthorized: secret => secret === 'wizard',
};
import utils from '../utils';
test('if utils mocked automatically', () => {
// Public methods of `utils` are now mock functions
expect(utils.authorize.mock).toBeTruthy();
expect(utils.isAuthorized.mock).toBeTruthy();
// You can provide them with your own implementation
// or pass the expected return value
utils.authorize.mockReturnValue('mocked_token');
utils.isAuthorized.mockReturnValue(true);
expect(utils.authorize()).toBe('mocked_token');
expect(utils.isAuthorized('not_wizard')).toBeTruthy();
});
当你进行手动模拟时,节点模块会自动模拟(例如:__mocks__/lodash.js
)。更多信息 此处。
¥Node modules are automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js
). More info here.
Node.js 核心模块(如 fs
)默认情况下不会被模拟。它们可以被明确地模拟,比如 jest.mock('fs')
。
¥Node.js core modules, like fs
, are not mocked by default. They can be mocked explicitly, like jest.mock('fs')
.
bail
[number | boolean]
默认:0
¥Default: 0
默认情况下,Jest 运行所有测试并在完成后将所有错误生成到控制台中。此处可以使用 bail 配置选项让 Jest 在 n
次失败后停止运行测试。将保释设置为 true
与将保释设置为 1
相同。
¥By default, Jest runs all tests and produces all errors into the console upon completion. The bail config option can be used here to have Jest stop running tests after n
failures. Setting bail to true
is the same as setting bail to 1
.
cacheDirectory
[string]
默认:"/tmp/<path>"
¥Default: "/tmp/<path>"
Jest 应存储其缓存的依赖信息的目录。
¥The directory where Jest should store its cached dependency information.
Jest 尝试一次(预先)扫描你的依赖树并将其缓存,以缓解运行测试时需要发生的一些文件系统混乱。此配置选项允许你自定义 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. This config option lets you customize where Jest stores that cache data on disk.
clearMocks
[boolean]
默认:false
¥Default: false
每次测试前自动清除模拟调用、实例、上下文和结果。相当于每次测试前调用 jest.clearAllMocks()
。这不会删除可能已提供的任何模拟实现。
¥Automatically clear mock calls, instances, contexts and results before every test. Equivalent to calling jest.clearAllMocks()
before each test. This does not remove any mock implementation that may have been provided.
collectCoverage
[boolean]
默认:false
¥Default: false
指示执行测试时是否应收集覆盖率信息。由于这会使用覆盖率收集语句改进所有执行的文件,因此可能会显着减慢你的测试速度。
¥Indicates whether the coverage information should be collected while executing the test. Because this retrofits all executed files with coverage collection statements, it may significantly slow down your tests.
Jest 附带两个承保提供商:babel
(默认)和 v8
。有关详细信息,请参阅 coverageProvider
选项。
¥Jest ships with two coverage providers: babel
(default) and v8
. See the coverageProvider
option for more details.
babel
和 v8
覆盖率提供程序分别使用 /* istanbul ignore next */
和 /* c8 ignore next */
注释从覆盖率报告中排除行。有关更多信息,你可以查看 istanbuljs
文档 和 c8
文档。
¥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]
默认:undefined
¥Default: undefined
通配符模式 数组,指示应收集其覆盖范围信息的一组文件。如果文件与指定的 glob 模式匹配,即使该文件不存在测试并且测试套件中从不需要它,也会为其收集覆盖信息。
¥An array of glob patterns indicating a set of files for which coverage information should be collected. If a file matches the specified glob pattern, coverage information will be collected for it even if no tests exist for this file and it's never required in the test suite.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
export default config;
这将收集项目 rootDir
内所有文件的覆盖范围信息,但与 **/node_modules/**
或 **/vendor/**
匹配的文件除外。
¥This will collect coverage information for all the files inside the project's rootDir
, except the ones that match **/node_modules/**
or **/vendor/**
.
每个 glob 模式都按照它们在配置中指定的顺序应用。例如,["!**/__tests__/**", "**/*.js"]
不会排除 __tests__
,因为否定被第二个模式覆盖。为了使本例中的否定 glob 起作用,它必须位于 **/*.js
之后。
¥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
.
此选项要求将 collectCoverage
设置为 true
或使用 --coverage
调用 Jest。
¥This option requires collectCoverage
to be set to true
or Jest to be invoked with --coverage
.
Help:
如果你看到覆盖输出,例如...
¥If you are seeing coverage output such as...
=============================== Coverage summary ===============================
Statements : Unknown% ( 0/0 )
Branches : Unknown% ( 0/0 )
Functions : Unknown% ( 0/0 )
Lines : Unknown% ( 0/0 )
================================================================================
Jest: Coverage data for global was not found.
你的 glob 模式很可能与任何文件都不匹配。请参阅 micromatch 文档以确保你的 glob 兼容。
¥Most likely your glob patterns are not matching any files. Refer to the micromatch documentation to ensure your globs are compatible.
coverageDirectory
[string]
默认:undefined
¥Default: undefined
Jest 应输出其覆盖范围文件的目录。
¥The directory where Jest should output its coverage files.
coveragePathIgnorePatterns
[array<string>]
默认:["/node_modules/"]
¥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.
这些模式字符串与完整路径匹配。使用 <rootDir>
字符串标记包含项目根目录的路径,以防止项目意外忽略可能具有不同根目录的不同环境中的所有文件。示例:["<rootDir>/build/", "<rootDir>/node_modules/"]
。
¥These pattern strings match against the full path. Use the <rootDir>
string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/", "<rootDir>/node_modules/"]
.
coverageProvider
[string]
指示应使用哪个提供商来检测代码的覆盖范围。允许的值为 babel
(默认)或 v8
。
¥Indicates which provider should be used to instrument code for coverage. Allowed values are babel
(default) or v8
.
coverageReporters
[array<string | [string, options]>]
默认:["clover", "json", "lcov", "text"]
¥Default: ["clover", "json", "lcov", "text"]
Jest 在撰写报道报告时使用的报告器名称列表。任何 伊斯坦布尔报告器报 都可以使用。
¥A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used.
设置此选项会覆盖默认值。添加 "text"
或 "text-summary"
以在控制台输出中查看覆盖率摘要。
¥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
/** @type {import('jest').Config} */
const config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
export default config;
有关选项对象形状的更多信息,请参阅 类型定义 中的 CoverageReporterWithOptions
类型。
¥For more information about the options object shape refer to CoverageReporterWithOptions
type in the type definitions.
coverageThreshold
[object]
默认:undefined
¥Default: undefined
这将用于配置覆盖结果的最小阈值强制执行。阈值可以指定为 global
、glob 以及目录或文件路径。如果未达到阈值,Jest 就会失败。指定为正数的阈值被视为所需的最小百分比。指定为负数的阈值表示允许的未覆盖实体的最大数量。
¥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.
例如,使用以下配置,如果分支、行和函数覆盖率低于 80%,或者未覆盖的语句超过 10 个,则 jest 将会失败:
¥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
/** @type {import('jest').Config} */
const config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
export default config;
如果与 global
一起指定了 glob 或路径,则将从总体覆盖范围中减去匹配路径的覆盖数据,并且将独立应用阈值。glob 的阈值应用于与该 glob 匹配的所有文件。如果未找到路径指定的文件,则返回错误。
¥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
/** @type {import('jest').Config} */
const config = {
coverageThreshold: {
global: {
branches: 50,
functions: 50,
lines: 50,
statements: 50,
},
'./src/components/': {
branches: 40,
statements: 40,
},
'./src/reducers/**/*.js': {
statements: 90,
},
'./src/api/very-important-module.js': {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageThreshold: {
global: {
branches: 50,
functions: 50,
lines: 50,
statements: 50,
},
'./src/components/': {
branches: 40,
statements: 40,
},
'./src/reducers/**/*.js': {
statements: 90,
},
'./src/api/very-important-module.js': {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
};
export default config;
如果出现以下情况,Jest 就会失败:
¥Jest will fail if:
-
./src/components
目录的分支或语句覆盖率低于 40%。¥The
./src/components
directory has less than 40% branch or statement coverage. -
与
./src/reducers/**/*.js
glob 匹配的文件之一的语句覆盖率低于 90%。¥One of the files matching the
./src/reducers/**/*.js
glob has less than 90% statement coverage. -
./src/api/very-important-module.js
文件的覆盖率低于 100%。¥The
./src/api/very-important-module.js
file has less than 100% coverage. -
每个剩余文件的总覆盖率均低于 50% (
global
)。¥Every remaining file combined has less than 50% coverage (
global
).
dependencyExtractor
[string]
默认:undefined
¥Default: undefined
此选项允许使用自定义依赖提取器。它必须是一个导出具有 extract
函数的对象的节点模块。例如。:
¥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.:
const crypto = require('crypto');
const fs = require('fs');
module.exports = {
extract(code, filePath, defaultExtract) {
const deps = defaultExtract(code, filePath);
// Scan the file and add dependencies in `deps` (which is a `Set`)
return deps;
},
getCacheKey() {
return crypto
.createHash('md5')
.update(fs.readFileSync(__filename))
.digest('hex');
},
};
extract
函数应该返回一个可迭代对象(Array
、Set
等),并在代码中找到依赖。
¥The extract
function should return an iterable (Array
, Set
, etc.) with the dependencies found in the code.
该模块还可以包含 getCacheKey
函数来生成缓存密钥,以确定逻辑是否已更改以及依赖于它的任何缓存工件是否应被丢弃。
¥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]
默认:undefined
¥default: undefined
允许在测试运行时与测试一起打印标签。这在可能有许多 Jest 配置文件的多项目存储库中变得更加有用。这可以直观地告诉你测试属于哪个项目。
¥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
/** @type {import('jest').Config} */
const config = {
displayName: 'CLIENT',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: 'CLIENT',
};
export default config;
或者,可以传递具有属性 name
和 color
的对象。这允许自定义配置 displayName 的背景颜色。当其值为字符串时,displayName
默认为白色。Jest 使用 chalk
来提供颜色。因此,Jest 也支持 chalk
支持的所有有效颜色选项。
¥Alternatively, 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.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
export default config;
errorOnDeprecated
[boolean]
默认:false
¥Default: false
让调用已弃用的 API 抛出有用的错误消息。对于简化升级过程很有用。
¥Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.
extensionsToTreatAsEsm
[array<string>]
默认:[]
¥Default: []
Jest 将运行 .mjs
和 .js
文件,并将最近的 package.json
的 type
字段设置为 module
作为 ECMAScript 模块。如果你有任何其他应与原生 ESM 一起运行的文件,则需要在此处指定其文件扩展名。
¥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
/** @type {import('jest').Config} */
const config = {
extensionsToTreatAsEsm: ['.ts'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
extensionsToTreatAsEsm: ['.ts'],
};
export default config;
Jest 的 ESM 支持仍处于实验阶段,请参阅 其文档了解更多详细信息。
¥Jest's ESM support is still experimental, see its docs for more details.
fakeTimers
[object]
默认:{}
¥Default: {}
当一段代码设置了我们不想在测试中等待的长时间超时时,假计时器可能会很有用。有关更多详细信息,请参阅 假定时器指南 和 API 文档。
¥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.
此选项为所有测试提供假定时器的默认配置。在测试文件中调用 jest.useFakeTimers()
将使用这些选项,或者在传递配置对象时覆盖它们。例如,你可以告诉 Jest 保留 process.nextTick()
的原始实现并调整将运行的递归计时器的限制:
¥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
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
export default config;
// install fake timers for this file using the options from Jest configuration
jest.useFakeTimers();
test('increase the limit of recursive timers for this and following tests', () => {
jest.useFakeTimers({timerLimit: 5000});
// ...
});
你可以为 Jest 配置中的所有测试全局启用伪计时器,而不是在每个测试文件中包含 jest.useFakeTimers()
:
¥Instead of including jest.useFakeTimers()
in each test file, you can enable fake timers globally for all tests in your Jest configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
},
};
export default config;
配置选项:
¥Configuration options:
type FakeableAPI =
| 'Date'
| 'hrtime'
| 'nextTick'
| 'performance'
| 'queueMicrotask'
| 'requestAnimationFrame'
| 'cancelAnimationFrame'
| 'requestIdleCallback'
| 'cancelIdleCallback'
| 'setImmediate'
| 'clearImmediate'
| 'setInterval'
| 'clearInterval'
| 'setTimeout'
| 'clearTimeout';
type ModernFakeTimersConfig = {
/**
* If set to `true` all timers will be advanced automatically by 20 milliseconds
* every 20 milliseconds. A custom time delta may be provided by passing a number.
* The default is `false`.
*/
advanceTimers?: boolean | number;
/**
* List of names of APIs that should not be faked. The default is `[]`, meaning
* all APIs are faked.
*/
doNotFake?: Array<FakeableAPI>;
/** Whether fake timers should be enabled for all test files. The default is `false`. */
enableGlobally?: boolean;
/**
* Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.
* The default is `false`.
*/
legacyFakeTimers?: boolean;
/** Sets current system time to be used by fake timers, in milliseconds. The default is `Date.now()`. */
now?: number;
/** Maximum number of recursive timers that will be run. The default is `100_000` timers. */
timerLimit?: number;
};
由于某种原因,你可能必须使用假计时器的旧版实现。以下是全局启用它的方法(不支持其他选项):
¥For some reason you might have to use legacy implementation of fake timers. Here is how to enable it globally (additional options are not supported):
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
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.
例如,如果你在以 .t.js
扩展名命名的源文件中进行测试,如下所示:
¥For example, if you have tests in source files named with .t.js
extension as following:
export function sum(a, b) {
return a + b;
}
if (process.env.NODE_ENV === 'test') {
test('sum', () => {
expect(sum(1, 2)).toBe(3);
});
}
你可以通过设置 forceCoverageMatch
从这些文件中收集覆盖率。
¥You can collect coverage from those files with setting forceCoverageMatch
.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
forceCoverageMatch: ['**/*.t.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
forceCoverageMatch: ['**/*.t.js'],
};
export default config;
globals
[object]
默认:{}
¥Default: {}
一组需要在所有测试环境中可用的全局变量。
¥A set of global variables that need to be available in all test environments.
例如,以下命令将在所有测试环境中创建设置为 true
的全局 __DEV__
变量:
¥For example, the following would create a global __DEV__
variable set to true
in all test environments:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
globals: {
__DEV__: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
globals: {
__DEV__: true,
},
};
export default config;
如果你在此处指定全局引用值(例如对象或数组),并且某些代码在运行测试期间更改了该值,则该更改将不会在其他测试文件的测试运行中持续存在。此外,globals
对象必须是 json 可序列化的,因此它不能用于指定全局函数。为此,你应该使用 setupFiles
。
¥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]
默认:undefined
¥Default: undefined
此选项允许使用自定义全局设置模块,该模块必须导出函数(可以是同步或异步)。该函数将在所有测试套件之前触发一次,并将接收两个参数:Jest 的 globalConfig
和 projectConfig
。
¥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
.
仅当你从该项目运行至少一个测试时,才会触发项目中配置的全局设置模块(使用多项目运行器)。
¥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.
通过 globalSetup
定义的任何全局变量只能在 globalTeardown
中读取。你无法检索测试套件中此处定义的全局变量。
¥Any global variables that are defined through globalSetup
can only be read in globalTeardown
. You cannot retrieve globals defined here in your test suites.
虽然代码转换应用于链接的安装文件,但 Jest 不会转换 node_modules
中的任何代码。这是因为需要加载实际的转换器(例如 babel
或 typescript
)来执行转换。
¥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.
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
// Set reference to mongod in order to close the server during teardown.
globalThis.__MONGOD__ = mongod;
};
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
await globalThis.__MONGOD__.stop();
};
globalTeardown
[string]
默认:undefined
¥Default: undefined
此选项允许使用必须导出函数的自定义全局拆卸模块(可以是同步或异步)。该函数将在所有测试套件之后被触发一次,并且它将接收两个参数:Jest 的 globalConfig
和 projectConfig
。
¥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
.
仅当你从该项目运行至少一个测试时,才会触发项目中配置的全局拆卸模块(使用多项目运行器)。
¥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.
关于 node_modules
转换的与 globalSetup
转换相同的警告也适用于 globalTeardown
。
¥The same caveat concerning transformation of node_modules
as for globalSetup
applies to globalTeardown
.
haste
[object]
默认:undefined
¥Default: undefined
这将用于配置 jest-haste-map
(Jest 的内部文件爬虫/缓存系统)的行为。支持以下选项:
¥This will be used to configure the behavior of jest-haste-map
, Jest's internal file crawler/cache system. The following options are supported:
type HasteConfig = {
/** Whether to hash files using SHA-1. */
computeSha1?: boolean;
/** The platform to use as the default, e.g. 'ios'. */
defaultPlatform?: string | null;
/** Force use of Node's `fs` APIs rather than shelling out to `find` */
forceNodeFilesystemAPI?: boolean;
/**
* Whether to follow symlinks when crawling for files.
* This options cannot be used in projects which use watchman.
* Projects with `watchman` set to true will error if this option is set to true.
*/
enableSymlinks?: boolean;
/** Path to a custom implementation of Haste. */
hasteImplModulePath?: string;
/** All platforms to target, e.g ['ios', 'android']. */
platforms?: Array<string>;
/** Whether to throw on error on module collision. */
throwOnModuleCollision?: boolean;
/** Custom HasteMap module */
hasteMapModulePath?: string;
/** Whether to retain all files, allowing e.g. search for tests in `node_modules`. */
retainAllFiles?: boolean;
};
injectGlobals
[boolean]
默认:true
¥Default: true
将 Jest 的全局变量(expect
、test
、describe
、beforeEach
等)插入全局环境中。如果将其设置为 false
,则应从 @jest/globals
导入,例如
¥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.
import {expect, jest, test} from '@jest/globals';
jest.useFakeTimers();
test('some test', () => {
expect(Date.now()).toBe(0);
});
仅使用默认的 jest-circus
测试运行程序才支持此选项。
¥This option is only supported using the default jest-circus
test runner.
maxConcurrency
[number]
默认:5
¥Default: 5
使用 test.concurrent
时限制允许同时运行的测试数量的数字。一旦插槽被释放,任何超过此限制的测试都将排队并执行。
¥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]
指定工作池为运行测试而生成的最大工作进程数量。在单运行模式下,这默认为计算机上可用的核心数减去主线程的一数。在监视模式下,这默认为机器上可用内核的一半,以确保 Jest 不引人注目并且不会让你的机器停止运行。在 CI 等资源有限的环境中调整此设置可能很有用,但默认值应该足以满足大多数用例。
¥Specifies the maximum number of workers the worker-pool will spawn for running tests. 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.
对于具有可用可变 CPU 的环境,你可以使用基于百分比的配置:
¥For environments with variable CPUs available, you can use percentage based configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
maxWorkers: '50%',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
maxWorkers: '50%',
};
export default config;
moduleDirectories
[array<string>]
默认:["node_modules"]
¥Default: ["node_modules"]
要从所需模块的位置向上递归搜索的目录名称数组。如果你仍希望搜索 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:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
export default config;
不鼓励将 '.'
用作 moduleDirectories
之一,因为这会阻止范围包(例如 @emotion/react
)访问具有相同子目录名称(react
)的包。详细信息请参见 这个问题。在大多数情况下,最好使用 moduleNameMapper 配置。
¥It is discouraged to use '.'
as one of the moduleDirectories
, because this prevents scoped packages such as @emotion/react
from accessing packages with the same subdirectory name (react
). See this issue for more details. In most cases, it is preferable to use the moduleNameMapper configuration instead.
moduleFileExtensions
[array<string>]
默认:["js", "mjs", "cjs", "jsx", "ts", "tsx", "json", "node"]
¥Default: ["js", "mjs", "cjs", "jsx", "ts", "tsx", "json", "node"]
你的模块使用的文件扩展名数组。如果你需要不指定文件扩展名的模块,这些是 Jest 将从左到右的顺序查找的扩展名。
¥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.
我们建议将项目中最常用的扩展放在左侧,因此如果你使用 TypeScript,你可能需要考虑将 "ts" 和/或 "tsx" 移动到数组的开头。
¥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>>]
默认:null
¥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.
如果要使用文件路径,请使用 <rootDir>
字符串标记来引用 rootDir
值。
¥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
/** @type {import('jest').Config} */
const config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
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.
如果你提供没有边界 ^$
的模块名称,可能会导致难以发现错误。例如。relay
将替换名称中包含 relay
作为子字符串的所有模块:relay
、react-relay
和 graphql-relay
将全部指向你的存根。
¥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: []
与所有模块路径相匹配的正则表达式模式字符串数组,在这些路径被模块加载器视为 'visible' 之前。如果给定模块的路径与任何模式匹配,则它在测试环境中将不支持 require()
。
¥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.
这些模式字符串与完整路径匹配。使用 <rootDir>
字符串标记包含项目根目录的路径,以防止项目意外忽略可能具有不同根目录的不同环境中的所有文件。
¥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
/** @type {import('jest').Config} */
const config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
export default config;
modulePaths
[array<string>]
默认:[]
¥Default: []
设置 NODE_PATH
环境变量的替代 API,modulePaths
是解析模块时要搜索的其他位置的绝对路径数组。使用 <rootDir>
字符串标记包含项目根目录的路径。
¥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
/** @type {import('jest').Config} */
const config = {
modulePaths: ['<rootDir>/app/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
modulePaths: ['<rootDir>/app/'],
};
export default config;
notify
[boolean]
默认:false
¥Default: false
激活测试结果的原生操作系统通知。要显示通知 Jest 需要 node-notifier
软件包,必须另外安装:
¥Activates native OS notifications for test results. To display the notifications Jest needs node-notifier
package, which must be installed additionally:
- npm
- Yarn
- pnpm
npm install --save-dev node-notifier
yarn add --dev node-notifier
pnpm add --save-dev node-notifier
在 macOS 上,请记住在“系统偏好设置”>“通知和焦点”下允许来自 terminal-notifier
的通知。
¥On macOS, remember to allow notifications from terminal-notifier
under System Preferences > Notifications & Focus.
在 Windows 上,node-notifier
在第一次使用时创建一个新的开始菜单条目,并且不显示通知。通知将在后续运行中正确显示。
¥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]
默认:failure-change
¥Default: failure-change
指定通知模式。需要 notify: true
。
¥Specifies notification mode. Requires notify: true
.
模式
¥Modes
-
always
:始终发送通知。¥
always
: always send a notification. -
failure
:当测试失败时发送通知。¥
failure
: send a notification when tests fail. -
success
:测试通过时发送通知。¥
success
: send a notification when tests pass. -
change
:当状态改变时发送通知。¥
change
: send a notification when the status changed. -
success-change
:当测试通过时发送通知或当测试失败时发送一次通知。¥
success-change
: send a notification when tests pass or once when it fails. -
failure-change
:当测试失败时发送通知或当测试通过时发送一次通知。¥
failure-change
: send a notification when tests fail or once when it passes.
openHandlesTimeout
[number]
默认:1000
¥Default: 1000
打印一条警告,指示如果 Jest 在完成后的毫秒数内未完全退出,则可能存在打开的句柄。使用 0
禁用警告。
¥Print a warning indicating that there are probable open handles if Jest does not exit cleanly this number of milliseconds after it completes. Use 0
to disable the warning.
preset
[string]
默认:undefined
¥Default: undefined
用作 Jest 配置基础的预设。预设应指向根目录下有 jest-preset.json
、jest-preset.js
、jest-preset.cjs
或 jest-preset.mjs
文件的 npm 模块。
¥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.
例如,该预设 foo-bar/jest-preset.js
将配置如下:
¥For example, this preset foo-bar/jest-preset.js
will be configured as follows:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
preset: 'foo-bar',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
preset: 'foo-bar',
};
export default config;
预设也可能与文件系统路径相关:
¥Presets may also be relative to filesystem paths:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
preset: './node_modules/foo-bar/jest-preset.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
preset: './node_modules/foo-bar/jest-preset.js',
};
export default config;
prettierPath
[string]
默认:'prettier'
¥Default: 'prettier'
设置用于更新内联快照的 prettier
节点模块的路径。
¥Sets the path to the prettier
node module used to update inline snapshots.
Prettier version 3 is not supported!
如果不需要,你可以在配置中传递 prettierPath: null
以禁用 Prettier,或者仅将 Prettier v2 用于 Jest。
¥You can either pass prettierPath: null
in your config to disable using prettier if you don't need it, or use v2 of Prettier solely for Jest.
{
"devDependencies": {
"prettier-2": "npm:prettier@^2"
}
}
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
prettierPath: require.resolve('prettier-2'),
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
prettierPath: require.resolve('prettier-2'),
};
export default config;
我们希望在 Jest 的未来版本中无缝支持 Prettier v3。请参阅 此 跟踪问题。
¥We hope to support Prettier v3 seamlessly out of the box in a future version of Jest. See this tracking issue.
projects
[array<string | ProjectConfig>]
默认:undefined
¥Default: undefined
当 projects
配置提供路径数组或 glob 模式时,Jest 将同时在所有指定项目中运行测试。这对于单一存储库或同时处理多个项目时非常有用。
¥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
/** @type {import('jest').Config} */
const config = {
projects: ['<rootDir>', '<rootDir>/examples/*'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
projects: ['<rootDir>', '<rootDir>/examples/*'],
};
export default config;
此示例配置将在根目录以及示例目录中的每个文件夹中运行 Jest。你可以在同一个 Jest 实例中运行无限数量的项目。
¥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.
项目功能还可用于运行多个配置或多个 runners。为此,你可以传递配置对象数组。例如,要在同一 Jest 调用中运行测试和 ESLint(通过 jest-runner-eslint):
¥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
/** @type {import('jest').Config} */
const config = {
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
};
export default config;
使用多项目运行器时,建议为每个项目添加 displayName
。这将在其测试旁边显示项目的 displayName
。
¥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.
启用 projects
选项后,Jest 将在测试运行期间将根级配置选项复制到每个单独的子配置,并在子上下文中解析其值。这意味着像 <rootDir>
这样的字符串标记将指向子级的根目录,即使它们是在根级配置中定义的。
¥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.
randomize
[boolean]
默认:false
¥Default: false
相当于 --randomize
标志,用于随机化文件中测试的顺序。
¥The equivalent of the --randomize
flag to randomize the order of the tests in a file.
reporters
[array<moduleName | [moduleName, options]>]
默认:undefined
¥Default: undefined
使用此配置选项将报告器添加到 Jest。它必须是报告器名称列表,可以使用元组形式将其他选项传递给报告器:
¥Use this configuration option to add reporters to Jest. It must be a list of reporter names, additional options can be passed to a reporter using the tuple form:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
};
export default config;
默认报告者
¥Default Reporter
如果指定了自定义报告器,则默认的 Jest 报告器将被覆盖。如果你想保留它,则必须将 'default'
作为报告器名称传递:
¥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
/** @type {import('jest').Config} */
const config = {
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
};
export default config;
GitHub Actions 报告器
¥GitHub Actions Reporter
如果包含在列表中,内置的 GitHub Actions Reporter 将使用测试失败消息注释更改的文件,并使用 github 组功能(如果与 'silent: false'
一起使用)打印日志,以便于导航。请注意,在这种情况下不应使用 'default'
,因为 'github-actions'
已经会处理该问题,因此请记住还包括 'summary'
。如果你只想将其用于注释,只需仅保留报告器而不带选项,因为 'silent'
的默认值为 'true'
:
¥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
/** @type {import('jest').Config} */
const config = {
reporters: [['github-actions', {silent: false}], 'summary'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [['github-actions', {silent: false}], 'summary'],
};
export default config;
摘要报告器
¥Summary Reporter
摘要报告器打印出所有测试的摘要。它是默认报告器的一部分,因此如果 'default'
包含在列表中,它将被启用。例如,你可能想将其用作独立报告器而不是默认报告器,或与 沉默的报告器 一起使用:
¥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
/** @type {import('jest').Config} */
const config = {
reporters: ['jest-silent-reporter', 'summary'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: ['jest-silent-reporter', 'summary'],
};
export default config;
summary
报告器接受选项。由于它包含在 default
报告器中,你也可以在其中传递选项。
¥The summary
reporter accepts options. Since it is included in the default
reporter you may also pass the options there.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [['default', {summaryThreshold: 10}]],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [['default', {summaryThreshold: 10}]],
};
export default config;
summaryThreshold
选项的行为方式如下,如果测试套件的总数超过此阈值,则在执行所有测试后将打印所有失败测试的详细摘要。默认为 20
。
¥The summaryThreshold
option behaves in the following way, if the total number of test suites surpasses this threshold, a detailed summary of all failed tests will be printed after executing all the tests. It defaults to 20
.
定制报告器
¥Custom Reporters
渴求报告器吗?看看来自 Awesome Jest 的 很棒的报告器 长列表。
¥Hungry for reporters? Take a look at long list of awesome reporters from Awesome Jest.
自定义报告器模块必须导出一个采用 globalConfig
、reporterOptions
和 reporterContext
作为构造函数参数的类:
¥Custom reporter module must export a class that takes globalConfig
, reporterOptions
and reporterContext
as constructor arguments:
class CustomReporter {
constructor(globalConfig, reporterOptions, reporterContext) {
this._globalConfig = globalConfig;
this._options = reporterOptions;
this._context = reporterContext;
}
onRunComplete(testContexts, results) {
console.log('Custom reporter output:');
console.log('global config:', this._globalConfig);
console.log('options for this reporter from Jest config:', this._options);
console.log('reporter context passed from test scheduler:', this._context);
}
// Optionally, reporters can force Jest to exit with non zero code by returning
// an `Error` from `getLastError()` method.
getLastError() {
if (this._shouldFail) {
return new Error('Custom error reported!');
}
}
}
module.exports = CustomReporter;
有关钩子和参数类型的完整列表,请参阅 包/jest-reporters/src/types.ts 中的 Reporter
接口。
¥For the full list of hooks and argument types see the Reporter
interface in packages/jest-reporters/src/types.ts.
resetMocks
[boolean]
默认:false
¥Default: false
每次测试前自动重置模拟状态。相当于每次测试前调用 jest.resetAllMocks()
。这将导致任何模拟的假实现被删除,但不会恢复其初始实现。
¥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
¥Default: false
默认情况下,每个测试文件都有自己独立的模块注册表。启用 resetModules
更进一步,在运行每个单独的测试之前重置模块注册表。这对于隔离每个测试的模块很有用,这样本地模块状态就不会在测试之间发生冲突。这可以使用 jest.resetModules()
以编程方式完成。
¥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]
默认:undefined
¥Default: undefined
此选项允许使用自定义解析器。该解析器必须是导出以下任一内容的模块:
¥This option allows the use of a custom resolver. This resolver must be a module that exports either:
-
一个函数,期望一个字符串作为要解析的路径的第一个参数,一个选项对象作为第二个参数。该函数应该返回应解析的模块的路径,或者如果找不到模块则抛出错误。或者
¥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
-
包含
async
和/或sync
属性的对象。sync
属性应该是具有上述形状的函数,async
属性也应该是接受相同参数的函数,但返回一个 Promise,该 Promise 使用模块路径解析或因错误而拒绝。¥an object containing
async
and/orsync
properties. Thesync
property should be a function with the shape explained above, and theasync
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:
type ResolverOptions = {
/** Directory to begin resolving from. */
basedir: string;
/** List of export conditions. */
conditions?: Array<string>;
/** Instance of default resolver. */
defaultResolver: (path: string, options: ResolverOptions) => string;
/** List of file extensions to search in order. */
extensions?: Array<string>;
/** List of directory names to be looked up for modules recursively. */
moduleDirectory?: Array<string>;
/** List of `require.paths` to use if nothing is found in `node_modules`. */
paths?: Array<string>;
/** Allows transforming parsed `package.json` contents. */
packageFilter?: (pkg: PackageJSON, file: string, dir: string) => PackageJSON;
/** Allows transforms a path within a package. */
pathFilter?: (pkg: PackageJSON, path: string, relativePath: string) => string;
/** Current root directory. */
rootDir?: string;
};
作为选项传递的 defaultResolver
是 Jest 默认解析器,在你编写自定义解析器时可能会很有用。它采用与你的自定义同步参数相同的参数,例如 (path, options)
并返回一个字符串或抛出异常。
¥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"
场,你可以使用以下解析器:
¥For example, if you want to respect Browserify's "browser"
field, you can use the following resolver:
const browserResolve = require('browser-resolve');
module.exports = browserResolve.sync;
并将其添加到 Jest 配置中:
¥And add it to Jest configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
resolver: '<rootDir>/resolver.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
resolver: '<rootDir>/resolver.js',
};
export default config;
通过组合 defaultResolver
和 packageFilter
,我们可以实现 package.json
"pre-processor",它允许我们更改默认解析器解析模块的方式。例如,假设我们想要使用字段 "module"
(如果存在),否则回退到 "main"
:
¥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"
:
module.exports = (path, options) => {
// Call the defaultResolver, so we leverage its cache, error handling, etc.
return options.defaultResolver(path, {
...options,
// Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
packageFilter: pkg => {
return {
...pkg,
// Alter the value of `main` before resolving the package
main: pkg.module || pkg.main,
};
},
});
};
restoreMocks
[boolean]
默认:false
¥Default: false
在每次测试之前自动恢复模拟状态和实现。相当于每次测试前调用 jest.restoreAllMocks()
。这将导致任何模拟的假实现被删除并恢复其初始实现。
¥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]
默认:包含 Jest 配置文件 或 package.json
或 pwd
的目录的根目录(如果未找到 package.json
)
¥Default: The root of the directory containing your Jest config file or the package.json
or the pwd
if no package.json
is found
Jest 应扫描其中的测试和模块的根目录。如果你将 Jest 配置放入 package.json
中并希望根目录成为存储库的根目录,则此配置参数的值将默认为 package.json
的目录。
¥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
.
通常,你需要将其设置为 'src'
或 'lib'
,对应于代码在存储库中的存储位置。
¥Oftentimes, you'll want to set this to 'src'
or 'lib'
, corresponding to where in your repository the code is stored.
在任何其他基于路径的配置设置中使用 '<rootDir>'
作为字符串标记将引用该值。例如,如果你希望 setupFiles
条目指向项目根目录下的 some-setup.js
文件,请将其值设置为:'<rootDir>/some-setup.js'
。
¥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>]
默认:["<rootDir>"]
¥Default: ["<rootDir>"]
Jest 用于搜索文件的目录路径列表。
¥A list of paths to directories that Jest should use to search for files in.
有时你只希望 Jest 在单个子目录中搜索(例如存储库中有 src/
目录的情况),但阻止它访问存储库的其余部分。
¥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.
虽然 rootDir
主要用作在其他配置选项中重复使用的令牌,但 roots
被 Jest 内部用来定位测试文件和源文件。这也适用于从 node_modules
搜索模块的手动模拟(__mocks__
将需要位于 roots
之一)。
¥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
).
默认情况下,roots
有一个条目 <rootDir>
,但在某些情况下你可能希望在一个项目中拥有多个根,例如 roots: ["<rootDir>/src/", "<rootDir>/tests/"]
。
¥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]
默认:"jest-runner"
¥Default: "jest-runner"
此选项允许你使用自定义运行程序而不是 Jest 的默认测试运行程序。运行器的例子包括:
¥This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include:
runner
属性值可以省略包名的 jest-runner-
前缀。
¥The runner
property value can omit the jest-runner-
prefix of the package name.
要编写测试运行程序,请导出一个类,该类在构造函数中接受 globalConfig
,并具有带有签名的 runTests
方法:
¥To write a test-runner, export a class with which accepts globalConfig
in the constructor, and has a runTests
method with the signature:
async function runTests(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
options: TestRunnerOptions,
): Promise<void>;
如果你需要限制测试运行程序仅以串行方式运行而不是并行执行,你的类应该将属性 isSerial
设置为 true
。
¥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 28 中的 extraGlobals
重命名。
¥Renamed from extraGlobals
in Jest 28.
默认:undefined
¥Default: undefined
测试文件在 vm 内运行,这会减慢对全局上下文属性(例如 Math
)的调用。使用此选项,你可以指定要在虚拟机内定义的额外属性,以加快查找速度。
¥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.
例如,如果你的测试经常调用 Math
,则可以通过设置 sandboxInjectedGlobals
来通过它。
¥For example, if your tests call Math
often, you can pass it by setting sandboxInjectedGlobals
.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
sandboxInjectedGlobals: ['Math'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
sandboxInjectedGlobals: ['Math'],
};
export default config;
如果你使用 原生 ESM,则此选项无效。
¥This option has no effect if you use native ESM.
setupFiles
[array]
默认:[]
¥Default: []
运行某些代码以配置或设置测试环境的模块的路径列表。每个 setupFile 将在每个测试文件中运行一次。由于每个测试都在自己的环境中运行,因此这些脚本将在执行 setupFilesAfterEnv
之前和测试代码本身之前在测试环境中执行。
¥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.
如果你的安装脚本是 CJS 模块,它可能会导出异步函数。Jest 将调用该函数并等待其结果。这对于异步获取一些数据可能很有用。如果文件是 ESM 模块,只需使用顶层 await 即可获得相同的结果。
¥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: []
模块的路径列表,这些模块在执行套件中的每个测试文件之前运行一些代码来配置或设置测试框架。由于 setupFiles
在测试框架安装到环境中之前执行,因此此脚本文件为你提供了在测试框架安装到环境中之后但在测试代码本身之前立即运行某些代码的机会。
¥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.
换句话说,setupFilesAfterEnv
模块适用于每个测试文件中重复的代码。安装测试框架后,可以在模块中访问 Jest globals、jest
对象 和 expect
。例如,你可以从 jest-extended
库添加额外的匹配器或调用 设置和拆卸 钩子:
¥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:
const matchers = require('jest-extended');
expect.extend(matchers);
afterEach(() => {
jest.useRealTimers();
});
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
};
export default config;
showSeed
[boolean]
默认:false
¥Default: false
相当于 --showSeed
标志,用于在测试报告摘要中打印种子。
¥The equivalent of the --showSeed
flag to print the seed in the test report summary.
slowTestThreshold
[number]
默认:5
¥Default: 5
经过多少秒后,测试被视为慢速并在结果中报告为慢速。
¥The number of seconds after which a test is considered as slow and reported as such in the results.
snapshotFormat
[object]
默认:{escapeString: false, printBasicPrototype: false}
¥Default: {escapeString: false, printBasicPrototype: false}
允许覆盖 格式漂亮的自述文件 中记录的特定快照格式选项,但 compareKeys
和 plugins
除外。例如,此配置将使快照格式化程序不打印 "目的" 和 "数组" 的前缀:
¥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
/** @type {import('jest').Config} */
const config = {
snapshotFormat: {
printBasicPrototype: false,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
snapshotFormat: {
printBasicPrototype: false,
},
};
export default config;
test('does not show prototypes for object and array inline', () => {
const object = {
array: [{hello: 'Danger'}],
};
expect(object).toMatchInlineSnapshot(`
{
"array": [
{
"hello": "Danger",
},
],
}
`);
});
snapshotResolver
[string]
默认:undefined
¥Default: undefined
可以解析 test<->snapshot 路径的模块路径。此配置选项允许你自定义 Jest 在磁盘上存储快照文件的位置。
¥The path to a module that can resolve test<->snapshot path. This config option lets you customize where Jest stores snapshot files on disk.
module.exports = {
// resolves from test to snapshot path
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath.replace('__tests__', '__snapshots__') + snapshotExtension,
// resolves from snapshot to test path
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath
.replace('__snapshots__', '__tests__')
.slice(0, -snapshotExtension.length),
// Example test path, used for preflight consistency check of the implementation above
testPathForConsistencyCheck: 'some/__tests__/example.test.js',
};
snapshotSerializers
[array<string>]
默认:[]
¥Default: []
Jest 用于快照测试的快照序列化器模块的路径列表。
¥A list of paths to snapshot serializer modules Jest should use for snapshot testing.
Jest 具有用于内置 JavaScript 类型、HTML 元素 (Jest 20.0.0+)、ImmutableJS (Jest 20.0.0+) 和 React 元素的默认序列化器。请参阅 快照测试教程 了解更多信息。
¥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.
module.exports = {
serialize(val, config, indentation, depth, refs, printer) {
return `Pretty foo: ${printer(val.foo)}`;
},
test(val) {
return val && Object.prototype.hasOwnProperty.call(val, 'foo');
},
};
printer
是一个使用现有插件序列化值的函数。
¥printer
is a function that serializes a value using existing plugins.
将 custom-serializer
添加到你的 Jest 配置中:
¥Add custom-serializer
to your Jest configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
snapshotSerializers: ['path/to/custom-serializer.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
snapshotSerializers: ['path/to/custom-serializer.js'],
};
export default config;
最后测试如下:
¥Finally tests would look as follows:
test(() => {
const bar = {
foo: {
x: 1,
y: 2,
},
};
expect(bar).toMatchSnapshot();
});
渲染快照:
¥Rendered snapshot:
Pretty foo: Object {
"x": 1,
"y": 2,
}
要使依赖显式而不是隐式,你可以调用 expect.addSnapshotSerializer
为单个测试文件添加模块,而不是在 Jest 配置中将其路径添加到 snapshotSerializers
。
¥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.
有关序列化器 API 的更多信息,请参阅 此处。
¥More about serializers API can be found here.
testEnvironment
[string]
默认:"node"
¥Default: "node"
将用于测试的测试环境。Jest 中的默认环境是 Node.js 环境。如果你正在构建 Web 应用,则可以通过 jsdom
使用类似浏览器的环境。
¥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.
通过在文件顶部添加 @jest-environment
文档块,你可以指定用于该文件中所有测试的另一个环境:
¥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:
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div');
expect(element).not.toBeNull();
});
你可以创建自己的模块,用于设置测试环境。该模块必须导出具有 setup
、teardown
和 getVmContext
方法的类。你还可以通过将变量分配给 this.global
对象来将变量从该模块传递到你的测试套件 - 这将使它们在你的测试套件中作为全局变量可用。构造函数传递 globalConfig
和 projectConfig
作为其第一个参数,testEnvironmentContext
作为其第二个参数。
¥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.
该类可以选择公开一个异步 handleTestEvent
方法来绑定到 jest-circus
触发的事件。通常,jest-circus
测试运行程序会暂停,直到 handleTestEvent
返回的 promise 得到履行,但以下事件除外:start_describe_definition
、finish_describe_definition
、add_hook
、add_test
或 error
(有关最新列表,你可以查看 类型定义中的 SyncEvent 类型)。这是由向后兼容性原因和 process.on('unhandledRejection', callback)
签名引起的,但这对于大多数用例来说通常不应该成为问题。
¥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.
测试文件中的任何 docblock 编译指示都将传递给环境构造函数,并可用于每个测试配置。如果该编译指示没有值,它将出现在对象中,并将其值设置为空字符串。如果该编译指示不存在,则它不会出现在对象中。
¥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.
要将此类用作你的自定义环境,请通过其在项目中的完整路径来引用它。例如,如果你的类存储在项目的某个子文件夹中的 my-custom-environment.js
中,则注释可能如下所示:
¥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:
/**
* @jest-environment ./src/test/my-custom-environment
*/
测试环境是沙盒的。每个测试套件将在自己的测试环境中触发设置/拆卸。
¥TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.
示例:
¥Example:
// my-custom-environment
const NodeEnvironment = require('jest-environment-node').TestEnvironment;
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
console.log(config.globalConfig);
console.log(config.projectConfig);
this.testPath = context.testPath;
this.docblockPragmas = context.docblockPragmas;
}
async setup() {
await super.setup();
await someSetupTasks(this.testPath);
this.global.someGlobalObject = createGlobalObject();
// Will trigger if docblock contains @my-custom-pragma my-pragma-value
if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
// ...
}
}
async teardown() {
this.global.someGlobalObject = destroyGlobalObject();
await someTeardownTasks();
await super.teardown();
}
getVmContext() {
return super.getVmContext();
}
async handleTestEvent(event, state) {
if (event.name === 'test_start') {
// ...
}
}
}
module.exports = CustomEnvironment;
// my-test-suite
/**
* @jest-environment ./my-custom-environment
*/
let someGlobalObject;
beforeAll(() => {
someGlobalObject = globalThis.someGlobalObject;
});
testEnvironmentOptions
[Object]
默认:{}
¥Default: {}
将传递给 testEnvironment
的测试环境选项。相关选项取决于环境。
¥Test environment options that will be passed to the testEnvironment
. The relevant options depend on the environment.
例如,你可以覆盖传递给 jsdom
的选项:
¥For example, you can override options passed to jsdom
:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
html: '<html lang="zh-cmn-Hant"></html>',
url: 'https://jest.nodejs.cn/',
userAgent: 'Agent/007',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
html: '<html lang="zh-cmn-Hant"></html>',
url: 'https://jest.nodejs.cn/',
userAgent: 'Agent/007',
},
};
export default config;
jest-environment-jsdom
和 jest-environment-node
都允许指定 customExportConditions
,这允许你控制从 exports
加载到 package.json
的库版本。jest-environment-jsdom
默认为 ['browser']
。jest-environment-node
默认为 ['node', 'node-addons']
。
¥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']
.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['react-native'],
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['react-native'],
},
};
export default config;
这些选项也可以在文档块中传递,类似于 testEnvironment
。带选项的字符串必须可由 JSON.parse
解析:
¥These options can also be passed in a docblock, similar to testEnvironment
. The string with options must be parseable by JSON.parse
:
/**
* @jest-environment jsdom
* @jest-environment-options {"url": "https://jest.nodejs.cn/"}
*/
test('use jsdom and set the URL in this test file', () => {
expect(window.location.href).toBe('https://jest.nodejs.cn/');
});
testFailureExitCode
[number]
默认:1
¥Default: 1
测试失败时返回退出代码 Jest。
¥The exit code Jest returns on test failure.
在出现 Jest 错误(例如无效配置)的情况下,这不会更改退出代码。
¥This does not change the exit code in the case of Jest errors (e.g. invalid configuration).
testMatch
[array<string>]
(默认:[ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
)
¥(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
)
Jest 用于检测测试文件的 glob 模式。默认情况下,它会查找 __tests__
文件夹内的 .js
、.jsx
、.ts
和 .tsx
文件,以及任何带有 .test
或 .spec
后缀的文件(例如 Component.test.js
或 Component.spec.js
)。它还会查找名为 test.js
或 spec.js
的文件。
¥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
.
有关你可以指定的模式的详细信息,请参阅 micromatch 包。
¥See the micromatch package for details of the patterns you can specify.
另请参见 testRegex
[string | array<string>],但请注意你不能同时指定这两个选项。
¥See also testRegex
[string | array<string>], but note that you cannot specify both options.
每个 glob 模式都按照它们在配置中指定的顺序应用。例如,["!**/__fixtures__/**", "**/__tests__/**/*.js"]
不会排除 __fixtures__
,因为否定被第二个模式覆盖。为了使本例中的否定 glob 起作用,它必须位于 **/__tests__/**/*.js
之后。
¥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>]
默认:["/node_modules/"]
¥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.
这些模式字符串与完整路径匹配。使用 <rootDir>
字符串标记包含项目根目录的路径,以防止项目意外忽略可能具有不同根目录的不同环境中的所有文件。示例:["<rootDir>/build/", "<rootDir>/node_modules/"]
。
¥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>]
默认:(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
¥Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
Jest 用于检测测试文件的一个或多个模式。默认情况下,它会查找 __tests__
文件夹内的 .js
、.jsx
、.ts
和 .tsx
文件,以及任何带有 .test
或 .spec
后缀的文件(例如 Component.test.js
或 Component.spec.js
)。它还会查找名为 test.js
或 spec.js
的文件。另请参见 testMatch
[array<string>],但请注意你不能同时指定这两个选项。
¥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:
├── __tests__
│ └── component.spec.js # test
│ └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test
testRegex
将尝试使用绝对文件路径检测测试文件,因此,拥有与其名称匹配的文件夹将运行所有文件作为测试。
¥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]
默认:undefined
¥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:
{
"success": boolean,
"startTime": epoch,
"numTotalTestSuites": number,
"numPassedTestSuites": number,
"numFailedTestSuites": number,
"numRuntimeErrorTestSuites": number,
"numTotalTests": number,
"numPassedTests": number,
"numFailedTests": number,
"numPendingTests": number,
"numTodoTests": number,
"openHandles": Array<Error>,
"testResults": [{
"numFailingTests": number,
"numPassingTests": number,
"numPendingTests": number,
"testResults": [{
"title": string (message in it block),
"status": "failed" | "pending" | "passed",
"ancestorTitles": [string (message in describe blocks)],
"failureMessages": [string],
"numPassingAsserts": number,
"location": {
"column": number,
"line": number
},
"duration": number | null
},
...
],
"perfStats": {
"start": epoch,
"end": epoch
},
"testFilePath": absolute path to test file,
"coverage": {}
},
"testExecError:" (exists if there was a top-level failure) {
"message": string
"stack": string
}
...
]
}
testResultsProcessor
和 reporters
彼此非常相似。一个区别是测试结果处理器仅在所有测试完成后才会被调用。而报告者有能力在单个测试和/或测试套件完成后接收测试结果。
¥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]
默认:jest-circus/runner
¥Default: jest-circus/runner
此选项允许使用自定义测试运行程序。默认为 jest-circus
。可以通过指定测试运行器实现的路径来提供自定义测试运行器。
¥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:
function testRunner(
globalConfig: GlobalConfig,
config: ProjectConfig,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
此类函数的示例可以在我们的默认 jasmine2 测试运行程序包.h 中找到。
¥An example of such function can be found in our default jasmine2 test runner package.
testSequencer
[string]
默认:@jest/test-sequencer
¥Default: @jest/test-sequencer
此选项允许你使用自定义定序器而不是 Jest 的默认定序器。
¥This option allows you to use a custom sequencer instead of Jest's default.
sort
和 shard
都可以选择返回 Promise
。
¥Both sort
and shard
may optionally return a Promise
.
例如,你可以按字母顺序对测试路径进行排序:
¥For example, you may sort test paths alphabetically:
const Sequencer = require('@jest/test-sequencer').default;
class CustomSequencer extends Sequencer {
/**
* Select tests for shard requested via --shard=shardIndex/shardCount
* Sharding is applied before sorting
*/
shard(tests, {shardIndex, shardCount}) {
const shardSize = Math.ceil(tests.length / shardCount);
const shardStart = shardSize * (shardIndex - 1);
const shardEnd = shardSize * shardIndex;
return [...tests]
.sort((a, b) => (a.path > b.path ? 1 : -1))
.slice(shardStart, shardEnd);
}
/**
* Sort test to determine order of execution
* Sorting is applied after sharding
*/
sort(tests) {
// Test structure information
// https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
const copyTests = [...tests];
return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
}
}
module.exports = CustomSequencer;
将 custom-sequencer
添加到你的 Jest 配置中:
¥Add custom-sequencer
to your Jest configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testSequencer: 'path/to/custom-sequencer.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testSequencer: 'path/to/custom-sequencer.js',
};
export default config;
testTimeout
[number]
默认:5000
¥Default: 5000
测试的默认超时(以毫秒为单位)。
¥Default timeout of a test in milliseconds.
transform
[object<string, pathToTransformer | [pathToTransformer, object]>]
默认:{"\\.[jt]sx?$": "babel-jest"}
¥Default: {"\\.[jt]sx?$": "babel-jest"}
从正则表达式到转换器路径的映射。或者,可以将带有配置选项的元组作为第二个参数传递:{filePattern: ['path-to-transformer', {options}]}
。例如,以下是如何配置 babel-jest
以实现非默认行为:{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}
。
¥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 将项目代码作为 JavaScript 运行,因此如果你使用 Node 不支持的某些语法(例如 JSX、TypeScript、Vue 模板),则需要转换器。默认情况下,Jest 将使用 babel-jest
转换器,它将加载项目的 Babel 配置并转换与 /\.[jt]sx?$/
RegExp 匹配的任何文件(换句话说,任何 .js
、.jsx
、.ts
或 .tsx
文件)。另外,babel-jest
将注入 ES 模块模拟 中谈到的模拟提升所需的 Babel 插件。
¥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). In addition, babel-jest
will inject the Babel plugin necessary for mock hoisting talked about in ES Module mocking.
有关构建你自己的转换器的更多详细信息和说明,请参阅 代码转换 部分。
¥See the Code Transformation section for more details and instructions on building your own transformer.
请记住,除非文件已更改,否则转换器仅对每个文件运行一次。
¥Keep in mind that a transformer only runs once per file unless the file has changed.
如果你希望将默认的 babel-jest
转换器与其他代码预处理器一起使用,请记住显式包含它:
¥Remember to include the default babel-jest
transformer explicitly, if you wish to use it alongside with additional code preprocessors:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transform: {
'\\.[jt]sx?$': 'babel-jest',
'\\.css$': 'some-css-transformer',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transform: {
'\\.[jt]sx?$': 'babel-jest',
'\\.css$': 'some-css-transformer',
},
};
export default config;
transformIgnorePatterns
[array<string>]
默认:["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
¥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. For example:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
};
export default config;
第一个模式将匹配(因此不转换)/node_modules
内的文件,/node_modules/foo/
和 /node_modules/bar/
中的文件除外。第二个模式将匹配(因此不会转换)任何包含 /bar/
的路径内的文件。将两者结合在一起时,/node_modules/bar/
中的文件将不会被转换,因为它确实与第二个模式匹配,即使它被第一个模式排除了。
¥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.
有时(尤其是在 React Native 或 TypeScript 项目中),第 3 方模块会作为未转译的代码发布。由于 node_modules
内的所有文件默认都不会被转换,Jest 将无法理解这些模块中的代码,从而导致语法错误。为了克服这个问题,你可以使用 transformIgnorePatterns
来允许转译此类模块。你将在 React Native 指南 中找到此用例的一个很好的示例。
¥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.
这些模式字符串与完整路径匹配。使用 <rootDir>
字符串标记包含项目根目录的路径,以防止项目意外忽略可能具有不同根目录的不同环境中的所有文件。
¥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
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: [
'<rootDir>/bower_components/',
'<rootDir>/node_modules/',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: [
'<rootDir>/bower_components/',
'<rootDir>/node_modules/',
],
};
export default config;
如果你使用 pnpm
,需要转换 node_modules
下的一些包,需要注意的是,该文件夹下的包(如 node_modules/package-a/
)已经符号链接到了 .pnpm
下的路径(如 node_modules/.pnpm/package-a@x.x.x/node_modules/package-a/
),所以直接使用 <rootDir>/node_modules/(?!(package-a|@scope/pkg-b)/)
将无法被识别,而 是使用:
¥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
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: [
'<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
/* if config file is under '~/packages/lib-a/' */
`${path.join(
__dirname,
'../..',
)}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
/* 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/' */
'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: [
'<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
/* if config file is under '~/packages/lib-a/' */
`${path.join(
__dirname,
'../..',
)}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
/* 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/' */
'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
],
};
export default config;
需要注意的是,.pnpm
下的 pnpm 的文件夹名称是包名加上 @
和版本号,所以写 /
不会被识别,但使用 @
可以。
¥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.
这对于一些几乎总是用作实现细节的常用 'utility' 模块很有用(如 underscore
、lodash
等)。通常,最佳实践是保持此列表尽可能小,并在单独的测试中始终使用显式 jest.mock()
/jest.unmock()
调用。对于测试的其他读者来说,显式的每个测试设置更容易推断测试将运行的环境。
¥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.
通过在测试文件顶部显式调用 jest.mock()
,可以在各个测试中覆盖此设置。
¥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
或 true
¥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: []
在监视模式下重新运行测试之前与所有源文件路径进行匹配的 RegExp 模式数组。如果文件路径与任何模式匹配,则更新时不会触发重新运行测试。
¥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.
这些模式与完整路径匹配。使用 <rootDir>
字符串标记包含项目根目录的路径,以防止项目意外忽略可能具有不同根目录的不同环境中的所有文件。示例:["<rootDir>/node_modules/"]
。
¥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/"]
.
即使此处未指定任何内容,观察程序也会忽略对版本控制文件夹(.git、.hg、.sl)的更改。默认情况下会监视其他隐藏文件和目录,即以点 (.
) 开头的文件和目录。当你将它们添加到 watchPathIgnorePatterns
时,请记住转义点,因为它是特殊的 RegExp 字符。
¥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
/** @type {import('jest').Config} */
const config = {
watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
};
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:
watchPlugins
属性值中的值可以省略包名称的 jest-watch-
前缀。
¥The values in the watchPlugins
property value can omit the jest-watch-
prefix of the package name.
watchman
[boolean]
默认:true
¥Default: true
是否使用 watchman
进行文件抓取。
¥Whether to use watchman
for file crawling.
workerIdleMemoryLimit
[number|string]
默认:undefined
¥Default: undefined
指定工作线程在回收之前的内存限制,主要是 这个问题 的解决方法;
¥Specifies the memory limit for workers before they are recycled and is primarily a work-around for this issue;
工作进程执行测试后,将检查其内存使用情况。如果超过指定的值,工作线程将被终止并重新启动。可以通过多种不同的方式指定限制,无论结果是什么 Math.floor
都用于将其转换为整数值:
¥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
- 该值假定为系统内存的百分比。所以 0.5 将 worker 的内存限制设置为系统总内存的一半¥
<= 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
- 假设是固定字节值。由于之前的规则,如果你想要 1 字节的值(我不知道为什么),你可以使用1.1
。¥
\> 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 use1.1
. -
有单位
¥With units
-
50%
- 如上,占系统总内存的百分比¥
50%
- As above, a percentage of total system memory -
100KB
、65MB
等 - 用单位表示固定的内存限制。¥
100KB
,65MB
, etc - With units to denote a fixed memory limit.-
K
/KB
- 千字节 (x1000)¥
K
/KB
- Kilobytes (x1000) -
KiB
- 千字节 (x1024)¥
KiB
- Kibibytes (x1024) -
M
/MB
- 兆字节¥
M
/MB
- Megabytes -
MiB
- 兆字节¥
MiB
- Mebibytes -
G
/GB
- 千兆字节¥
G
/GB
- Gigabytes -
GiB
- 千兆字节¥
GiB
- Gibibytes
-
-
由于报告的系统内存不正确,导致基于百分比的内存限制 不适用于 Linux CircleCI 工作线程。
¥Percentage based memory limit does not work on Linux CircleCI workers due to incorrect system memory being reported.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
workerIdleMemoryLimit: 0.2,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
workerIdleMemoryLimit: 0.2,
};
export default config;
//
[string]
该选项允许在 package.json
中的注释。包含注释文本作为该键的值:
¥This option allows comments in package.json
. Include the comment text as the value of this key:
{
"name": "my-project",
"jest": {
"//": "Comment goes here",
"verbose": true
}
}
workerThreads
默认:false
¥Default: false
¥Whether to use worker threads for parallelization. Child processes are used by default.
使用工作线程可能有助于改进 performance。
¥Using worker threads may help to improve performance.
这是实验性功能。请记住,工作线程使用结构化克隆而不是 JSON.stringify()
来序列化消息。这意味着 BigInt
、Map
或 Set
等内置 JavaScript 对象将被正确序列化。但是,在 Error
、Map
或 Set
上设置的额外属性将不会通过序列化步骤传递。有关更多详细信息,请参阅有关 结构化克隆 的文章。
¥This is experimental feature. Keep in mind that the worker threads use structured clone instead of JSON.stringify()
to serialize messages. This means that built-in JavaScript objects as BigInt
, Map
or Set
will get serialized properly. However extra properties set on Error
, Map
or Set
will not be passed on through the serialization step. For more details see the article on structured clone.