Перейти к основной части
Version: 30.0

Опции командной строки Jest

The jest command line runner has a number of useful options. You can run jest --help to view all available options. Многие из них могут использоваться совместно друг с другом для запуска тестов именно так, как вы хотите. Every one of Jest's Configuration options can also be specified through the CLI.

Вот их краткий обзор:

Запуск из командной строки

Запуск всех тестов (по умолчанию):

jest

Запустить только тесты по шаблону или по имени файла:

jest my-test #or
jest path/to/my-test.js

Выполнить тесты, связанные с измененными файлами, отраженными в hg/git (uncommitted файлы):

jest -o

Run tests related to path/to/fileA.js and path/to/fileB.js:

jest --findRelatedTests path/to/fileA.js path/to/fileB.js

Run tests that match this spec name (match against the name in describe or test, basically).

jest -t name-of-spec

Запуск в режиме отслеживания изменений:

jest --watch #runs jest -o by default
jest --watchAll #runs all tests

Режим отслеживания изменений также позволяет указать имя или путь к файлу, чтобы сфокусироваться на выполнении определенного набора тестов.

Using with package manager

If you run Jest via your package manager, you can still pass the command line arguments directly as Jest arguments.

Вместо:

jest -u -t="ColorPicker"

вы можете использовать:

npm test -- -u -t="ColorPicker"

Camelcase & dashed args support

Jest supports both camelcase and dashed arg formats. The following examples will have an equal result:

jest --collect-coverage
jest --collectCoverage

Arguments can also be mixed:

jest --update-snapshot --detectOpenHandles

Параметры

note

CLI options take precedence over values from the Configuration.


Справка

jest <regexForTestFiles>

When you run jest with an argument, that argument is treated as a regular expression to match against files in your project. Это позволяет запустить наборы тестов, предоставляя шаблон. Будут выбраны и выполнены только те файлы, которые соответствуют шаблону. Depending on your terminal, you may need to quote this argument: jest "my.*(complex)?pattern". On Windows, you will need to use / as a path separator or escape \ as \\.

--bail[=<n>]

Alias: -b. Exit the test suite immediately upon n number of failing test suite. Defaults to 1.

--cache

Нужно ли использовать кэш. По умолчанию используется значение true. Disable the cache using --no-cache.

caution

The cache should only be disabled if you are experiencing caching related problems. On average, disabling the cache makes Jest at least two times slower.

If you want to inspect the cache, use --showConfig and look at the cacheDirectory value. If you need to clear the cache, use --clearCache.

--changedFilesWithAncestor

Запускает тесты для файлов с текущими изменениями, а также для файлов, которые были измененны в предыдущем коммите. Behaves similarly to --onlyChanged.

--changedSince

Запускает тесты, которые затрагивают изменения в указанной ветке или коммите. Если рабочая ветка не совпадает с указанной, тогда будут протестированны только локальные изменения. Behaves similarly to --onlyChanged.

--ci

При указании этой опции Jest будет считать, что выполняется в CI-среде. В этом случае меняется поведение при обнаружении новых тестов со снимками. Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with --updateSnapshot.

--clearCache

Удаляет директорию с кэшом Jest и завершает процесс без запуска тестов. Will delete cacheDirectory if the option is passed, or Jest's default cache directory. The default cache directory can be found by calling jest --showConfig.

caution

Clearing the cache will reduce performance.

--clearMocks

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.

--collectCoverageFrom=<glob>

A glob pattern relative to rootDir matching the files that coverage info needs to be collected from.

--colors

Принудительно включает подсветку вывода результатов тестирования, даже если stdout – не TTY.

note

Alternatively you can set the environment variable FORCE_COLOR=true to forcefully enable or FORCE_COLOR=false to disable colorized output. The use of FORCE_COLOR overrides all other color support checks.

--config=<path>

Alias: -c. Путь к файлу конфигурации Jest, в котором указывается где искать и как выполнять тесты. If no rootDir is set in the config, the directory containing the config file is assumed to be the rootDir for the project. Для задания данной опции может быть использовано JSON-значение, которое Jest будет использовать как конфигурацию.

--coverage[=<boolean>]

