Налаштування 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
для передачі явного шляху до файлу.
Майте на увазі, що отримана конфігурація має бути придатна для серіалізації в 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,
};
};
Щоб прочитати файли конфігурації TypeScript, Jest потребує ts-node
. Переконайтеся, що він встановлений у вашому проєкті.
Також, конфігурація може зберігатися у файлі JSON у вигляді звичайного об'єкту:
{
"bail": 1,
"verbose": true
}
Інший спосіб визначити Jest конфігурацію - через ключове значення "jest"
в package.json
вашого проєкту:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
Параметри
За потреби в доповненні, ви можете отримати значення за замовчуванням з jest-config
:
- 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]
Default: false
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', () => {
// Публічні методи `utils` тепер є функціями-імітаціями
expect(utils.authorize.mock).toBeTruthy();
expect(utils.isAuthorized.mock).toBeTruthy();
// Ми можете надати їм власну реалізацію
// чи передати очікуване значення
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. They can be mocked explicitly, like jest.mock('fs')
.
bail
[number | boolean]
Default: 0
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]
Default: "/tmp/<path>"
The directory where Jest should store its cached dependency information.
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]
Default: false
Автоматично очищує імітації викликів, екземплярів, контекстів і результатів перед кожним тестом. Equivalent to calling jest.clearAllMocks()
before each test. This does not remove any mock implementation that may have been provided.
collectCoverage
[boolean]
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 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]
Default: undefined
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/**',
],
};
import type {Config} from 'jest';
const config: Config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/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/**
.
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
.
Допомога:
Якщо ви бачите вивід покриття, наприклад як...
=============================== 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]
Default: 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]
Вказує, який постачальник повинен використовуватися для перевірки покриття коду. Allowed values are babel
(default) or 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}]],
};
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]
Default: 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;
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 will fail if:
- Каталог
./src/components
має менш ніж 40% покриття рішення або тверджень. - Один з файлів, що відповідають шаблону
./src/reducers/**/*.js
, має менш ніж 90% покриття тверджень. - Файл
./src/api/very-important-module.js
має менш ніж 100% покриття. - Кожен файл із залишку має менш ніж 50% покриття (
global
).
dependencyExtractor
[string]
Default: undefined
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');
},
};
The extract
function should return an iterable (Array
, Set
, etc.) with the dependencies found in the code.
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]
default: undefined
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;
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
за замовчуванням, коли його значення є рядком. 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]
Default: false
Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.
extensionsToTreatAsEsm
[array<string>]
Default: []
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's ESM support is still experimental, see its docs for more details.
fakeTimers
[object]
Default: {}
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.
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});
// ...
});
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;
/** Встановлює поточний час системи для використання в фальшивих таймерах у мілісекундах. 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.
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);
});
}
You can collect coverage from those files with setting forceCoverageMatch
.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
forceCoverageMatch: ['**/*.t.js'],
};
module.exports = config;