Jest 配置
Jest的理念在默认配置就能运行得很好,但有些时候我们还是需要发挥配置的功效。
为了方便对配置进行维护,建议在一个专用的Javascript、Typescript 或 JSON格式的配置文件中定义配置。 The file will be discovered automatically, if it is named jest.config.js|ts|mjs|cjs|cts|json
. 您可以使用 --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,
};
};
To read TypeScript configuration files Jest by default requires ts-node
. You can override this behavior by adding a @jest-config-loader
docblock at the top of the file. Currently, ts-node
and esbuild-register
is supported. Make sure ts-node
or the loader you specify is installed.
/** @jest-config-loader ts-node */
// or
/** @jest-config-loader esbuild-register */
import type {Config} from 'jest';
const config: Config = {
verbose: true,
};
export default config;
You can also pass options to the loader, for instance to enable 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"
键进行配置 Jest,如:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
Also Jest's configuration json file can be referenced through the "jest"
key in the package.json
of your project:
{
"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
[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]waitNextEventLoopTurnForUnhandledRejectionEvents
[boolean]watchPathIgnorePatterns
[array<string>]watchPlugins
[array<string | [string, Object]>]watchman
[boolean]workerIdleMemoryLimit
[number|string]//
[string]workerThreads
参考
automock
[boolean]
默认: 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();
});
Node modules are automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js
). More info here.
Node.js core modules, like fs
, are not mocked by default. 它们可以像 jest.mock('fs')
这样被明显的指定模拟。
bail
[number | boolean]
默认: 0
默认情况下,Jest运行所有测试,并在完成时将所有错误生成到控制台中。 此处可以使用bail config选项,使Jest在n
失败后停止运行测试。 将bail设置为 true
等于将bail设置为 1
。
cacheDirectory
[string]
默认: "/tmp/<path>"
Jest用来储存依赖信息缓存的目录。
Jest attempts to scan your dependency tree once (up-front) and cache it in order to ease some of the filesystem churn that needs to happen while running tests. 这一配置选项让你可以自定义Jest将缓存数据储存在磁盘的某个位置。
clearMocks
[boolean]
默认: false
在每次测试前自动清除mock调用、实例、上下文和结果。 在每次测试之前调用 jest.clearAllMocks()
这不会删除可能已提供的任何模拟实现。
collectCoverage
[boolean]
默认: false
指出是否收集测试时的覆盖率信息。 由于要带上覆盖率搜集语句重新访问所有执行过的文件,这可能会让你的测试执行速度被明显减慢。
Jest ships with two coverage providers: babel
(default) and v8
. See the coverageProvider
option for more details.
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.