Alias: --collectCoverage. Указывает, что следует собирать и отображать информацию о тестовом покрытии. Optionally pass <boolean> to override option set in configuration.

--coverageDirectory=<path>

The directory where Jest should output its coverage files.

--coverageProvider=<provider>

Indicates which provider should be used to instrument code for coverage. Allowed values are babel (default) or v8.

--debug

Выводит информацию о файле конфигурации Jest.

--detectOpenHandles

Attempt to collect and print open handles preventing Jest from exiting cleanly. Use this in cases where you need to use --forceExit in order for Jest to exit to potentially track down the reason. This implies --runInBand, making tests run serially. Implemented using async_hooks. Эта опция существенно снижает производительность и поэтому рекоммендуется использовать её только при отладке.

--env=<environment>

Тестовое окружение, используемое для всех тестов. Может указывать на любой node-модуль или файл. Examples: jsdom, node or path/to/my-environment.js.

--errorOnDeprecated

Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.

--expand

Alias: -e. Используйте этот флаг, чтобы отображать полноценные diff и сообщения об ошибках вместо патчей.

--filter=<file>

Путь к модулю, экспортирующему функцию фильтрации. This asynchronous function receives a list of test paths which can be manipulated to exclude tests from running and must return an object with shape { filtered: Array<string> } containing the tests that should be run by Jest. Especially useful when used in conjunction with a testing infrastructure to filter known broken tests.

my-filter.js
// This filter when applied will only run tests ending in .spec.js (not the best way to do it, but it's just an example):
const filteringFunction = testPath => testPath.endsWith('.spec.js');

module.exports = testPaths => {
const allowedPaths = testPaths.filter(filteringFunction); // ["path1.spec.js", "path2.spec.js", etc]

return {
filtered: allowedPaths,
};
};

--findRelatedTests <spaceSeparatedListOfSourceFiles>

Запускает тесты, которые покрывают список файлов, переданных в качестве параметров через пробел. Эту опцию удобно использовать в связке с pre-commit хуком, так как она будет запускать только минимально необходимое количество тестов. Can be used together with --coverage to include a test coverage for the source files, no duplicate --collectCoverageFrom arguments needed.

--forceExit

Вынуждает Jest закончить исполнение после того, как все тесты завершены. Полезно в случаях, когда ресурсы, созданные в целях тестирования, не могут быть освобождены надлежащим образом.

caution

This feature is an escape-hatch. Если Jest не заканчивает выполнение после того, как тесты завершились, это означает, что внешние ресурсы по-прежнему удерживаются или таймеры ожидают завершения. Настоятельно рекомендуется высвобождать внешние ресурсы после завершения каждого отдельного теста для того, чтобы Jest успешно мог завершить выполнение. You can use --detectOpenHandles to help track it down.

--help

Показать справку, схожую с данной страницей.

--ignoreProjects <project1> ... <projectN>

Ignore the tests of the specified projects. Jest uses the attribute displayName in the configuration to identify each project. If you use this option, you should provide a displayName to all your projects.

--injectGlobals

Insert Jest's globals (expect, test, describe, beforeEach etc.) into the global environment. If you set this to false, you should import from @jest/globals, e.g.

import {expect, jest, test} from '@jest/globals';

jest.useFakeTimers();

test('some test', () => {
expect(Date.now()).toBe(0);
});
note

This option is only supported using the default jest-circus test runner.

--json

Выводит результаты в формате JSON. В этом режиме весь вывод тестов и пользовательских сообщений будет направлен в stderr.

--lastCommit

Выполнит все тесты, которые были связаны с изменёнными файлами в последнем коммите. Behaves similarly to --onlyChanged.

--listTests

Lists all test files that Jest will run given the arguments, and exits.

--logHeapUsage

Заносит в журнал данные об использовании динамической области после каждого теста. Полезно для выявления утечек памяти. Use together with --runInBand and --expose-gc in node.

--maxConcurrency=<num>

Приостанавливает Jest от выполнения большего количества тестов одновременно, чем указано. Only affects tests that use test.concurrent.

--maxWorkers=<num>|<string>

