Jest CLI Options
The jest
command line runner has a number of useful options. You can run jest --help
to view all available options. Many of the options shown below can also be used together to run tests exactly the way you want. Every one of Jest's Configuration options can also be specified through the CLI.
Here is a brief overview:
Running from the command lineโ
Run all tests (default):
jest
Run only the tests that were specified with a pattern or filename:
jest my-test #or
jest path/to/my-test.js
Run tests related to changed files based on hg/git (uncommitted files):
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
Run watch mode:
jest --watch #runs jest -o by default
jest --watchAll #runs all tests
Watch mode also enables to specify the name or path to a file to focus on a specific set of tests.
Using with yarnโ
If you run Jest via yarn test
, you can pass the command line arguments directly as Jest arguments.
Instead of:
jest -u -t="ColorPicker"
you can use:
yarn test -u -t="ColorPicker"
Using with npm scriptsโ
If you run Jest via npm test
, you can still use the command line arguments by inserting a --
between npm test
and the Jest arguments.
Instead of:
jest -u -t="ColorPicker"
you can use:
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
Optionsโ
CLI options take precedence over values from the Configuration.
- Using with npm scripts
- Camelcase & dashed args support
- Options
- Reference
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
--init
--json
--outputFile=<filename>
--lastCommit
--listTests
--logHeapUsage
--maxConcurrency=<num>
--maxWorkers=<num>|<string>
--noStackTrace
--notify
--onlyChanged
--passWithNoTests
--projects <path1> ... <pathN>
--reporters
--resetMocks
--restoreMocks
--roots
--runInBand
--runTestsByPath
--setupFilesAfterEnv <path1> ... <pathN>
--showConfig
--silent
--testLocationInResults
--testMatch glob1 ... globN
--testNamePattern=<regex>
--testPathIgnorePatterns=<regex>|[array]
--testPathPattern=<regex>
--testRunner=<path>
--testSequencer=<path>
--testTimeout=<number>
--updateSnapshot
--useStderr
--verbose
--version
--watch
--watchAll
--watchman
Referenceโ
jest <regexForTestFiles>
โ
When you run jest
with an argument, that argument is treated as a regular expression to match against files in your project. It is possible to run test suites by providing a pattern. Only the files that the pattern matches will be picked up and executed. 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
โ
Whether to use the cache. Defaults to true. Disable the cache using --no-cache
.
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
โ
Runs tests related to the current changes and the changes made in the last commit. Behaves similarly to --onlyChanged
.
--changedSince
โ
Runs tests related to the changes since the provided branch or commit hash. If the current branch has diverged from the given branch, then only changes made locally will be tested. Behaves similarly to --onlyChanged
.
--ci
โ
When this option is provided, Jest will assume it is running in a CI environment. This changes the behavior when a new snapshot is encountered. 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
โ
Deletes the Jest cache directory and then exits without running tests. 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
.
Clearing the cache will reduce performance.
--clearMocks
โ
Automatically clear mock calls, instances 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
โ
Forces test results output highlighting even if stdout is not a 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
. The path to a Jest config file specifying how to find and execute tests. If no rootDir
is set in the config, the directory containing the config file is assumed to be the rootDir
for the project. This can also be a JSON-encoded value which Jest will use as configuration.
--coverage[=<boolean>]
โ
Alias: --collectCoverage
. Indicates that test coverage information should be collected and reported in the output. 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
.
Using v8
is considered experimental. This uses V8's builtin code coverage rather than one based on Babel and comes with a few caveats
- Your node version must include
vm.compileFunction
, which was introduced in node 10.10 - Tests needs to run in Node test environment (support for
jsdom
requiresjest-environment-jsdom-sixteen
) - V8 has way better data in the later versions, so using the latest versions of node (v13 at the time of this writing) will yield better results
--debug
โ
Print debugging info about your Jest config.
--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 method receives a list of tests which can be manipulated to exclude tests from running. Especially useful when used in conjunction with a testing infrastructure to filter known broken.
--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
โ
Force Jest to exit after all tests have completed running. This is useful when resources set up by test code cannot be adequately cleaned up.
This feature is an escape-hatch. If Jest doesn't exit at the end of a test run, it means external resources are still being held on to or timers are still pending in your code. It is advised to tear down external resources after each test to make sure Jest can shut down cleanly. You can use --detectOpenHandles
to help track it down.
--help
โ
Show the help information, similar to this page.
--init
โ
Generate a basic configuration file. Based on your project, Jest will ask you a few questions that will help to generate a jest.config.js
file with a short description for each option.
--json
โ
Prints the test results in JSON. This mode will send all other test output and user messages to stderr.
--outputFile=<filename>
โ
Write test results to a file when the --json
option is also specified. The returned JSON structure is documented in testResultsProcessor.
--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
. Specifies the maximum number of workers the worker-pool will spawn for running tests. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases.
For environments with variable CPUs available, you can use percentage based configuration: --maxWorkers=50%
--noStackTrace
โ
Disables stack trace in test results output.
--notify
โ
Activates notifications for test results. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing.
--onlyChanged
โ
Alias: -o
. Attempts to identify which tests to run based on which files have changed in the current repository. 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).
--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.
--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.
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.
--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.
--showConfig
โ
Print your Jest config and then exits.
--silent
โ
Prevent tests from printing messages through the console.
--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 --testPathPattern
, 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.
--testPathPattern=<regex>
โ
A regexp pattern string that is matched against all tests paths before executing the test. On Windows, you will need to use /
as a path separator or escape \
as \\
.
--testRunner=<path>
โ
Lets you specify a custom test runner.
--testSequencer=<path>
โ
Lets you specify a custom test sequencer. Please refer to the documentation of the corresponding configuration property for details.
--testTimeout=<number>
โ
Default timeout of a test in milliseconds. Default value: 5000.
--updateSnapshot
โ
Alias: -u
. Use this flag to re-record every snapshot that fails during this test run. Can be used together with a test suite pattern or with --testNamePattern
to re-record snapshots.
--useStderr
โ
Divert all output to stderr.
--verbose
โ
Display individual test results with the test suite hierarchy.
--version
โ
Alias: -v
. Print the version and exit.
--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
.