跳转至主内容
版本:29.5

Jest CLI 选项

jest 命令行运行有很多好用的选项。 你可以运行jest --help命令查看所有可用的选项。 下面所示选项都可一起使用,以你想要的方式来运行测试。 Jest 的 配置选项 里每一条都可以通过命令行来指定。

下面是简要概述:

在命令行中使用

默认运行所有测试

jest

仅运行指定文件名称或文件路径的测试

# 指定测试文件的名称
jest my-test
# 指定测试文件的路径
jest path/to/my-test.js

仅运行在 hg/git 上有改动但尚未提交的文件

jest -o

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

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

仅运行匹配特定名称的测试用例(主要是匹配 describe 或 test 的名称)

jest -t name-of-spec

运行监视模式

jest --watch # 默认执行 jest -o 监视有改动的测试
jest --watchAll # 监视所有测试

该模式下可以指定名称或路径来监视特定的测试文件

通过包管理器使用Jest

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

除了下面这种使用方式

jest -u -t="ColorPicker"

现在你还可以使用

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

驼峰命名与横线分割命名支持

Jest同时支持驼峰命名与横线分割命名。 下面两个例子的效果是一样的:

jest --collect-coverage
jest --collectCoverage

两种命名的参数也可以混用:

jest --update-snapshot --detectOpenHandles

选项

备注

使用命令行传入的参数优先级高于使用 配置 指定的参数。


参考

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 \. On Windows, you will need to use / as a path separator or escape \ as \\.

--bail[=<n>]

Alias: -b. Alias: -b. Exit the test suite immediately upon n number of failing test suite. Defaults to 1. 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. 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. 与 --onlyChanged 的行为相似。

--changedSince

Runs tests related to the changes since the provided branch or commit hash. 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 的行为相似。 与 --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. * 注意:清除缓存将降低性能。 The default cache directory can be found by calling jest --showConfig.

注意

清除缓存将影响性能。

--clearMocks

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

--collectCoverageFrom=<glob>

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

--colors

即便stdout不是TTY模式, 也要强制高亮显示测试结果。

备注

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

--config=<path>

或: -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. 这也可以是 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>

Indicates which provider should be used to instrument code for coverage. 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>

所有测试都使用该测试环境设定。 可以指向任何文件或者node模块。 例如jsdom, node or path/to/my-environment.js

--errorOnDeprecated

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

--expand

别名︰ -e。 使用该参数来对比完整的差异和错误,而非修复。

--filter=<file>

Path to a module exporting a filtering function. 此异步函数接收一个测试路径列表,可以通过返回像{ filtered: Array<{ test: string }> }的对象来操作该列表以排除正在运行的测试。 当与测试基础设施结合使用以过滤已知的损坏测试时尤其有用,如:

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

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. 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可以完全关闭,建议你在每个测试后都关闭用到的外部资源。 你可以使用 --detectOpenHandles 来帮助追踪问题。

--help

显示帮助信息,类似于本页文档。

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

忽略特定的测试项目。 Run only 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. If you use this option, you should provide a displayName to all your projects.

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

--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);
});
备注

这个选项仅在使用jest-circus进行测试时生效

--json

以JSON模式显示测试结果。 该模式会包其他所有测试和用户信息都发送到stderr。

--lastCommit

Run all tests affected by file changes in the last commit made. Behaves similarly to --onlyChanged. 与 --onlyChanged 的行为相似。

--listTests

以JSON数组的形式列出所有将要运行的测试并退出

--logHeapUsage

记录每个测试后的记录堆使用情况。 主要用来调试内存泄漏。 与 --runInBand--expose-gc一起使用.

--maxConcurrency=<num>

Prevents Jest from executing more than the specified amount of tests at the same time. 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 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. 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. 特别是当你不想专心致志等待 JavaScript 测试结果时。

--onlyChanged

或: -o. 尝试确定根据当前存储库中哪些已经更改的文件来运行的测试。 只有在此刻 git/hg 存储库中运行测试,需要静态依赖关系图时有用(例如. 无动态要求)。

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

通过 — — json 参数可以将测试结果写入到指定文件。 The returned JSON structure is documented in testResultsProcessor.

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

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

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

jest --randomize --seed 1234
备注

这个选项仅在使用jest-circus进行测试时生效

--reporters

Run tests with specified reporters. Run tests with specified reporters. Reporter options are not available via CLI. Example with multiple reporters: 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. 或: -i. 仅在当前的进程中连续运行所有测试,而非通过创建的子进程的工作池来运行测试。 This can be useful for debugging.

--runTestsByPath

Run only the tests that were specified with their exact paths.

提示

默认正则表达式匹配在测试用例比较少时正常工作,但如果提供多个模式或大量测试,测试则变得较慢。 此选项代替正则表达式匹配逻辑,优化筛选特定测试文件所用的时间。

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

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

运行指定的测试项目。 Run only 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. 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

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

shardIndex 描述了当前选中的分片序号,而 shardCount 描述了套件的分片总数量

shardIndexshardCount 是从1开始的正整数,且 shardIndexshardCount

指定 shard 时需要配置 testSequencer 实现一个分片方法。

比如,将测试分为3份:

jest --shard=1/3
jest --shard=2/3
jest --shard=3/3

--showConfig

输出Jest配置,然后退出。

--showSeed

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

Can also be set in configuration. 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. 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>

别名︰ -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.

提示

提示:正则表达式与全名匹配,全名是测试名称及其所有周围describe块的组合。

--testPathIgnorePatterns=<regex>|[array]

A single or array of regexp pattern strings that are tested against all tests paths before executing the test. 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.

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>

在运行测试前,匹配的regexp模式字符串的测试文件路径。 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. 详情请查看 testSequencer 配置文件

--testTimeout=<number>

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

--updateSnapshot

或: -u. 在运行测试中使用这个参数来重新录制每个失败测试的快照。 还可以和测试套件模式或 --testNamePattern 一起使用,从而重新录制的快照。

--useStderr

转移所有输出到stderr(标准错误输出).

--verbose

层次显示测试套件中每个测试的结果。

--version

Alias: -v. Print the version and exit.

--watch

监视文件更改,并重新运行与已更改的文件相关的测试。 当文件发生更改时,如果你想要重新运行所有测试,可以使用 --watchAll 选项。

提示

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 选项。

提示

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.