Configuring Jest
Jest's configuration can be defined in the package.json
file of your project, or through a jest.config.js
file or through the --config <path/to/file.js|json>
option. If you'd like to use your package.json
to store Jest's config, the "jest"
key should be used on the top level so Jest will know how to find your settings:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
Або використовуючи JavaScript:
// jest.config.js
module.exports = {
verbose: true,
};
Майте на увазі, що фінальна конфігурація повинна бути придатна для серіалізації в JSON.
When using the --config
option, the JSON file must not contain a "jest" key:
{
"bail": true,
"verbose": true
}
Опції
These options let you control Jest's behavior in your package.json
file. The Jest philosophy is to work great by default, but sometimes you just need more configuration power.
Defaults
You can retrieve Jest's default options to expand them if needed:
// jest.config.js
const {defaults} = require('jest-config');
module.exports = {
// ...
moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
// ...
};
automock
[boolean]bail
[boolean]browser
[boolean]cacheDirectory
[string]clearMocks
[boolean]collectCoverage
[boolean]collectCoverageFrom
[array]coverageDirectory
[string]coveragePathIgnorePatterns
[array<string>]coverageReporters
[array<string>]coverageThreshold
[object]displayName
[string]errorOnDeprecated
[boolean]forceCoverageMatch
[array<string>]globals
[object]globalSetup
[string]globalTeardown
[string]haste
[object]moduleDirectories
[array<string>]moduleFileExtensions
[array<string>]moduleNameMapper
[object<string, 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]setupFiles
[array]setupTestFrameworkScriptFile
[string]snapshotSerializers
[array<string>]testEnvironment
[string]testEnvironmentOptions
[Object]testFailureExitCode
[number]testMatch
[array<string>]testPathIgnorePatterns
[array<string>]testRegex
[string]testResultsProcessor
[string]testRunner
[string]testURL
[string]timers
[string]transform
[object<string, pathToTransformer | [pathToTransformer, object]>]transformIgnorePatterns
[array<string>]unmockedModulePathPatterns
[array<string>]verbose
[boolean]watchPathIgnorePatterns
[array<string>]watchPlugins
[array<string | [string, object]>]watchman
[boolean]
Довідка
automock
[boolean]
За замовчуванням: 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.
Приклад:
// utils.js
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
//__tests__/automocking.test.js
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();
});
Note: Node modules are automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js
). More info here.
Note: Core modules, like fs
, are not mocked by default. They can be mocked explicitly, like jest.mock('fs')
.
bail
[boolean]
За замовчуванням: false
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 the first failure.
browser
[boolean]
За замовчуванням: false
Чи враховувати поле Browserify "browser"
в package.json
під час пошуку модулів. Деякі модулі експортують різні версії в залежності від того, чи вони виконуються в Node, чи в браузері.
cacheDirectory
[string]
За замовчуванням: "/tmp/ < шлях >"
Каталог в якому Jest має зберігати свою кешовану інформацію про залежності.
Jest сканує ваше дерево залежностей один раз (наперед) і кешує його аби дещо полегшити згрібання файлової системи, що відбувається при виконанні тестів. Ця опція дозволяє налаштувати де саме Jest зберігатиме цю кешовану інформацію на диску.
clearMocks
[boolean]
За замовчуванням: false
Automatically clear mock calls and instances before every test. Equivalent to calling jest.clearAllMocks()
before each test. Цей параметр не видаляє жодну реалізацію, яка могла бути вказана для імітацій.
collectCoverage
[boolean]
За замовчуванням: false
Визначає чи потрібно збирати інформацію про покриття під час виконання тестів. Оскільки це модифікує всі виконані файли інструкціями збирання покриття, це може суттєво сповільнити тести.
collectCoverageFrom
[array]
За замовчуванням: 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.
Приклад:
{
"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/**
.
Примітка: Цей параметр вимагає collectCoverage
бути рівним true або щоб Jest, було викликано з --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
Каталог, де Jest виводить файли покриття.
coveragePathIgnorePatterns
[array<string>]
За замовчуванням: ["/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.
Ці рядкові вирази зіставляються з повним шляхом. 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. Приклад: ["<rootDir>/build/", "<rootDir>/node_modules/"]
.
coverageReporters
[array<string>]
Default: ["json", "lcov", "text", "clover"]
A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used.
Note: Setting this option overwrites the default values. Add "text"
or "text-summary"
to see a coverage summary in the console output.
coverageThreshold
[object]
За замовчуванням: undefined
Цей параметр використовується, щоб вказати мінімальний поріг покриття тестами. 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:
{
...
"jest": {
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
}
}
}
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:
{
...
"jest": {
"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
}
}
}
}
Jest will fail if:
- The
./src/components
directory has less than 40% branch or statement coverage. - One of the files matching the
./src/reducers/**/*.js
glob has less than 90% statement coverage. - The
./src/api/very-important-module.js
file has less than 100% coverage. - Every remaining file combined has less than 50% coverage (
global
).
displayName
[string]
за замовчуванням: 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.
errorOnDeprecated
[boolean]
За замовчуванням: false
Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.
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:
// sum.t.js
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
.
{
...
"jest": {
"forceCoverageMatch": ["**/*.t.js"]
}
}
globals
[object]
За замовчуванням: {}
Множина глобальних змінних, що повинна бути доступною у всіх тестових середовищах.
Наприклад, наступний код присвоїть глобальній змінній __DEV__
значення true
у всіх тестових середовищах:
{
...
"jest": {
"globals": {
"__DEV__": true
}
}
}
Зверніть увагу, що, якщо ви вказуєте тут значення, яке передається за посиланням (таке, як об’єкт або масив) і якийсь код мутує це значення в процесі виконання тестів, ця зміна не буде збережена для інших тестових файлів. In addition, the globals
object must be json-serializable, so it can't be used to specify global functions. For that, you should use setupFiles
.
globalSetup
[string]
За замовчуванням: undefined
This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's globalConfig
object as a parameter.
globalTeardown
[string]
За замовчуванням: undefined
This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's globalConfig
object as a parameter.
haste
[object]
За замовчуванням: undefined
This will be used to configure the behavior of jest-haste-map
, Jest's internal file crawler/cache system. The following options are supported:
type HasteConfig = {
// Whether to hash files using SHA-1.
computeSha1?: boolean;
// The platform to use as the default, e.g. 'ios'.
defaultPlatform?: string | null;
// Path to a custom implementation of Haste.
hasteImplModulePath?: string;
// All platforms to target, e.g ['ios', 'android'].
platforms?: Array<string>;
// Whether to throw on error on module collision.
throwOnModuleCollision?: boolean;
};
moduleDirectories
[array<string>]
За замовчуванням: ["node_modules"]
Масив імен каталогів, в яких буде відбуватися рекурсивний пошук підключених модулів. Setting this option will override the default, if you wish to still search node_modules
for packages include it along with any other options: ["node_modules", "bower_components"]
moduleFileExtensions
[array<string>]
За замовчуванням: ["js", "json", "jsx", "вузол"]
An array of file extensions your modules use. If you require modules without specifying a file extension, these are the extensions Jest will look for, in left-to-right order.
If you are using TypeScript, you will want to add "ts"
and/or "tsx"
to the above default. Where you place these is up to you - we recommend placing the extensions most commonly used in your project on the left.
moduleNameMapper
[object<string, string>]
За замовчуванням: null
Відповідність регулярних виразів до імен модулів, які дозволяють підміняти ресурси, такі як зображення чи стилі, одним модулем.
Модулі, які використовуються для підміни, не імітовані за замовчуванням, незалежно від того, чи увімнена автоматична імітація модулів, чи ні.
Використовуйте токен <rootDir>
, для посилання на значення rootDir
, якщо ви хочете вказати шляхи до файлів.
Додатково ви можете заміняти знайдені регулярними виразами групи на нумеровані посилання.
Приклад:
{
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
"module_name_(.*)": "<rootDir>/substituted_module_$1.js"
}
}
The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first.
Примітка: якщо ви вкажете регулярні вирази без границь ^$
, це може спричинити помилки, які дуже важко відслідкувати. Наприклад relay
замінить всі модулі, які містять слово relay
в імені: relay
, react-relay
і graphql-relay
будуть підмінені вказаним файлом.
modulePathIgnorePatterns
[array<string>]
За замовчуванням: []
Масив рядків з регулярними виразами, з якими звіряються шляхи всіх модулів перед тим, як вважатися видимими для завантажувача модулів. Якщо шлях до модуля співпадає з будь-яким шаблоном, то цей модуль не буде підключатися в тестах за допомогою require()
.
Ці рядкові вирази зіставляються з повним шляхом. 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. Наприклад: ["<rootDir>/build/"]
.
modulePaths
[array<string>]
За замовчуванням: []
An alternative API to setting the NODE_PATH
env variable, modulePaths
is an array of absolute paths to additional locations to search when resolving modules. Використовуйте ключове слово <rootDir>
, щоб посилатися на кореневий каталог вашого проекту. Наприклад: ["<rootDir>/app/"]
.
notify
[boolean]
За замовчуванням: false
Активує сповіщення про результати тестування.
Beware: Jest uses node-notifier to display desktop notifications. On Windows, it creates a new start menu entry on the first use and not display the notification. Notifications will be properly displayed on subsequent runs
notifyMode
[string]
Default: always
Specifies notification mode. Requires notify: true
.
Modes
always
: always send a notification.failure
: send a notification when tests fail.success
: send a notification when tests pass.change
: send a notification when the status changed.success-change
: send a notification when tests pass or once when it fails.failure-change
: send a notification when tests fail or once when it passes.
preset
[string]
За замовчуванням: undefined
A preset that is used as a base for Jest's configuration. A preset should point to an npm module that has a jest-preset.json
or jest-preset.js
file at the root.
For example, this preset foo-bar/jest-preset.js
will be configured as follows:
{
"preset": "foo-bar"
}
Presets may also be relative to filesystem paths.
{
"preset": "./node_modules/foo-bar/jest-preset.js"
}
prettierPath
[string]
Default: 'prettier'
Sets the path to the prettier
node module used to update inline snapshots.
projects
[array<string | projectconfig>]
За замовчуванням: undefined
Коли в параметрі projects
вказаний масив шляхів до каталогів або шаблонів пошуку каталогів, Jest буде запускати тести одночасно у всіх вказаних проектах. Це чудова опція для монорепозиторіїв або під час роботи над кількома проектами одночасно.
{
"projects": ["<rootDir>", "<rootDir>/examples/*"]
}
This example configuration will run Jest in the root directory as well as in every folder in the examples directory. You can have an unlimited amount of projects running in the same Jest instance.
The projects feature can also be used to run multiple configurations or multiple runners. For this purpose, you can pass an array of configuration objects. For example, to run both tests and ESLint (via jest-runner-eslint) in the same invocation of Jest:
{
"projects": [
{
"displayName": "test"
},
{
"displayName": "lint",
"runner": "jest-runner-eslint",
"testMatch": ["<rootDir>/**/*.js"]
}
]
}
Note: When using multi-project runner, it's recommended to add a displayName
for each project. This will show the displayName
of a project next to its tests.
reporters
[array<modulename | [modulename, options]>]
За замовчуванням: undefined
Використовуйте цей параметр, щоб додати користувацькі генератори звітів для Jest. Користувацький генератор звітів — це клас, який реалізує методи onRunStart
, onTestStart
, onTestResult
, onRunComplete
, які будуть викликані як тільки відбудеться відповідна подія.
If custom reporters are specified, the default Jest reporters will be overridden. To keep default reporters, default
can be passed as a module name.
Це перезапише генератори звітів, встановлені за замовчуванням:
{
"reporters": ["<rootDir>/my-custom-reporter.js"]
}
А це й приклад буде використовувати користувацькі генератори звітів на додачу до встановлених за замовчуванням:
{
"reporters": ["default", "<rootDir>/my-custom-reporter.js"]
}
Крім того, налаштування користувацьких генераторів звітів можуть бути передані в об’єкті options
в якості другого праметру:
{
"reporters": [
"default",
["<rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]
]
}
Модулі користувацьких генераторів звітів повинні визначити клас, який приймає GlobalConfig
та опції в якості параметрів конструктора:
Приклад генератора звітів:
// my-custom-reporter.js
class MyCustomReporter {
constructor(globalConfig, options) {
this._globalConfig = globalConfig;
this._options = options;
}
onRunComplete(contexts, results) {
console.log('Custom reporter output:');
console.log('GlobalConfig: ', this._globalConfig);
console.log('Options: ', this._options);
}
}
module.exports = MyCustomReporter;
Користувацькі генератори звітів також можуть змусити Jest завершити роботу з ненульовим кодом виходу, повернувши об’єкт Error з методу getLastError()
class MyCustomReporter {
// ...
getLastError() {
if (this._shouldFail) {
return new Error('my-custom-reporter.js reported an error');
}
}
}
For the full list of methods and argument types see Reporter
interface in packages/jest-reporters/src/types.ts
resetMocks
[boolean]
За замовчуванням: false
Automatically reset mock state before every test. Equivalent to calling jest.resetAllMocks()
before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.
resetModules
[boolean]
За замовчуванням: false
By default, each test file gets its own independent module registry. Enabling resetModules
goes a step further and resets the module registry before running each individual test. This is useful to isolate modules for every test so that the local module state doesn't conflict between tests. This can be done programmatically using jest.resetModules()
.
resolver
[string]
За замовчуванням: undefined
This option allows the use of a custom resolver. This resolver must be a node module that exports a function expecting a string as the first argument for the path to resolve and an object with the following structure as the second argument:
{
"basedir": string,
"browser": boolean,
"extensions": [string],
"moduleDirectory": [string],
"paths": [string],
"rootDir": [string]
}
The function should either return a path to the module that should be resolved or throw an error if the module can't be found.
restoreMocks
[boolean]
За замовчуванням: false
Automatically restore mock state before every test. Equivalent to calling jest.restoreAllMocks()
before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation.
rootDir
[string]
Default: The root of the directory containing your Jest config file or the package.json
or the pwd
if no package.json
is found
The root directory that Jest should scan for tests and modules within. If you put your Jest config inside your package.json
and want the root directory to be the root of your repo, the value for this config param will default to the directory of the package.json
.
Oftentimes, you'll want to set this to 'src'
or 'lib'
, corresponding to where in your repository the code is stored.
Note that using '<rootDir>'
as a string token in any other path-based config settings will refer back to this value. So, for example, if you want your setupFiles
config entry to point at the env-setup.js
file at the root of your project, you could set its value to ["<rootDir>/env-setup.js"]
.
roots
[array<string>]
За замовчуванням: ["< rootDir >"]
Список шляхів до директорій, що Jest повинен використовувати для пошуку файлів в них.
There are times where you only want Jest to search in a single sub-directory (such as cases where you have a src/
directory in your repo), but prevent it from accessing the rest of the repo.
Note: While rootDir
is mostly used as a token to be re-used in other configuration options, roots
is used by the internals of Jest to locate test files and source files. This applies also when searching for manual mocks for modules from node_modules
(__mocks__
will need to live in one of the roots
).
Note: By default, roots
has a single entry <rootDir>
but there are cases where you may want to have multiple roots within one project, for example roots: ["<rootDir>/src/", "<rootDir>/tests/"]
.
runner
[string]
Default: "jest-runner"
This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include:
To write a test-runner, export a class with which accepts globalConfig
in the constructor, and has a runTests
method with the signature:
async runTests(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
options: TestRunnerOptions,
): Promise<void>
If you need to restrict your test-runner to only run in serial rather than being executed in parallel your class should have the property isSerial
to be set as true
.
setupFiles
[array]
За замовчуванням: []
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
It's also worth noting that setupFiles
will execute before setupTestFrameworkScriptFile
.
setupTestFrameworkScriptFile
[string]
За замовчуванням: undefined
The path to a module that runs some code to configure or set up the testing framework before each test file in the suite is executed. Since setupFiles
executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment.
If you want a path to be relative to the root directory of your project, please include <rootDir>
inside a path's string, like "<rootDir>/a-configs-folder"
.
For example, Jest ships with several plug-ins to jasmine
that work by monkey-patching the jasmine API. If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in these modules.
Example setupTestFrameworkScriptFile
in a jest.config.js:
module.exports = {
setupTestFrameworkScriptFile: './jest.setup.js',
};
Example jest.setup.js
file
jest.setTimeout(10000); // in milliseconds
snapshotSerializers
[array<string>]
За замовчуванням: []
A list of paths to snapshot serializer modules Jest should use for snapshot testing.
Jest has default serializers for built-in JavaScript types, HTML elements (Jest 20.0.0+), ImmutableJS (Jest 20.0.0+) and for React elements. See snapshot test tutorial for more information.
Example serializer module:
// my-serializer-module
module.exports = {
serialize(val, config, indentation, depth, refs, printer) {
return 'Pretty foo: ' + printer(val.foo);
},
test(val) {
return val && val.hasOwnProperty('foo');
},
};
printer
is a function that serializes a value using existing plugins.
To use my-serializer-module
as a serializer, configuration would be as follows:
{
...
"jest": {
"snapshotSerializers": ["my-serializer-module"]
}
}
Нарешті тести будуть виглядати наступним чином:
test(() => {
const bar = {
foo: {
x: 1,
y: 2,
},
};
expect(bar).toMatchSnapshot();
});
Rendered snapshot:
Pretty foo: Object {
"x": 1,
"y": 2,
}
To make a dependency explicit instead of implicit, you can call expect.addSnapshotSerializer
to add a module for an individual test file instead of adding its path to snapshotSerializers
in Jest configuration.
More about serializers API can be found here.
testEnvironment
[string]
За замовчуванням: "jsdom"
The test environment that will be used for testing. The default environment in Jest is a browser-like environment through jsdom. If you are building a node service, you can use the node
option to use a node-like environment instead.
By adding a @jest-environment
docblock at the top of the file, you can specify another environment to be used for all tests in that file:
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div');
expect(element).not.toBeNull();
});
You can create your own module that will be used for setting up the test environment. The module must export a class with setup
, teardown
and runScript
methods. You can also pass variables from this module to your test suites by assigning them to this.global
object – this will make them available in your test suites as global variables.
To use this class as your custom environment, refer to it by its full path within the project. For example, if your class is stored in my-custom-environment.js
in some subfolder of your project, then the annotation might looke like this:
/**
* @jest-environment ./src/test/my-custom-environment
*/
Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.
Приклад:
// my-custom-environment
const NodeEnvironment = require('jest-environment-node');
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
this.testPath = context.testPath;
this.docblockPragmas = context.docblockPragmas;
}
async setup() {
await super.setup();
await someSetupTasks(this.testPath);
this.global.someGlobalObject = createGlobalObject();
// Will trigger if docblock contains @my-custom-pragma my-pragma-value
if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
// ...
}
}
async teardown() {
this.global.someGlobalObject = destroyGlobalObject();
await someTeardownTasks();
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
module.exports = CustomEnvironment;
// my-test-suite
/**
* @jest-environment ./my-custom-environment
*/
let someGlobalObject;
beforeAll(() => {
someGlobalObject = global.someGlobalObject;
});
Note: Jest comes with JSDOM@11 by default. Due to JSDOM 12 and newer dropping support for Node 6, Jest is unable to upgrade for the time being. However, you can install a custom testEnvironment
with whichever version of JSDOM you want. E.g. jest-environment-jsdom-thirteen, which has JSDOM@13.
testEnvironmentOptions
[Object]
За замовчуванням: {}
Test environment options that will be passed to the testEnvironment
. The relevant options depend on the environment. For example, you can override options given to jsdom such as {userAgent: "Agent/007"}
.
testFailureExitCode
[number]
Default: 1
The exit code Jest returns on test failure.
Note: This does not change the exit code in the case of Jest errors (e.g. invalid configuration).
testMatch
[array<string>]
(default: [ "**/__tests__/**/*.js?(x)", "**/?(*.)+(spec|test).js?(x)" ]
)
The glob patterns Jest uses to detect test files. By default it looks for .js
and .jsx
files inside of __tests__
folders, as well as any files with a suffix of .test
or .spec
(e.g. Component.test.js
or Component.spec.js
). It will also find files called test.js
or spec.js
.
See the micromatch package for details of the patterns you can specify.
See also testRegex
[string], but note that you cannot specify both options.
testPathIgnorePatterns
[array<string>]
За замовчуванням: ["/node_modules/"]
An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped.
Ці рядкові вирази зіставляються з повним шляхом. 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. Приклад: ["<rootDir>/build/", "<rootDir>/node_modules/"]
.
testRegex
[string]
За замовчуванням: (/__tests__/.*| ( \\.| /) (test|spec))\\.jsx?$
The pattern Jest uses to detect test files. By default it looks for .js
and .jsx
files inside of __tests__
folders, as well as any files with a suffix of .test
or .spec
(e.g. Component.test.js
or Component.spec.js
). It will also find files called test.js
or spec.js
. See also testMatch
[array<string>], but note that you cannot specify both options.
The following is a visualization of the default regex:
├── __tests__
│ └── component.spec.js # тест
│ └── anything # тест
├── package.json # не тест
├── foo.test.js # тест
├── bar.spec.jsx # тест
└── component.js # не тест
Note: testRegex
will try to detect test files using the absolute file path, therefore, having a folder with a name that matches it will run all the files as tests
testResultsProcessor
[string]
За замовчуванням: undefined
This option allows the use of a custom results processor. This processor must be a node module that exports a function expecting an object with the following structure as the first argument and return it:
{
"success": boolean,
"startTime": epoch,
"numTotalTestSuites": number,
"numPassedTestSuites": number,
"numFailedTestSuites": number,
"numRuntimeErrorTestSuites": number,
"numTotalTests": number,
"numPassedTests": number,
"numFailedTests": number,
"numPendingTests": number,
"openHandles": Array<Error>,
"testResults": [{
"numFailingTests": number,
"numPassingTests": number,
"numPendingTests": number,
"testResults": [{
"title": string (message in it block),
"status": "failed" | "pending" | "passed",
"ancestorTitles": [string (message in describe blocks)],
"failureMessages": [string],
"numPassingAsserts": number,
"location": {
"column": number,
"line": number
}
},
...
],
"perfStats": {
"start": epoch,
"end": epoch
},
"testFilePath": абсолютний шлях до файла з тестами,
"coverage": {}
},
...
]
}
testRunner
[string]
За замовчуванням: jasmine2
This option allows the use of a custom test runner. The default is jasmine2. A custom test runner can be provided by specifying a path to a test runner implementation.
The test runner module must export a function with the following signature:
function testRunner(
globalConfig: GlobalConfig,
config: ProjectConfig,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
An example of such function can be found in our default jasmine2 test runner package.
testURL
[string]
Default: http://localhost
This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
.
timers
[string]
За замовчуванням: real
Setting this value to fake
allows the use of fake timers for functions such as setTimeout
. Fake timers are useful when a piece of code sets a long timeout that we don't want to wait for in a test.
transform
[object<string, pathToTransformer | [pathToTransformer, object]>]
Default: {"^.+\\.[jt]sx?$": "babel-jest"}
A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the examples/typescript example or the webpack tutorial.
Examples of such compilers include:
- Babel
- TypeScript
- async-to-gen
- To build your own please visit the Custom Transformer section
Note: a transformer is only run once per file unless the file has changed. During the development of a transformer it can be useful to run Jest with --no-cache
to frequently delete Jest's cache.
Note: when adding additional code transformers, this will overwrite the default config and babel-jest
is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding {"\\.[jt]sx?$": "babel-jest"}
to the transform property. See babel-jest plugin
transformIgnorePatterns
[array<string>]
За замовчуванням: ["/node_modules/"]
An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed.
Ці рядкові вирази зіставляються з повним шляхом. 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>/bower_components/", "<rootDir>/node_modules/"]
.
Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules
are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns
to allow transpiling such modules. You'll find a good example of this use case in React Native Guide.
unmockedModulePathPatterns
[array<string>]
За замовчуванням: []
An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns in this list, it will not be automatically mocked by the module loader.
This is useful for some commonly used 'utility' modules that are almost always used as implementation details almost all the time (like underscore/lo-dash, etc). It's generally a best practice to keep this list as small as possible and always use explicit jest.mock()
/jest.unmock()
calls in individual tests. Explicit per-test setup is far easier for other readers of the test to reason about the environment the test will run in.
It is possible to override this setting in individual tests by explicitly calling jest.mock()
at the top of the test file.
verbose
[boolean]
За замовчуванням: false
Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. Note that if there is only one test file being run it will default to true
.
watchPathIgnorePatterns
[array<string>]
За замовчуванням: []
An array of RegExp patterns that are matched against all source file paths before re-running tests in watch mode. If the file path matches any of the patterns, when it is updated, it will not trigger a re-run of tests.
These patterns 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>/node_modules/"]
.
Even if nothing is specified here, the watcher will ignore changes to any hidden files and directories, i.e. files and folders that begin with a dot (.
).
watchPlugins
[array<string | [string, object]>]
За замовчуванням: []
This option allows you to use custom watch plugins. Read more about watch plugins here.
Examples of watch plugins include:
jest-watch-master
jest-watch-select-projects
jest-watch-suspend
jest-watch-typeahead
jest-watch-yarn-workspaces
watchman
[boolean]
Default: true
Whether to use watchman
for file crawling.