Опції командного рядка
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 # або
jest path/to/my-test.js
Запустити тести що мають відношення до змінених файлів (файли які не були закомічені):
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 # запускає "jest -o" за замовчуванням
jest --watchAll # запускає всі тести
Режим спостереження також дозволяє вказувати ім’я або шлях до файлу, щоб сфокусуватися на певному наборі тестів.
Використання з менеджером пакетів
Якщо ви використовуєте Jest з вашим менеджером пакетів, ви все ще можете передати аргументи командного рядка напряму, як аргументи Jest.
Замість:
jest -u -t="ColorPicker"
ви можете використовувати:
- npm
- Yarn
- pnpm
- Bun
npm test -- -u -t="ColorPicker"
yarn test -u -t="ColorPicker"
pnpm test -u -t="ColorPicker"
bun run test -u -t "ColorPicker"
Camelcase & dashed args support
Jest підтримує аргументи в верблюдячому та шашличному регістрах. Наступні приклади матимуть однаковий результат:
jest --collect-coverage
jest --collectCoverage
Аргументи також можуть бути змішаними:
jest --update-snapshot --detectOpenHandles
Параметри
CLI options take precedence over values from the Configuration.
- Camelcase & dashed args support
- Параметри
- Довідка
jest <regexForTestFiles>--bail[=<n>]--cache--changedFilesWithAncestor--changedSince--ci--clearCache--clearMocks--collectCoverageFrom=<glob>--colors--config=<path>--coverage[=<boolean>]--coverageDirectory=<path>--coverageProvider=<provider>--debug--detectOpenHandles--env=<environment>--errorOnDeprecated--expand--filter=<file>--findRelatedTests <spaceSeparatedListOfSourceFiles>--forceExit--help--ignoreProjects <project1> ... <projectN>--injectGlobals--json--lastCommit--listTests--logHeapUsage--maxConcurrency=<num>--maxWorkers=<num>|<string>--noStackTrace--notify--onlyChanged--onlyFailures--openHandlesTimeout=<milliseconds>--outputFile=<filename>--passWithNoTests--projects <path1> ... <pathN>--randomize--reporters--resetMocks--restoreMocks--roots--runInBand--runTestsByPath--seed=<num>--selectProjects <project1> ... <projectN>--setupFilesAfterEnv <path1> ... <pathN>--shard--showConfig--showSeed--silent--testEnvironmentOptions=<json string>--testLocationInResults--testMatch glob1 ... globN--testNamePattern=<regex>--testPathIgnorePatterns=<regex>|[array]--testPathPatterns=<regex>--testRunner=<path>--testSequencer=<path>--testTimeout=<number>--updateSnapshot--useStderr--verbose--version--waitForUnhandledRejections--watch--watchAll--watchman--workerThreads
Довідка
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.
Кеш варто відключати лише в тоді, коли ви маєте проблеми, пов’язані з кешем. В середньому, відключення кешу робить Jest щонайменше вдвічі повільнішим.
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.
Очищення кешу знизить продуктивність.
--clearMocks
Автоматично очищує імітації викликів, екземплярів, контекстів і результатів перед кожним тестом. 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.
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>
Вказує, який постачальник повинен використовуватися для перевірки покриття коду. 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. This option has a significant performance penalty and should only be used for debugging.
--env=<environment>
The test environment used for all tests. This can point to any file or node module. 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. Use this flag to show full diffs and errors instead of a patch.
--filter=<file>
Path to a module exporting a filtering function. 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.
// 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>
Find and run the tests that cover a space separated list of source files that were passed in as arguments. Useful for pre-commit hook integration to run the minimal amount of tests necessary. Can be used together with --coverage to include a test coverage for the source files, no duplicate --collectCoverageFrom arguments needed.
--forceExit
Змусити Jest примусово завершувати роботу після виконання всіх тестів. Це може бути корисно, якщо ресурси, підготовлені тестовим кодом, не можуть бути коректно очищені.
Ця опція - це обхідний механізм. Якщо 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);
});
This option is only supported using the default jest-circus test runner.
--json
Prints the test results in JSON. This mode will send all other test output and user messages to stderr.
--lastCommit
Run all tests affected by file changes in the last commit made. Behaves similarly to --onlyChanged.
--listTests
Lists all test files that Jest will run given the arguments, and exits.
--logHeapUsage
Logs the heap usage after every test. Useful to debug memory leaks. Use together with --runInBand and --expose-gc in node.
--maxConcurrency=<num>
Prevents Jest from executing more than the specified amount of tests at the same time. Only affects tests that use test.concurrent.
--maxWorkers=<num>|<string>
Alias: -w. Вказує максимальну кількість робочих процесів, які можуть бути створені під час виконання тестів. В одиничному режимі, це значення за замовчуванням дорівнює кількості ядер доступних на вашому комп'ютері мінус один для головного процесу. У режимі перегляду, це за замовчуванням половина доступних ядер на вашому комп’ютері для того, щоб 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. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing. To display the notifications Jest needs the node-notifier package, which must be installed separately.
--onlyChanged
Alias: -o. Пробує визначити, які тести запускати, на основі того, які файли були змінені в поточному репозиторії. Only works if you're running tests in a git/hg repository at the moment and requires a static dependency graph (ie. no dynamic requires).
--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
Allows the test suite to pass when no files are found.
--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.
If configuration files are found in the specified paths, all projects specified within those configuration files will be run.
--randomize
Перемішує порядок тестів всередині файлу. Перемішування базується на тестових даних. See --seed=<num> for more info.
Тестове значення відображується, коли встановлено цей параметр. Equivalent to setting the CLI option --showSeed.
jest --randomize --seed 1234
This option is only supported using the default jest-circus test runner.
--reporters
Run tests with specified reporters. Reporter options are not available via CLI. Example with multiple reporters:
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
A list of paths to directories that Jest should use to search for files in.
--runInBand
Alias: -i. Run all tests serially in the current process, rather than creating a worker pool of child processes that run tests. This can be useful for debugging.
--runTestsByPath
Run only the tests that were specified with their exact paths. Це дозволяє їм уникнути перетворення в регулярний вираз і його порівняння з кожним файлом.
Для прикладу, візьмемо наступну файлову структуру:
__tests__
└── t1.test.js # test
└── t2.test.js # test
При запуску з шаблоном, жоден тест не знаходиться:
jest --runTestsByPath __tests__/t
Вивід:
No tests found
Однак, передача точного шляху призведе до виконання лише заданого тесту:
jest --runTestsByPath __tests__/t1.test.js
Вивід:
PASS __tests__/t1.test.js
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
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
Забороняє тестам виводити повідомлення в консоль.
--showSeed
Виводить тестові дані в підсумковому звіті про тестування. See --seed=<num> for the details.
Також можна встановити в конфігурації. 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.
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. 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.
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. Print the version and exit.
--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
Watch files for changes and rerun tests related to changed files. If you want to re-run all tests when a file has changed, use the --watchAll option instead.
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
Watch files for changes and rerun all tests when something changes. If you want to re-run only the tests that depend on the changed files, use the --watch option.
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.
This is experimental feature. See the workerThreads configuration option for more details.