Jest CLI Options
jest
命令行运行器拥有诸多有用的选项。 运行jest --help
可以查看所有可用的选项 下面所示选项都可一起使用,以你想要的方式来运行测试。 每一条 Jest 的 配置选项 都可以通过命令行来指定.
大致简述如下:
在命令行运行
运行所有测试(默认)
jest
仅运行符合指定用模板或文件名的测试︰
jest my-test #or
jest path/to/my-test.js
运行基于 hg/git (未提交的文件) 修改的文件的测试︰
jest -o
运行类似 path/to/fileA.js
和 path/to/fileB.js
的测试︰
jest --findRelatedTests path/to/fileA.js path/to/fileB.js
运行匹配特定名称的测试用例(主要是匹配 describe
或 test
的名称)。
jest -t name-of-spec
运行监视模式︰
jest --watch #runs jest -o by default
jest --watchAll #runs all tests
监视模式还能够指定名称或文件路径,从而运行特定的一组测试。
Using with yarn
If you run Jest via yarn test
, you can pass the command line arguments directly as Jest arguments.
旧做法:
jest -u -t="ColorPicker"
现在你可以使用
yarn test -u -t="ColorPicker"
使用npm脚本
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.
旧做法:
jest -u -t="ColorPicker"
现在你可以使用
npm test -- -u -t="ColorPicker"
参数支持驼峰和中横线
Jest supports both camelcase and dashed arg formats. The following examples will have an equal result:
jest --collect-coverage
jest --collectCoverage
参数也可以混合使用
jest --update-snapshot --detectOpenHandles
选项
Note: CLI options take precedence over values from the Configuration.
jest <regexForTestFiles>
--bail
--cache
--changedFilesWithAncestor
--changedSince
--ci
--clearCache
--collectCoverageFrom=<glob>
--colors
--config=<path>
--coverageProvider=<provider>
--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
--roots
--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
参考
jest <regexForTestFiles>
当你在运行 jest
时附加参数,参数会以正则表达式来匹配项目中的文件。 可通过提供的模式来运行测试。 只会选择并运行匹配模式的测试文件。 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
Alias: -b
. Exit the test suite immediately upon n
number of failing test suite. Defaults to 1
.
--cache
是否使用缓存。 默认值为 true。 使用 --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
Runs tests related to the current changes and the changes made in the last commit. 与 --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. 与 --onlyChanged
的行为相似。
--ci
指定该参数时,Jest会认为正在CI环境上运行。 当遇到新的快照时,这会改变原来的行为。 不再是自动的保存新的快照,取而代之的是,它会将测试标记失败,并要求运行Jest时增加--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
. _ 注意:清除缓存将降低性能。_
--collectCoverageFrom=<glob>
A glob pattern relative to rootDir
matching the files that coverage info needs to be collected from.
--colors
即便stdout不是TTY模式, 也要强制高亮显示测试结果。
--config=<path>
或: -c
. The path to a Jest config file specifying how to find and execute tests. 如果在配置中未设置` rootDir </ code>,则假定包含配置文件的目录为项目的 rootDir </ code>。 这也可以是 JSON 编码的值,Jest可以将其设为基本配置。
--coverage[=]`
Alias: --collectCoverage
. 将测试覆盖率信息输出为报告。 Optionally pass <boolean>
to override option set in configuration.
--coverageProvider=<provider>
Indicates which provider should be used to instrument code for coverage. Allowed values are babel
(default) or v8
.
Note that 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
打印关于 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.
--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在所有测试运行完后退出。 对于一些由测试所生成但无法充分清理的资源来说,这是很有用的。 注意︰ 此功能是escape-hatch。 如果Jest在测试运行最后没有退出,那就意味着外部资源还是被占用,又或是计时器还尚在你的代码中待令。 为了确保Jest可以完全关闭,建议你在每个测试后都关闭用到的外部资源。 You can use --detectOpenHandles
to help track it down.
--help
显示帮助信息,类似于本页文档。
--init
生成一个基础配置文件. 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>
通过 — — json
参数可以将测试结果写入到指定文件。 The returned JSON structure is documented in testResultsProcessor.
--lastCommit
Run all tests affected by file changes in the last commit made. 与 --onlyChanged
的行为相似。
--listTests
Lists 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 will run.
--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>
别名︰ -w
。 设定运行测试的最大工作池数目。 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
禁止栈跟踪信息在测试结果输出中。
--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
或: -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).
--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 that 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"
--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.
Note: 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
--setupTestFrameworkScriptFile=<file>
模块路径是可以在每个测试运行前,通过运行一些代码来配置或设置测试框架。 Beware that files imported by the setup script will not be mocked during testing.
--showConfig
输出Jest配置,然后退出。
--silent
阻止所有测试通过控制台输出信息。
--testNamePattern=<regex>
别名︰ -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
.
Note: The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks.
--testLocationInResults
Adds a location
field to test results. Useful if you want to report the location of a test in a reporter.
请注意 column
是从 0 开始,而 line
不是。
{
"column": 4,
"line": 5
}
--testPathPattern=<regex>
在运行测试前,匹配的regexp模式字符串的测试文件路径。 On Windows, you will need to use /
as a path separator or escape \` as
\`.
--testPathIgnorePatterns=[array]
An 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.
--testRunner=<path>
允许你指定自定义测试运行程序。
--testSequencer=<path>
Lets you specify a custom test sequencer. Please refer to the documentation of the corresponding configuration property for details.
--testTimeout=<number>
默认测试超时时间单位为毫秒。 Default value: 5000.
--updateSnapshot
或: -u
. 在运行测试中使用这个参数来重新录制每个失败测试的快照。 还可以和测试套件模式或 --testNamePattern
一起使用,从而重新录制的快照。
--useStderr
转移所有输出到stderr(标准错误输出).
--verbose
层次显示测试套件中每个测试的结果。
--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.
--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 --watchAll=false
to explicitly disable the watch mode. Note that in most CI environments, this is automatically handled for you.
--watchman
Whether to use watchman
for file crawling. 默认为 true
。 Disable using --no-watchman
.