Skip to main content
Version: 29.7

Jest CLI 选项

jest 命令行运行程序有许多有用的选项。你可以运行 jest --help 查看所有可用选项。下面显示的许多选项也可以一起使用,以完全按照你想要的方式运行测试。Jest 的每一个 配置 选项也可以通过 CLI 指定。

¥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):



¥Run only the tests that were specified with a pattern or filename:

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

基于 hg/git(未提交的文件)运行与更改的文件相关的测试:

¥Run tests related to changed files based on hg/git (uncommitted files):

jest -o

运行与 path/to/fileA.jspath/to/fileB.js 相关的测试:

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

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

运行与此规范名称匹配的测试(基本上与 describetest 中的名称匹配)。

¥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 package manager

如果你通过包管理器运行 Jest,你仍然可以直接将命令行参数作为 Jest 参数传递。

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


¥Instead of:

jest -u -t="ColorPicker"


¥you can use:

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


¥Camelcase & dashed args support

Jest 支持驼峰式和虚线参数格式。以下示例将具有相同的结果:

¥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




CLI 选项优先于 配置 中的值。

¥CLI options take precedence over values from the Configuration.



jest <regexForTestFiles>

当你使用参数运行 jest 时,该参数将被视为正则表达式以与项目中的文件进行匹配。可以通过提供模式来运行测试套件。只有模式匹配的文件才会被拾取并执行。根据你的终端,你可能需要引用此参数:jest "my.*(complex)?pattern"。在 Windows 上,你需要使用 / 作为路径分隔符或将 \ 转义为 \\

¥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 \\.


别名:-b。当 n 个测试套件失败时,立即退出测试套件。默认为 1

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


是否使用缓存。默认为 true。使用 --no-cache 禁用缓存。

¥Whether to use the cache. Defaults to true. Disable the cache using --no-cache.


仅当你遇到与缓存相关的问题时才应禁用缓存。平均而言,禁用缓存会使 Jest 至少慢两倍。

¥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.

如果你想检查缓存,请使用 --showConfig 并查看 cacheDirectory 值。如果需要清除缓存,请使用 --clearCache

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


运行与当前更改和上次提交中所做的更改相关的测试。行为与 --onlyChanged 类似。

¥Runs tests related to the current changes and the changes made in the last commit. Behaves similarly to --onlyChanged.


运行与自提供的分支或提交哈希以来的更改相关的测试。如果当前分支与给定分支有分歧,则仅测试本地所做的更改。行为与 --onlyChanged 类似。

¥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.


当提供此选项时,Jest 将假设它在 CI 环境中运行。这会改变遇到新快照时的行为。与自动存储新快照的常规行为不同,它会使测试失败并要求 Jest 使用 --updateSnapshot 运行。

¥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.


删除 Jest 缓存目录,然后退出而不运行测试。如果通过该选项,将删除 cacheDirectory,或者 Jest 的默认缓存目录。默认的缓存目录可以通过调用 jest --showConfig

¥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.


每次测试前自动清除模拟调用、实例、上下文和结果。相当于每次测试前调用 jest.clearAllMocks()。这不会删除可能已提供的任何模拟实现。

¥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.


相对于 rootDir 的 glob 模式与需要从中收集覆盖率信息的文件相匹配。

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


即使 stdout 不是 TTY,也强制测试结果输出高亮。

¥Forces test results output highlighting even if stdout is not a TTY.


或者,你可以设置环境变量 FORCE_COLOR=true 强制启用或设置 FORCE_COLOR=false 禁用彩色输出。FORCE_COLOR 的使用会覆盖所有其他颜色支持检查。

¥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.


别名:-c。Jest 配置文件的路径,指定如何查找和执行测试。如果配置中未设置 rootDir,则包含配置文件的目录将被假定为项目的 rootDir。这也可以是 Jest 将用作配置的 JSON 编码值。

¥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.


别名:--collectCoverage。指示应收集测试覆盖率信息并在输出中报告。(可选)传递 <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.


Jest 应输出其覆盖范围文件的目录。

¥The directory where Jest should output its coverage files.


指示应使用哪个提供商来检测代码的覆盖范围。允许的值为 babel(默认)或 v8

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


打印有关 Jest 配置的调试信息。

¥Print debugging info about your Jest config.


尝试收集并打印打开的句柄,以防止 Jest 干净退出。如果你需要使用 --forceExit 以便 Jest 退出以找出可能的原因,请使用此选项。这意味着 --runInBand,使测试串行运行。使用 async_hooks 实现。此选项会显着降低性能,因此只能用于调试。

¥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.



¥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.


让调用已弃用的 API 抛出有用的错误消息。对于简化升级过程很有用。

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



¥Alias: -e. Use this flag to show full diffs and errors instead of a patch.


导出过滤函数的模块的路径。该异步函数接收一个测试路径列表,可以通过返回形状为 { filtered: Array<{ test: string }> } 的对象来操作该列表以排除测试运行。当与测试基础设施结合使用来过滤已知的损坏测试时特别有用,例如

