配置 Jest
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
Jest 的设计理念是默认开箱即用,但有时您需要更多配置能力。
建议在专用的 JavaScript、TypeScript 或 JSON 文件中定义配置。若文件命名为 jest.config.js|ts|mjs|cjs|cts|json,Jest 将自动发现该文件。您可以使用 --config 参数显式指定文件路径。
请注意:最终生成的配置对象必须始终支持 JSON 序列化。
配置文件应直接导出一个对象:
- 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;
或导出一个返回对象的函数:
- 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,
};
};
Jest 默认需要 ts-node 来读取 TypeScript 配置文件。您可以通过在文件顶部添加 @jest-config-loader 文档块来覆盖此行为。目前支持 ts-node 和 esbuild-register。请确保已安装 ts-node 或您指定的加载器。
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import type {Config} from 'jest';
const config: Config = {
verbose: true,
};
export default config;
您还可以向加载器传递选项,例如启用 transpileOnly:
/** @jest-config-loader ts-node */
/** @jest-config-loader-options {"transpileOnly": true} */
import type {Config} from 'jest';
const config: Config = {
verbose: true,
};
export default config;
配置也可作为普通对象存储在 JSON 文件中:
{
"bail": 1,
"verbose": true
}
或者通过项目 package.json 中的 "jest" 字段定义配置:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
也可通过项目 package.json 中的 "jest" 字段引用 Jest 的 JSON 配置文件:
{
"name": "my-project",
"jest": "./path/to/config.json"
}
选项说明
您可以从 jest-config 获取 Jest 的默认配置进行扩展:
- JavaScript
- TypeScript
const {defaults} = require('jest-config');
/** @type {import('jest').Config} */
const config = {
moduleDirectories: [...defaults.moduleDirectories, 'bower_components'],
};
module.exports = config;
import type {Config} from 'jest';
import {defaults} from 'jest-config';
const config: Config = {
moduleDirectories: [...defaults.moduleDirectories, 'bower_components'],
};
export default config;
automock[布尔值]bail[数值 | 布尔值]cacheDirectory[字符串]clearMocks[布尔值]collectCoverage[布尔值]collectCoverageFrom[数组]coverageDirectory[字符串]coveragePathIgnorePatterns[数组<字符串>]coverageProvider[字符串]coverageReporters[数组<字符串 | [字符串, 选项]>]coverageThreshold[对象]dependencyExtractor[字符串]displayName[字符串, 对象]errorOnDeprecated[布尔值]extensionsToTreatAsEsm[数组<字符串>]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[数字]preset[字符串]prettierPath[字符串]projects[数组<string | ProjectConfig>]randomize[布尔值]reporters[数组<moduleName | [moduleName, options]>]resetMocks[布尔值]resetModules[布尔值]resolver[字符串]restoreMocks[布尔值]rootDir[字符串]roots[数组<字符串>]runtime[字符串]runner[字符串]sandboxInjectedGlobals[array<string>]setupFiles[array]setupFilesAfterEnv[array]showSeed[boolean]slowTestThreshold[number]snapshotFormat[对象]snapshotResolver[字符串]snapshotSerializers[字符串数组]testEnvironment[字符串]testEnvironmentOptions[对象]testFailureExitCode[数字]testMatch[字符串 | 数组<字符串>]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]waitForUnhandledRejections[boolean]watchPathIgnorePatterns[array<string>]watchPlugins[数组<string | [string, Object]>]watchman[布尔值]workerIdleMemoryLimit[数值 | 字符串]//[字符串]workerThreads
参数详解
automock [布尔值]
默认值:false
此选项告知 Jest 自动模拟测试中所有导入的模块。所有被使用的模块将被替换为模拟实现,同时保留原始 API 接口。
示例:
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 模块会自动被模拟。详见此处。
Node.js 核心模块(如 fs)默认不会被模拟。可通过显式调用模拟,例如 jest.mock('fs')。
bail [数值 | 布尔值]
默认值:0
默认情况下,Jest 会运行所有测试并在完成后将所有错误输出到控制台。使用此配置选项可使 Jest 在遇到 n 次失败后停止测试。将 bail 设为 true 等同于设为 1。
cacheDirectory [字符串]
默认值:"/tmp/<path>"
Jest 存储依赖缓存信息的目录。
Jest 会尝试预先扫描你的依赖树一次并将其缓存,以减少运行测试时可能发生的文件系统频繁操作。此配置选项允许你自定义 Jest 在磁盘上存储该缓存数据的位置。
clearMocks [布尔值]
默认值:false
在每次测试前自动清除模拟调用、实例、上下文和结果。等效于在每个测试前调用jest.clearAllMocks()。此操作不会移除已配置的任何模拟实现。
collectCoverage [布尔值]
默认值:false
指示在执行测试时是否应收集覆盖率信息。由于这会给所有执行的文件添加覆盖率收集语句,可能会显著降低测试速度。
Jest 内置两种覆盖率提供程序:babel(默认)和 v8。更多详情请参阅 coverageProvider 选项。
babel 和 v8 覆盖率提供程序分别使用 /* istanbul ignore next */ 和 /* c8 ignore next */ 注释从覆盖率报告中排除行。更多信息可查看 istanbuljs 文档 和 c8 文档。
collectCoverageFrom [数组]
默认: undefined
一个 glob 模式 数组,指示应收集覆盖率信息的文件集合。如果文件匹配指定的 glob 模式,即使该文件没有测试用例且从未在测试套件中被引用,也会收集其覆盖率信息。
- 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/** 的文件。
每个 glob 模式按配置中的顺序应用。例如 ["!**/__tests__/**", "**/*.js"] 不会排除 __tests__,因为第二个模式覆盖了否定规则。要使否定 glob 生效,在此示例中必须将其置于 **/*.js 之后。
此选项要求 collectCoverage 设为 true 或使用 --coverage 参数调用 Jest。
Help:
If you are seeing coverage output such as...
=============================== Coverage summary ===============================
Statements : Unknown% ( 0/0 )
Branches : Unknown% ( 0/0 )
Functions : Unknown% ( 0/0 )
Lines : Unknown% ( 0/0 )
================================================================================
Jest: Coverage data for global was not found.
Most likely your glob patterns are not matching any files. Refer to the micromatch documentation to ensure your globs are compatible.
coverageDirectory [字符串]
默认: undefined
Jest输出覆盖率文件的目录路径。
coveragePathIgnorePatterns [数组<字符串>]
默认值:["/node_modules/"]
一个正则表达式模式字符串数组,在执行测试前与所有文件路径进行匹配。如果文件路径匹配任何模式,将跳过覆盖率信息收集。
这些模式字符串会匹配完整路径。使用 <rootDir> 字符串标记可包含项目根目录路径,防止在不同环境下因根目录不同而意外忽略所有文件。例如:["<rootDir>/build/", "<rootDir>/node_modules/"]。
coverageProvider [字符串]
指定用于检测代码覆盖率的提供程序。允许值为babel(默认)或v8。
coverageReporters [数组<字符串 | [字符串, 选项]>]
默认值:["clover", "json", "lcov", "text"]
Jest 在生成覆盖率报告时使用的报告器名称列表。可以使用任何 istanbul 报告器。
设置此选项会覆盖默认值。添加 "text" 或 "text-summary" 可在控制台输出中查看覆盖率摘要。
可通过元组形式传递额外选项。例如,您可以隐藏所有完全覆盖文件的覆盖率报告行:
- 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 类型。
coverageThreshold [对象]
默认: undefined
用于配置覆盖率结果的最低强制阈值。阈值可指定为 global(全局)、glob 模式 或目录/文件路径。若未达到阈值,Jest 将执行失败。正数阈值表示要求的最低百分比,负数阈值表示允许的最大未覆盖实体数。
例如,使用以下配置时,如果分支/行/函数覆盖率低于 80% 或存在超过 10 个未覆盖语句,Jest 将失败:
- 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;
若同时指定了 glob/路径 和 global,则匹配路径的覆盖率数据将从全局统计中扣除,阈值将独立应用。glob 的阈值适用于所有匹配文件。若路径指定的文件不存在,将返回错误。
例如,对于以下配置:
- 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 将在以下情况失败:
-
./src/components目录的分支或语句覆盖率低于 40% -
匹配
./src/reducers/**/*.jsglob 的文件存在语句覆盖率低于 90% -
./src/api/very-important-module.js文件覆盖率低于 100% -
其余文件合并覆盖率低于 50%(
global)
dependencyExtractor [字符串]
默认: undefined
此选项允许使用自定义依赖提取器。必须是导出包含 extract 函数的对象的 Node 模块,例如:
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 等)。
该模块还可包含 getCacheKey 函数,用于生成缓存键以确定逻辑是否变更,从而决定是否应丢弃相关缓存产物。
displayName [字符串, 对象]
默认值:undefined
允许在测试运行时旁显示标签。这在多项目仓库中特别有用,可直观标识测试所属项目。
- 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 提供颜色支持,因此所有有效的 chalk 颜色选项均可使用。
- 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 [布尔值]
默认值:false
使调用已弃用的 API 时抛出友好错误信息。有助于简化升级过程。
extensionsToTreatAsEsm [数组<字符串>]
默认值:[]
Jest 会将 .mjs 文件及最近的 package.json 中 type 字段设为 module 的 .js 文件作为 ECMAScript 模块执行。如需其他原生 ESM 文件支持,请在此指定其文件扩展名。
- 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 支持仍处于实验阶段,详情请参阅 相关文档。
fakeTimers [object]
默认值:{}
当代码设置了测试中无需等待的长超时时限时,伪计时器会非常有用。更多细节请参阅 伪计时器指南 和 API 文档。
此选项为所有测试提供伪计时器的默认配置。在测试文件中调用 jest.useFakeTimers() 将使用这些配置,若传入配置对象则会覆盖这些设置。例如,可配置 Jest 保留 process.nextTick() 的原始实现并调整递归计时器的执行上限:
- 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.useFakeTimers(),可通过 Jest 配置全局启用伪计时器:
- 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;
配置选项:
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;
};
如需使用传统伪计时器实现(不支持额外选项),可通过以下方式全局启用:
- 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>]
默认值:['']
测试文件通常会被排除在代码覆盖率统计之外。此选项可覆盖该行为,将原本忽略的文件纳入统计。
例如,若测试文件使用 .t.js 扩展名:
export function sum(a, b) {
return a + b;
}
if (process.env.NODE_ENV === 'test') {
test('sum', () => {
expect(sum(1, 2)).toBe(3);
});
}
通过设置 forceCoverageMatch 即可收集这些文件的覆盖率数据:
- 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]
默认值:{}
定义在所有测试环境中需可用的全局变量集合。
例如,以下配置将在所有测试环境中创建值为 true 的全局变量 __DEV__:
- 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 实现。
globalSetup [string]
默认: undefined
此选项允许使用自定义全局安装模块,该模块必须导出一个函数(可以是同步或异步) 。该函数将在所有测试套件执行前触发一次,并接收两个参数:Jest 的 globalConfig 和 projectConfig。
在多项目运行器中配置的全局安装模块,仅当您运行该项目的至少一个测试时才会触发。
通过 globalSetup 定义的全局变量只能在 globalTeardown 中读取。您无法在测试套件中访问此处定义的全局变量。
虽然代码转换会应用于链接的安装文件,但 Jest 不会转换 node_modules 中的任何代码。这是因为需要加载实际的转换器(如 babel 或 typescript)来执行转换。
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPatterns);
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.testPathPatterns);
console.log(projectConfig.cache);
await globalThis.__MONGOD__.stop();
};
globalTeardown [string]
默认: undefined
此选项允许使用自定义全局拆卸模块,该模块必须导出一个函数(可以是同步或异步)。该函数将在所有测试套件执行后触发一次,并接收两个参数:Jest 的 globalConfig 和 projectConfig。
在多项目运行器中配置的全局拆卸模块,仅当您运行该项目的至少一个测试时才会触发。
与 globalSetup 相同,关于 node_modules 转换的限制同样适用于 globalTeardown。
haste [object]
默认: undefined
此选项用于配置 jest-haste-map(Jest 内部文件爬虫/缓存系统)的行为。支持以下配置项:
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 an 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
将 Jest 的全局变量(expect、test、describe、beforeEach 等)注入全局环境。设为 false 时,需从 @jest/globals 显式导入,例如:
import {expect, jest, test} from '@jest/globals';
jest.useFakeTimers();
test('some test', () => {
expect(Date.now()).toBe(0);
});
此选项仅在使用默认的 jest-circus 测试运行器时支持。
maxConcurrency [number]
默认值:5
当使用 test.concurrent 时,此数值限制可同时运行的并发测试数量。超出此限制的测试将进入队列,待有可用资源时执行。
maxWorkers [number | string]
指定工作线程池为运行测试所创建的最大工作线程数。在单次运行模式下,默认值为机器可用核心数减一(为主线程预留)。在监视模式下,默认值为机器可用核心数的一半,以确保 Jest 保持非侵入性且不会导致机器卡顿。在资源有限的环境(如 CI)中调整此值可能有用,但默认值已满足大多数场景需求。
对于 CPU 资源不稳定的环境,可使用基于百分比的配置:
- 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"]
一个目录名称数组,将从被请求模块的位置开始向上 递归搜索。设置此选项将覆盖默认值,若仍需搜索 node_modules 中的包,请将其包含在数组中:
- 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;