Alias: -w. Задает максимальное количество рабочих потоков, выделяемое при выполнении тестов. В одиночном режиме прогона тестов, данный параметр будет равен количеству ядер, доступных на вашем компьютере минус 1 ядро, на котором запущен главный поток выполнения. В режиме наблюдения за изменениями файлов (watch mode), данный параметр будет равен половине от доступного количества ядер ПК, во избежание фризов системы и чрезмерного потребления ресурсов ПК Jest'ом. Может быть полезно настроить этот параметр в средах выполнения кода с ограниченными ресурсами, например в CI средах. Значение по умолчанию должно быть приемлемым для остальных вариантов использования.

For environments with variable CPUs available, you can use percentage based configuration: --maxWorkers=50%

--noStackTrace

Отключает отображение трассирования стека при выводе результатов тестов.

--notify

Activates native OS notifications for test results. Удобно, когда вы не хотите акцентировать всё свое внимание на тестировании JavaScript. To display the notifications Jest needs the node-notifier package, which must be installed separately.

--onlyChanged

Alias: -o. Run only tests with a name that matches the regex. For example, suppose you want to run only tests related to authorization which will have names like "GET /api/posts with auth", then you can use jest -t=auth.

--onlyFailures

Alias: -f. Run tests that failed in the previous execution.

--openHandlesTimeout=<milliseconds>

When --detectOpenHandles and --forceExit are disabled, Jest will print a warning if the process has not exited cleanly after this number of milliseconds. A value of 0 disables the warning. Defaults to 1000.

--outputFile=<filename>

Write test results to a file when the --json option is also specified. The returned JSON structure is documented in testResultsProcessor.

--passWithNoTests

Разрешает успешно завершиться прогону тестов, даже если ни одного теста не было обнаружено.

--projects <path1> ... <pathN>

Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the projects configuration option.

note

If configuration files are found in the specified paths, all projects specified within those configuration files will be run.

--randomize

Shuffle the order of the tests within a file. The shuffling is based on the seed. See --seed=<num> for more info.

Seed value is displayed when this option is set. Equivalent to setting the CLI option --showSeed.

jest --randomize --seed 1234
note

This option is only supported using the default jest-circus test runner.

--reporters

Запуск тестов с указанными генераторами отчетов. Reporter options are not available via CLI. Пример с несколькими генераторами отчетов:

jest --reporters="default" --reporters="jest-junit"

--resetMocks

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.

--restoreMocks

Automatically restore mock state and implementation 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.

--roots

Список путей к директориями, в которых Jest должен искать файлы с тестами.

--runInBand

Alias: -i. Последовательно выполняет все тесты в текущем процессе вместо создания пула дочерних рабочих процессов, которые выполняют тесты. Может быть полезно для отладки.

--runTestsByPath

Запускает тесты, к которым указаны конкретные пути. This avoids converting them into a regular expression and matching it against every single file.

For example, given the following file structure:

__tests__
└── t1.test.js # test
└── t2.test.js # test

When ran with a pattern, no test is found:

jest --runTestsByPath __tests__/t

Output:

No tests found

However, passing an exact path will execute only the given test:

jest --runTestsByPath __tests__/t1.test.js

Output:

PASS __tests__/t1.test.js
tip

The default regex matching works fine on small runs, but becomes slow if provided with multiple patterns and/or against a lot of tests. This option replaces the regex matching logic and by that optimizes the time it takes Jest to filter specific test files.

--seed=<num>

Sets a seed value that can be retrieved in a test file via jest.getSeed(). The seed value must be between -0x80000000 and 0x7fffffff inclusive (-2147483648 (-(2 ** 31)) and 2147483647 (2 ** 31 - 1) in decimal).

jest --seed=1324
tip

If this option is not specified Jest will randomly generate the value. You can use the --showSeed flag to print the seed in the test report summary.

Jest uses the seed internally for shuffling the order in which test suites are run. If the --randomize option is used, the seed is also used for shuffling the order of tests within each describe block. When dealing with flaky tests, rerunning with the same seed might help reproduce the failure.

--selectProjects <project1> ... <projectN>

Run the tests of the specified projects. Jest uses the attribute displayName in the configuration to identify each project. If you use this option, you should provide a displayName to all your projects.

--setupFilesAfterEnv <path1> ... <pathN>