¥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 by returning an object with shape { filtered: Array<{ test: string }> }. Especially useful when used in conjunction with a testing infrastructure to filter known broken tests, e.g.

module.exports = testPaths => {
const allowedPaths = testPaths
.map(test => ({test})); // [{ test: "path1.spec.js" }, { test: "path2.spec.js" }, etc]

return {
filtered: allowedPaths,

--findRelatedTests <spaceSeparatedListOfSourceFiles>

查找并运行覆盖作为参数传入的空格分隔的源文件列表的测试。对于预提交钩子集成非常有用,可以运行最少量的必要测试。可以与 --coverage 一起使用以包含源文件的测试覆盖率,不需要重复的 --collectCoverageFrom 参数。

¥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.


所有测试完成运行后强制 Jest 退出。当无法充分清理测试代码设置的资源时,这非常有用。

¥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.


此功能是一个应急方案。如果 Jest 在测试运行结束时没有退出,则意味着外部资源仍被保留,或者计时器在代码中仍处于待处理状态。建议每次测试后拆除外部资源,以确保 Jest 可以干净地关闭。你可以使用 --detectOpenHandles 来帮助追踪它。

¥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.



¥Show the help information, similar to this page.

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

忽略指定项目的测试。Jest 在配置中使用属性 displayName 来标识每个项目。如果你使用此选项,你应该为所有项目提供 displayName

¥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.


生成基本配置文件。根据你的项目,Jest 会问你几个问题,这些问题将有助于生成 jest.config.js 文件,其中包含每个选项的简短描述。

¥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.


将 Jest 的全局变量(expecttestdescribebeforeEach 等)插入全局环境中。如果将其设置为 false,则应从 @jest/globals 导入,例如

¥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';


test('some test', () => {

仅使用默认的 jest-circus 测试运行程序才支持此选项。

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


以 JSON 格式打印测试结果。此模式会将所有其他测试输出和用户消息发送到 stderr。

¥Prints the test results in JSON. This mode will send all other test output and user messages to stderr.


运行受上次提交中的文件更改影响的所有测试。行为与 --onlyChanged 类似。

¥Run all tests affected by file changes in the last commit made. Behaves similarly to --onlyChanged.


列出 Jest 将在给定参数的情况下运行的所有测试文件,然后退出。

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


每次测试后记录堆使用情况。对于调试内存泄漏很有用。与节点中的 --runInBand--expose-gc 一起使用。

¥Logs the heap usage after every test. Useful to debug memory leaks. Use together with --runInBand and --expose-gc in node.


防止 Jest 同时执行超过指定数量的测试。仅影响使用 test.concurrent 的测试。

¥Prevents Jest from executing more than the specified amount of tests at the same time. Only affects tests that use test.concurrent.


别名:-w。指定工作池为运行测试而生成的最大工作进程数量。在单运行模式下,这默认为计算机上可用的核心数减去主线程的一数。在监视模式下,这默认为机器上可用内核的一半,以确保 Jest 不引人注目并且不会让你的机器停止运行。在 CI 等资源有限的环境中调整此设置可能很有用,但默认值应该足以满足大多数用例。

¥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.

对于具有可用可变 CPU 的环境,你可以使用基于百分比的配置:--maxWorkers=50%

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



¥Disables stack trace in test results output.


激活测试结果通知。当你不希望自己的意识能够专注于 JavaScript 测试之外的任何事情时,这很有用。

¥Activates notifications for test results. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing.


别名:-o。尝试根据当前存储库中哪些文件已更改来确定要运行哪些测试。仅当你当前在 git/hg 存储库中运行测试并且需要静态依赖图(即没有动态需求)时才有效。

¥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).


--detectOpenHandles--forceExit 被禁用时,如果进程在此毫秒数后仍未完全退出,Jest 将打印警告。值 0 将禁用警告。默认为 1000

¥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.


当还指定了 --json 选项时,将测试结果写入文件。返回的 JSON 结构记录在 testResultsProcessor

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



¥Allows the test suite to pass when no files are found.

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

从指定路径中找到的一个或多个项目运行测试;也采用路径全局。此选项在 CLI 中相当于 projects 配置选项。

¥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.


打乱文件中测试的顺序。洗牌是基于种子的。请参阅 --seed=<num> 了解更多信息。

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

设置此选项后将显示种子值。相当于设置 CLI 选项 --showSeed

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

jest --randomize --seed 1234

仅使用默认的 jest-circus 测试运行程序才支持此选项。

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


使用指定的报告器运行测试。报告器选项 无法通过 CLI 获得。多个报告者的示例:

¥Run tests with specified reporters. Reporter options are not available via CLI. Example with multiple reporters:

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


每次测试前自动重置模拟状态。相当于每次测试前调用 jest.resetAllMocks()。这将导致任何模拟的假实现被删除,但不会恢复其初始实现。

¥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.


在每次测试之前自动恢复模拟状态和实现。相当于每次测试前调用 jest.restoreAllMocks()。这将导致任何模拟的假实现被删除并恢复其初始实现。

¥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.


Jest 用于搜索文件的目录路径列表。

¥A list of paths to directories that Jest should use to search for files in.



¥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.



¥Run only the tests that were specified with their exact paths. This avoids converting them into a regular expression and matching it against every single file.


¥For example, given the following file structure:

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


¥When ran with a pattern, no test is found:

jest --runTestsByPath __tests__/t



No tests found


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

jest --runTestsByPath __tests__/t1.test.js



PASS __tests__/t1.test.js

默认的正则表达式匹配在小规模运行中工作正常,但如果提供多个模式和/或针对大量测试,则会变得很慢。此选项取代了正则表达式匹配逻辑,从而优化了 Jest 过滤特定测试文件所需的时间。

¥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.


设置可通过 jest.getSeed() 在测试文件中检索的种子值。种子值必须介于 -0x800000000x7fffffff 之间(含 -2147483648 (-(2 ** 31)) 和 2147483647 (2 ** 31 - 1),十进制)。

¥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

如果未指定此选项,Jest 将随机生成该值。你可以使用 --showSeed 标志来打印测试报告摘要中的种子。

¥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.

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

运行指定项目的测试。Jest 在配置中使用属性 displayName 来标识每个项目。如果你使用此选项,你应该为所有项目提供 displayName

¥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.


(?<shardIndex>\d+)/(?<shardCount>\d+) 格式执行的测试套件分片。

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

shardIndex 描述选择哪个分片,而 shardCount 控制套件应分割成的分片数量。

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

shardIndexshardCount 必须是从 1 开始的正数,并且 shardIndex 必须小于或等于 shardCount

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

当指定 shard 时,配置的 testSequencer 必须实现 shard 方法。

¥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


打印你的 Jest 配置,然后退出。

¥Print your Jest config and then exits.


打印测试报告摘要中的种子值。详情请参见 --seed=<num>

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

也可以在配置中设置。参见 showSeed

¥Can also be set in configuration. See showSeed.



¥Prevent tests from printing messages through the console.

--testEnvironmentOptions=<json string>

带有选项的 JSON 字符串将传递给 testEnvironment。相关选项取决于环境。

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


向测试结果添加 location 字段。如果你想在报告中报告测试位置,这很有用。

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


在生成的对象中,column 是 0 索引的,而 line 不是。

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

"column": 4,
"line": 5

--testMatch glob1 ... globN

Jest 用于检测测试文件的 glob 模式。详情请参阅 testMatch 配置

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


别名:-t。仅运行名称与正则表达式匹配的测试。例如,假设你只想运行与授权相关的测试,其名称如 'GET /api/posts with auth',那么你可以使用 jest -t=auth

¥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.


在执行测试之前针对所有测试路径进行测试的单个或正则表达式模式字符串数组。与 --testPathPattern 相反,它只会运行那些路径与提供的正则表达式不匹配的测试。

¥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.

要作为数组传递,请使用转义括号和空格分隔的正则表达式,例如 \(/node_modules/ /tests/e2e/\)。或者,你可以通过将正则表达式组合成单个正则表达式(如 /node_modules/|/tests/e2e/)来省略括号。这两个例子是等价的。

¥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.


在执行测试之前与所有测试路径进行匹配的正则表达式模式字符串。在 Windows 上,你需要使用 / 作为路径分隔符或将 \ 转义为 \\

¥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 \\.



¥Lets you specify a custom test runner.


允许你指定自定义测试序列器。详情请参阅 testSequencer 配置

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



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


别名:-u。使用此标志重新记录此测试运行期间失败的每个快照。可以与测试套件模式或 --testNamePattern 一起使用来重新记录快照。

¥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.


将所有输出转移到 stderr。

¥Divert all output to stderr.



¥Display individual test results with the test suite hierarchy.



¥Alias: -v. Print the version and exit.


监视文件的更改并重新运行与更改的文件相关的测试。如果要在文件更改后重新运行所有测试,请改用 --watchAll 选项。

¥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.


如果使用 --watch 启用了监视模式,则使用 --no-watch(或 --watch=false)显式禁用监视模式。在大多数 CI 环境中,这是自动为你处理的。

¥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.


监视文件的更改并在发生更改时重新运行所有测试。如果你只想重新运行依赖于已更改文件的测试,请使用 --watch 选项。

¥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.


如果使用 --watchAll 启用了监视模式,则使用 --no-watchAll(或 --watchAll=false)显式禁用监视模式。在大多数 CI 环境中,这是自动为你处理的。

¥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 进行文件抓取。默认为 true。禁用使用 --no-watchman

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


是否使用 工作线程 进行并行化。默认使用 子进程

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


这是实验性功能。有关详细信息,请参阅 workerThreads 配置选项

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