Настройка Jest
Философия Jest'а заключается в идеальном функционале "из коробки", но иногда вам нужно немного поработать с конфигурированием.
Советуем хранить конфигурации в отдельном JavaScript, TypeScript или JSON файле. Он будет автоматически загружен, если его название будет выглядеть, как jest.config.js|ts|mjs|cjs|json
. Используйте --config
флаг, чтобы явно указать путь к файлу конфигурации.
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,
};
};
To read TypeScript configuration files Jest requires ts-node
. Make sure it is installed in your project.
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 the package.json
of your project:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
Параметры
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]preset
[string]prettierPath
[string]projects
[array<string | ProjectConfig>]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]
Справка
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]
По умолчанию: 7
По умолчанию, Jest запускает все тесты и после завершения выводит все ошибки в консоли. Опция bail может быть использована, чтобы Jest прекратил запуск тестов после n
сбоев. Установка bail в значение true
равнозначна установке bail в 1
.
cacheDirectory
[string]
По умолчанию: «/tmp/<путь>»
Директория, в которой 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. Данная опция позволяет разработчику указать где именно в файловой системе следует хранить кэшированные данные.
clearMocks
[boolean]
По умолчанию = false
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
Указывает следует ли собирать информацию о тестовом покрытии при выполнении тестов. Из-за того, что данный процесс вносит информацию о покрытии во все выполненные файлы, ваши тесты могут быть выполняться на порядок дольше обычного.
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.
collectCoverageFrom
[array]
По умолчанию: undefined
Массив glob patterns, который указывает, для каких файлов необходимо собирать информацию о покрытии. Если файл указанный в массиве существует, то информация о покрытии будет собираться для него, даже если тестов для этого файла не существует и сам он не встречается в наборе тестов.
- 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/**
.
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
.
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.
Most likely your glob patterns are not matching any files. Refer to the micromatch documentation to ensure your globs are compatible.
coverageDirectory
[string]
По умолчанию: undefined
The directory where Jest should output its coverage files.
coveragePathIgnorePatterns
[array<string>]
Default: ["/node_modules/"]
An array of regexp pattern strings that are matched against all file paths before executing the test. If the file path matches any of the patterns, coverage information will be skipped.
These pattern strings match against the full path. Use the <rootDir>
string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/", "<rootDir>/node_modules/"]
.
coverageProvider
[string]
Indicates which provider should be used to instrument code for coverage. Допустимые значения: babel
(по умолчанию) или v8
.
coverageReporters
[array<string | [string, options]>]
Default: ["clover", "json", "lcov", "text"]
A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used.
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;
For more information about the options object shape refer to CoverageReporterWithOptions
type in the type definitions.
coverageThreshold
[object]
По умолчанию: undefined
This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as global
, as a glob, and as a directory or file path. If thresholds aren't met, jest will fail. Thresholds specified as a positive number are taken to be the minimum percentage required. Thresholds specified as a negative number represent the maximum number of uncovered entities allowed.
For example, with the following configuration jest will fail if there is less than 80% branch, line, and function coverage, or if there are more than 10 uncovered statements:
- JavaScript
- TypeScript
/** @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;
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;