A list of paths to modules that run some code to configure or to set up the testing framework before each test. Beware that files imported by the setup scripts will not be mocked during testing.

--shard

The test suite shard to execute in a format of (?<shardIndex>\d+)/(?<shardCount>\d+).

shardIndex describes which shard to select while shardCount controls the number of shards the suite should be split into.

shardIndex and shardCount have to be 1-based, positive numbers, and shardIndex has to be lower than or equal to shardCount.

When shard is specified the configured testSequencer has to implement a shard method.

For example, to split the suite into three shards, each running one third of the tests:

jest --shard=1/3
jest --shard=2/3
jest --shard=3/3

--showConfig

Печатает Jest конфигурацию и затем выходит.

--showSeed

Prints the seed value in the test report summary. See --seed=<num> for the details.

Can also be set in configuration. See showSeed.

--silent

Запрещает тестам печать сообщений в консоль.

--testEnvironmentOptions=<json string>

A JSON string with options that will be passed to the testEnvironment. The relevant options depend on the environment.

--testLocationInResults

Adds a location field to test results. Useful if you want to report the location of a test in a reporter.

note

In the resulting object column is 0-indexed while line is not.

{
"column": 4,
"line": 5
}

--testMatch glob1 ... globN

The glob patterns Jest uses to detect test files. Please refer to the testMatch configuration for details.

--testNamePattern=<regex>

Alias: -t. Запускает только те тесты, наименование которых подпадает под шаблон регулярного выражения. For example, suppose you want to run only tests related to authorization which will have names like 'GET /api/posts with auth', then you can use jest -t=auth.

tip

The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks.

--testPathIgnorePatterns=<regex>|[array]

A single or array of regexp pattern strings that are tested against all tests paths before executing the test. Contrary to --testPathPatterns, it will only run those tests with a path that does not match with the provided regexp expressions.

To pass as an array use escaped parentheses and space delimited regexps such as \(/node_modules/ /tests/e2e/\). Alternatively, you can omit parentheses by combining regexps into a single regexp like /node_modules/|/tests/e2e/. These two examples are equivalent.

--testPathPatterns=<regex>

Строка регулярного выражения, которая противопоставляется всем путям тестов перед выполнением. On Windows, you will need to use / as a path separator or escape \ as \\.

--testRunner=<path>

Позволяет указать сторонний исполнитель тестов.

--testSequencer=<path>

Lets you specify a custom test sequencer. Please refer to the testSequencer configuration for details.

--testTimeout=<number>

Default timeout of a test in milliseconds. Default value: 5000.

--updateSnapshot

Alias: -u. Используйте этот флаг, чтобы повторно сохранять каждый снимок, который проваливается при исполнении тестов. Can be used together with a test suite pattern or with --testNamePattern to re-record snapshots.

--useStderr

Отображает результаты индивидуальных тестов в тестовой иерархии.

--verbose

Отображает результаты отдельных в иерархии набора тестов.

--version

Alias: -v. Печатает текущую версию и выходит.

--waitForUnhandledRejections

Gives one event loop turn to handle rejectionHandled, uncaughtException or unhandledRejection.

Without this flag Jest may report false-positive errors (e.g. actually handled rejection reported) or not report actually unhandled rejection (or report it for different test case).

This option may add a noticeable overhead for fast test suites.

--watch

Наблюдает за изменениями в файлах и перезапускает тесты связанные с измененными файлами. If you want to re-run all tests when a file has changed, use the --watchAll option instead.

tip

Use --no-watch (or --watch=false) to explicitly disable the watch mode if it was enabled using --watch. In most CI environments, this is automatically handled for you.

--watchAll

Наблюдает за изменениями в файлах и перезапускает тесты, если что-то изменяется. If you want to re-run only the tests that depend on the changed files, use the --watch option.

tip

Use --no-watchAll (or --watchAll=false) to explicitly disable the watch mode if it was enabled using --watchAll. In most CI environments, this is automatically handled for you.

--watchman

Whether to use watchman for file crawling. Defaults to true. Disable using --no-watchman.

--workerThreads

Whether to use worker threads for parallelization. Child processes are used by default.

caution

This is experimental feature. See the workerThreads configuration option for more details.