Jest CLI Options
Today we will explore the options that come with Jest's command line interface There are a number of useful command line interface that comes with jest. To view all the available options, you can run jest ?help. Most of the options that are shown below can also be used together to run tests exactly the way you want. Each Jest's Configuration options can also be specified through the CLI.
A brief overview is shown below:
Running from the command line
To Run all tests (default):
Jest
If you only want to run the tests that were specified with a pattern or filename:
jest my-test #or
jest path/to/my-test.js
To run tests related to changed files based on hg/git (uncommitted files):
jest -o
To run tests related to path/to/fileA.js and path/to/fileB.js:
jest --findRelatedTests path/to/fileA.js path/to/fileB.js
To run tests that match this spec name (match against the name in describe or test, basically).
jest -t name-of-spec
To run watch mode:
jest --watch #runs jest -o by default
jest --watchAll #runs all tests
Watch mode also enables you to specify the name or path to a file that you want to focus on a specific set of tests.
Using with yarn
When you run Jest via yarn test, you can pass the command line arguments as Jest arguments directly.
Rather than:
jest -u -t="ColorPicker"
You can also use:
yarn test -u -t="ColorPicker"
Using with npm scripts
If you are running Jest via npm test, you also use the command line arguments by inserting a -- between npm test and Jest arguments.
So instead of:
jest -u -t="ColorPicker"
you will have:
npm test -- -u -t="ColorPicker"
Camelcase & dashed args support
Jest has support for both dashed and camelcase arg formats. The following examples have equal result:
jest --collect-coverage
jest -collectCoverage
Arguments can be mixed as well:
jest --update-snapshot -detectOpenHandles
Options
Note: CLI options will take precedence over values from the Configuration.
jest <regexForTestFiles>- --bail
- --cache
- --changedFilesWithAncestor
- --changedSince
- --ci
- --clearCache
- --collectCoverageFrom=<glob>
- --colors
- --config=<path>
- --coverage
- --debug
- --detectOpenHandles
- --env=<environment>
- --errorOnDeprecated
- --expand
- --findRelatedTests <spaceSeparatedListOfSourceFiles>
- --forceExit
- --help
- --init
- --json
- --outputFile=<filename>
- --lastCommit
- --listTests
- --logHeapUsage
- --maxConcurrency=<num>
- --maxWorkers=<num>|<string>
- --noStackTrace
- --notify
- --onlyChanged
- --passWithNoTests
- --projects <path1> ... <pathN>
- --reporters
- --runInBand
- --runTestsByPath
- --setupTestFrameworkScriptFile=<file>
- --showConfig
- --silent
- --testNamePattern=<regex>
- --testLocationInResults
- --testPathPattern=<regex>
- --testPathIgnorePatterns=[array]
- --testRunner=<path>
- --testSequencer=<path>
- --testTimeout=<number>
- --updateSnapshot
- --useStderr
- --verbose
- --version
- --watch
- --watchAll
- --watchman
Reference
jest <regexForTestFiles>
Whenever you run jest with an argument, that argument will be treated as a regular expression to match against files in your project. Running test suites by providing a pattern is possible. Only the files that the pattern matches are picked up and executed. Based on your terminal, you may have to quote this argument: jest "my.*(complex)?pattern". On Windows, you should use / as a path separator or escape \ as \\.
--bail
Alias: -b. Will exit the test suite immediately upon n number of failing test suite. The default value is 1.
--cache
This determines whether you should use the cache. It defaults to true. You can disable the cache using --no-cache. Note: the cache should only be disabled when you are experiencing caching related problems. On average, disabling the cache will make Jest at least two times slower.
Whenever you want to inspect the cache, you can use --showConfig and then look at the cacheDirectory value. When you need to clear the cache, you can use --clearCache.
--changedFilesWithAncestor
This will run tests related to the current changes and the changes made in the last commit. It behaves similarly to --onlyChanged.
--changedSince
This runs tests related to the changes since the provided branch. whenever the current branch has diverged from the given branch, then only changes made locally are tested. It behaves similarly to --onlyChanged.
--ci
If you provide this option, Jest assumes it is running in a CI environment. This will change the behavior when a new snapshot is encountered. Instead of the regular behavior where a new snapshot is automatically stored, it fails the test and then require Jest to be run with --updateSnapshot.
--clearCache
This will delete the Jest cache directory and then exits without running tests. It will delete cacheDirectory if the option is passed, or it will delete Jest's default cache directory. The default cache directory may be found by calling jest --showConfig. Note: clearing the cache reduces performance.
--collectCoverageFrom=<glob>
A glob pattern relative to the matching files that coverage info needs to be collected from.
--colors
This forces test results output highlighting even if stdout is not a TTY.
--config=<path>
Alias: -c. The path to a Jest config file that specifies how to find and execute tests. If you set no rootDir in the config, the directory that contains the config file is assumed to be the rootDir for the project. This can be a JSON-encoded value which Jest uses as configuration.
--coverage
This indicates that test coverage information should be collected and reported in the output. This option is aliased by -collectCoverage as well.
--debug
This will print debugging info about your Jest config.
--detectOpenHandles
This will attempt to collect and print open handles that are preventing Jest from exiting cleanly. You should 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, will make tests run serially. It is implemented using async_hooks, so it will only work in Node 8 and newer. There is a significant performance penalty that comes with this option, thus it should be used for debugging only.
--env=<environment>
This is the test environment used for all tests. You can use this to point to any file or node module. Examples: jsdom, node or path/to/my-environment.js.
--errorOnDeprecated
This will make calling deprecated APIs throw helpful error messages. It useful for easing the upgrade process.
--expand
Alias: -e. You should use this flag to show full diffs and errors instead of a patch.
--findRelatedTests <spaceSeparatedListOfSourceFiles>
This will find and then run the tests that cover a space separated list of source files that were passed in as arguments. It is useful for pre-commit hook integration to run the minimal amount of tests necessary. This can be used together with --coverage to include a test coverage for the source files, there is no duplicate --collectCoverageFrom arguments needed.
--forceExit
This will force Jest to exit after all tests have completed running. This is useful when resources that are set up by test code cannot be adequately cleaned up. Note: This feature will be an escape-hatch. In the case where Jest doesn't exit at the end of a test run, what this means is that external resources are still being held on to or you still have pending timers in your code. It is advised that you tear down external resources after each test to make sure Jest can shut down cleanly. --detectOpenHandles can be used you to help track it down.
--help
This will show the help information.
--init
This will generate a basic configuration file. Based on your own project, Jest asks you a few questions that helps to generate a jest.config.js file with a short description for each option.
--json
This will print the test results in JSON. This mode sends all other test output and user messages to stderr.
--outputFile=<filename>
This will write test results to a file when the --json option is also specified. The returned JSON structure will be documented in testResultsProcessor.
--lastCommit
This will run all tests affected by file changes in the last commit made. It behaves similarly to --onlyChanged.
--listTests
This will list all tests as JSON that Jest will run given the arguments, and exits. This can be used together with --findRelatedTests to know which tests Jest runs.
--logHeapUsage
This will log the heap usage after every test. It is useful to debug memory leaks. You should use together with --runInBand and --expose-gc in node.
--maxConcurrency=<num>
This will prevent Jest from executing more than the specified amount of tests at the same time. It will only affect tests that use test.concurrent.
--maxWorkers=<num>|<string>
Alias: -w. This will specify the maximum number of workers the worker-pool will spawn for running tests. In single run mode, this will default to the number of the cores available on your machine minus one for the main thread. In the watch mode, this will default to half of the available cores on your machine to ensure Jest is unobtrusive and will not grind your machine to a halt. It can be useful to adjust this in resource limited environments like CIs but the defaults has to be adequate for most use-cases.
For environments that have variable CPUs available, it is possible to use percentage based configuration: --maxWorkers=50%
--noStackTrace
This will disable stack trace in test results output.
--notify
This will activate notifications for test results. It is useful when you don't want your consciousness to be able to focus on anything except JavaScript testing.
--onlyChanged
Alias: -o. This will attempt to identify which tests to run based on which files have changed in the current repository. It will only work if you're running tests in a git/hg repository at the moment and it requires a static dependency graph (ie. no dynamic requires).
--passWithNoTests
This allows the test suite to pass when no files are found.
--projects <path1> ... <pathN>
This will run tests from one or more projects, that are found in the specified paths; it also takes path globs. This option will be 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 are run.
--reporters
This will run tests with specified reporters. The reporter options are not available via CLI. Here is an example with multiple reporters:
jest --reporters="default" --reporters="jest-junit"
runInBand
Alias: -i. This will run all tests serially in the current process, instead of creating a worker pool of child processes that run tests. It can be useful for debugging.
--runTestsByPath
This will only run the tests that were specified with their exact paths.
It should be noted that the default regex matching works fine on small runs, but will become slow if provided with multiple patterns and/or against a lot of tests. This option will replace the regex matching logic and by that optimizes the time it takes Jest to filter specific test files
--setupTestFrameworkScriptFile=<file>
The path to a module that will run some code to configure or set up the testing framework before each test. Beware that files that are imported by the setup script will not be mocked during testing.
--showConfig
This will print your Jest config and then it will exit.
--silent
This will prevent tests from printing messages through the console.
--testNamePattern=<regex>
Alias: -t. This will only run tests with a name that matches the regex. For instance, suppose you only want to run tests related to authorization which will have names like "GET /api/posts with auth", then you can utilize jest -t=auth.
It should be noted that the regex is matched against the full name, this is a combination of the test name and all its surrounding describe blocks.
--testLocationInResults
This will add a location field to test results. It is useful if you want to report the location of a test in a reporter.
It should be noted that column is 0-indexed whereas line is not.
{
"column": 4,
"line": 5
}
--testPathPattern=<regex>
This is a regexp pattern string that is matched against all tests paths before executing the test. On Windows, you have to use / as a path separator or escape \ as \\.
--testPathIgnorePatterns=[array]
This is an array of regexp pattern strings that is tested against all tests paths before executing the test. This is contrary to --testPathPattern, it only runs those test with a path that does not match with the provided regexp expressions.
--testRunner=<path>
This enables you specify a custom test runner.
--testSequencer=<path>
This enables you specify a custom test sequencer.
--testTimeout=<number>
This is the default timeout of a test in milliseconds. Its default value is 5000.
--updateSnapshot
Alias: -u. You should use this flag to re-record every snapshot that fails during this test run. It can be used together with a test suite pattern or together with --testNamePattern to re-record snapshots.
--useStderr
This will divert all output to stderr.
--verbose
This will display individual test results with the test suite hierarchy.
--version
Alias: -v. this will print the version and exit.
--watch
This will watch files for changes and then rerun tests related to changed files. In the case where you want to re-run all tests when a file has changed, you should use the --watchAll option instead.
--watchAll
This will watch files for changes and rerun all tests when something changes. In the case where you want to re-run only the tests that depend on the changed files, you should use the --watch option.
--watchman
This determines whether to use watchman for file crawling. The default value is true. You can disable it using --no-watchman.
Previous:
Configuring Jest: Setup Options and Customization.
Next:
Jest Architecture: Understanding Framework Components.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/jest/Jest-cli-options.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics