配置 Jest
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
Jest 的设计理念是默认开箱即用,但有时您需要更多配置能力。
建议在专用的 JavaScript、TypeScript 或 JSON 文件中定义配置。若文件命名为 jest.config.js|ts|mjs|cjs|cts|json,Jest 将自动发现该文件。您可以使用 --config 参数显式指定文件路径。
请注意:最终生成的配置对象必须始终支持 JSON 序列化。
Open Config Examples
- Using
defineConfigfromjestyou should follow this:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
module.exports = defineConfig({
// ... Specify options here.
});
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig} from 'jest';
export default defineConfig({
// ... Specify options here.
});
- You can retrieve Jest's defaults from
jest-configto extend them if needed:
- JavaScript
- TypeScript
const {defineConfig} = require('jest');
const {defaults} = require('jest-config');
module.exports = defineConfig({
moduleDirectories: [...defaults.moduleDirectories, 'bower_components'],
});
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig} from 'jest';
import {defaults} from 'jest-config';
export default defineConfig({
moduleDirectories: [...defaults.moduleDirectories, 'bower_components'],
});
export default config;
- When using a separate Jest config, you can also extend Jest's options from another config file if needed using
mergeConfigfromjest:
- JavaScript
- TypeScript
const {defineConfig, mergeConfig} = require('jest');
const jestConfig = require('./jest.config');
module.exports = mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
);
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig, mergeConfig} from 'jest';
import jestConfig from './jest.config';
export default mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
);
- If your Jest config needs to be defined as a function, you can define the config like this:
- JavaScript
- TypeScript
const {defineConfig, mergeConfig} = require('jest');
const jestConfig = require('./jest.config');
module.exports = defineConfig(() =>
mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
),
);
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig, mergeConfig} from 'jest';
import jestConfig from './jest.config';
export default defineConfig(() =>
mergeConfig(
jestConfig,
defineConfig({
// ... Specify options here.
}),
),
);
- The configuration also can be stored in a JSON file as a plain object:
{
"bail": 1,
"verbose": true
}
- Alternatively Jest's configuration can be defined through the
"jest"key in thepackage.jsonof your project:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
- Also Jest's configuration json file can be referenced through the
"jest"key in thepackage.jsonof your project:
{
"name": "my-project",
"jest": "./path/to/config.json"
}
默认情况下,Jest 读取 TypeScript 配置文件需要依赖 ts-node。您可以在文件顶部添加 @jest-config-loader 文档块来覆盖此行为。目前支持 ts-node 和 esbuild-register。请确保已安装 ts-node 或指定的加载器。
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import {defineConfig} from 'jest';
export default defineConfig({
verbose: true,
});
您还可以向加载器传递选项,例如启用 transpileOnly:
/** @jest-config-loader ts-node */
/** @jest-config-loader-options {"transpileOnly": true} */
import type {defineConfig} from 'jest';
export default defineConfig({
verbose: true,
});
选项说明
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
const {defineConfig} = require('jest');
module.exports = defineConfig({
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
});
import {defineConfig} from 'jest';
export default defineConfig({
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
});
这将收集项目 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。