--- url: /guide/cli.md --- # 命令行界面。 ## 命令 ### `vitest` 在当前目录启动 Vitest。在开发环境中会自动进入监视模式,在 CI(或非交互式终端)中会自动进入运行模式。 你可以传递一个额外的参数作为要运行的测试文件的过滤器。例如: ```bash vitest foobar ``` 将只运行路径中包含 `foobar` 的测试文件。此过滤器仅检查包含关系,不支持正则表达式或 glob 模式(除非你的终端在 Vitest 接收过滤器之前处理了它)。 自 Vitest 3 起,你还可以通过文件名和行号指定测试: ```bash $ vitest basic/foo.test.ts:10 ``` ::: warning 注意,Vitest 需要完整的文件名才能使此功能正常工作。它可以相对于当前工作目录,也可以是绝对文件路径。 ```bash $ vitest basic/foo.js:10 # ✅ $ vitest ./basic/foo.js:10 # ✅ $ vitest /users/project/basic/foo.js:10 # ✅ $ vitest foo:10 # ❌ $ vitest ./basic/foo:10 # ❌ ``` 目前 Vitest 也不支持范围: ```bash $ vitest basic/foo.test.ts:10, basic/foo.test.ts:25 # ✅ $ vitest basic/foo.test.ts:10-25 # ❌ ``` ::: ### `vitest run` 执行单次运行,不进入监视模式。 ### `vitest watch` 运行所有测试套件,但监视更改并在更改时重新运行测试。与不带参数调用 `vitest` 相同。在 CI 中或当 stdin 不是 TTY(非交互式环境)时将回退到 `vitest run`。 ### `vitest dev` `vitest watch` 的别名。 ### `vitest related` 仅运行覆盖一系列源文件的测试。适用于静态导入(例如,`import('./index.js')` 或 `import index from './index.js`),但不适用于动态导入(例如,`import(filepath)`)。所有文件应相对于根文件夹。 适合与 [`lint-staged`](https://github.com/okonet/lint-staged) 或你的 CI 设置一起运行。 ```bash vitest related /src/index.ts /src/hello-world.js ``` ::: tip 请记住,Vitest 默认以监视模式运行。如果你使用 `lint-staged` 之类的工具,还应传入 `--run` 选项,使命令可以正常退出。 ```js [.lintstagedrc.js] export default { '*.{js,ts}': 'vitest related --run', } ``` ::: ### `vitest bench` 只运行用于比较性能结果的[基准测试](/guide/features#benchmarking)。 ### `vitest init` `vitest init ` 可用于设置项目配置。目前,它仅支持 [`browser`](/guide/browser/) 值: ```bash vitest init browser ``` ### `vitest list` `vitest list` 命令继承所有 `vitest` 选项以打印所有匹配测试的列表。此命令忽略 `reporters` 选项。默认情况下,它将打印所有匹配文件过滤器和名称模式的测试名称: ```shell vitest list filename.spec.ts -t="some-test" ``` ```txt describe > some-test describe > some-test > test 1 describe > some-test > test 2 ``` 你可以传递 `--json` 标志以 JSON 格式打印测试或将其保存到单独的文件中: ```bash vitest list filename.spec.ts -t="some-test" --json=./file.json ``` 如果 `--json` 标志没有接收值,它将把 JSON 输出到 stdout。 你还可以传递 `--filesOnly` 标志仅打印测试文件: ```bash vitest list --filesOnly ``` ```txt tests/test1.test.ts tests/test2.test.ts ``` 从 Vitest 5 开始,`vitest list` 会通过[静态解析测试文件](/api/advanced/vitest#parsespecifications)来收集测试,而不是运行这些文件。传入 `--no-static-parse` 可改为运行文件。Vitest 会以有限并发度解析测试文件,默认值为 `os.availableParallelism()`。可以通过 `--static-parse-concurrency` 选项更改并发度。 ### `vitest doctor` `vitest doctor` 会通过在每种候选配置下运行测试套件,测量在替代配置下测试套件的运行速度可以提升多少。候选配置根据当前配置选定: ```bash vitest doctor ``` ``` 结果(每种配置取 3 次运行中的最短时间) 基准(pool: forks · isolate: true) 4.08s pool: 'threads' 3.64s (-11%) pool: 'vmThreads' 1.33s (-67%) isolate: false 1.28s (-69%) 建议:pool: 'vmThreads' (-67%) // vitest.config.ts import { defineConfig } from 'vitest/config' export default defineConfig({ test: { pool: 'vmThreads', // 在此套件中测得快 67% }, }) ``` `isolate: false` 候选配置还会通过以随机文件顺序运行两次测试套件进行额外验证:如果任何测试依赖隔离,该候选配置会被报告为失败,而不会被推荐。当多个候选配置与最快配置相差不大时,doctor 会优先选择能够保留文件级隔离的配置。 Doctor 还会在获胜配置的基础上测试较低的 [`maxWorkers`](/config/maxworkers) 值:每个 worker 都会将其转换请求通过同一个主线程 Vite 服务器处理,因此超过某个数量后,增加 worker 会使运行变慢而不是变快。Doctor 从当前 worker 数量的一半开始,只要测试套件至少快 5%,就会继续将数量减半,并在建议中包含获胜的值。 在 DOM 或自定义环境中运行的测试套件,会分别在 `vmThreads` 和 `vmForks` 两个 VM 池下进行测量:它们让每个 worker 保留一个环境,从而摊销环境创建成本,同时仍为每个文件提供全新的 VM 上下文。`vmForks` 使用子进程而非 worker 线程;每个子进程都有自己的堆和垃圾回收器,因此哪个池更快取决于测试套件。对于无法在 worker 线程中运行的套件,应使用 VM 选项 `vmForks`。 如果安装了 `jsdom`,运行 `jsdom` 的项目也会在 `environment: 'happy-dom'` 下进行测量。该替换会针对每个项目单独应用;使用其他环境的项目会保留原环境。happy-dom 与 jsdom 采用不同的 DOM 实现,因此在采用此替换方案前,应验证依赖布局或导航功能的测试。当 [fs 模块缓存](/config/fsmodulecache) 关闭时,doctor 会在一次不计时的预热运行(用于填充缓存)之后测量 `fsModuleCache: true`,因此报告的时间就是重复运行时实际付出的时间。 每次测量都会运行完整的测试套件,包括浏览器项目:`isolate: false` 也会影响浏览器模式。无法影响浏览器项目的候选配置(`pool`、`environment`、fs 模块缓存)会根据仅运行 Node 端项目的结果选定。 失败的候选配置会附带其错误信息摘录。如果测试套件在当前配置下失败,doctor 会中止并显示错误:它需要一个通过测试的基准配置才能进行比较。 较短的测试套件会被多次测量,并报告其中的最佳时间,因此比较结果能够反映预热后的稳定状态。Doctor 会多次运行完整的测试套件,因此所需时间是普通运行时间的数倍。有关每个候选配置背后权衡的详细信息,请参阅[改进性能](/guide/improving-performance)。 即使没有候选配置可供比较,doctor 也会测量并报告基准配置。在 `vm` pool 上的配置还会与 `pool: 'threads'` 和 `isolate: false` 进行额外比较,该配置同样会复用 worker,但会在文件之间共享模块状态;已经使用其中一个 vm pool 的配置仍会在另一个 vm pool 下进行测量。 ## Shell 自动补全 Vitest 为命令、选项和选项值提供 Shell 自动补全,由 [`@bomb.sh/tab`](https://github.com/bombshell-dev/tab) 提供支持。 ### 设置 要在 zsh 中永久设置,请将此添加到你的 `~/.zshrc`: ```bash # 添加到 ~/.zshrc 以实现永久自动补全(其他 shell 也可以这样做) source <(vitest complete zsh) ``` ### 包管理器集成 `@bomb.sh/tab` 与[包管理器](https://github.com/bombshell-dev/tab?tab=readme-ov-file#package-manager-completions)集成。直接运行 vitest 时自动补全生效: ::: code-group ```bash [npm] npm vitest ``` ```bash [npm] npm exec vitest ``` ```bash [pnpm] pnpm vitest ``` ```bash [yarn] yarn vitest ``` ```bash [bun] bun vitest ``` ::: 对于包管理器自动补全,你应该单独安装 [Tab 的包管理器补全](https://github.com/bombshell-dev/tab?tab=readme-ov-file#package-manager-completions)。 ## 选项 ::: tip Vitest 支持 [CLI 参数](https://github.com/cacjs/cac#dot-nested-options) 的驼峰式和短横线式。例如,`--passWithNoTests` 和 `--pass-with-no-tests` 都有效(`--no-color` 和 `--inspect-brk` 除外)。 Vitest 还支持不同的指定值的方式:`--reporter dot` 和 `--reporter=dot` 都有效。 如果选项支持值数组,你需要多次传递该选项: ``` vitest --reporter=dot --reporter=default ``` 布尔选项可以用 `no-` 前缀否定。将值指定为 `false` 也有效: ``` vitest --no-api vitest --api=false ``` ::: ### root * **CLI:** `-r, --root ` * **Config:** [root](/config/root) Root path ### config * **CLI:** `-c, --config ` Path to config file ### update * **CLI:** `-u, --update [type]` * **Config:** [update](/config/update) Update snapshot (accepts boolean, "new", "all" or "none") ### watch * **CLI:** `-w, --watch` * **Config:** [watch](/config/watch) Enable watch mode ### testNamePattern * **CLI:** `-t, --testNamePattern ` * **Config:** [testNamePattern](/config/testnamepattern) Run tests with full names matching the specified regexp pattern ### dir * **CLI:** `--dir ` * **Config:** [dir](/config/dir) Base directory to scan for the test files ### ui * **CLI:** `--ui` Enable UI ### open * **CLI:** `--open` * **Config:** [open](/config/open) Open UI automatically (default: `!process.env.CI`) ### api.port * **CLI:** `--api.port [port]` Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. If true will be set to `51204` ### api.host * **CLI:** `--api.host [host]` Specify which IP addresses the server should listen on. Set this to `0.0.0.0` or `true` to listen on all addresses, including LAN and public addresses ### api.strictPort * **CLI:** `--api.strictPort` Set to true to exit if port is already in use, instead of automatically trying the next available port ### api.allowExec * **CLI:** `--api.allowExec` * **Config:** [api.allowExec](/config/api#api-allowexec) Allow API to execute code. (Be careful when enabling this option in untrusted environments) ### api.allowWrite * **CLI:** `--api.allowWrite` * **Config:** [api.allowWrite](/config/api#api-allowwrite) Allow API to edit files. (Be careful when enabling this option in untrusted environments) ### silent * **CLI:** `--silent [value]` * **Config:** [silent](/config/silent) Silent console output from tests. Use `'passed-only'` to see logs from failing tests only. ### hideSkippedTests * **CLI:** `--hideSkippedTests` Hide logs for skipped tests ### reporters * **CLI:** `--reporter ` * **Config:** [reporters](/config/reporters) Specify reporters (default, agent, minimal, blob, verbose, dot, json, tap, tap-flat, junit, tree, hanging-process, github-actions) ### outputFile * **CLI:** `--outputFile ` * **Config:** [outputFile](/config/outputfile) Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters (example: `--outputFile.tap=./tap.txt`) ### coverage.provider * **CLI:** `--coverage.provider ` * **Config:** [coverage.provider](/config/coverage#coverage-provider) Select the tool for coverage collection, available values are: "v8", "istanbul" and "custom" ### coverage.enabled * **CLI:** `--coverage.enabled` * **Config:** [coverage.enabled](/config/coverage#coverage-enabled) Enables coverage collection. Can be overridden using the `--coverage` CLI option (default: `false`) ### coverage.include * **CLI:** `--coverage.include ` * **Config:** [coverage.include](/config/coverage#coverage-include) Files included in coverage as glob patterns. May be specified more than once when using multiple patterns. By default only files covered by tests are included. ### coverage.exclude * **CLI:** `--coverage.exclude ` * **Config:** [coverage.exclude](/config/coverage#coverage-exclude) Files to be excluded in coverage. May be specified more than once when using multiple extensions. ### coverage.clean * **CLI:** `--coverage.clean` * **Config:** [coverage.clean](/config/coverage#coverage-clean) Clean coverage results before running tests (default: true) ### coverage.cleanOnRerun * **CLI:** `--coverage.cleanOnRerun` * **Config:** [coverage.cleanOnRerun](/config/coverage#coverage-cleanonrerun) Clean coverage report on watch rerun (default: true) ### coverage.reportsDirectory * **CLI:** `--coverage.reportsDirectory ` * **Config:** [coverage.reportsDirectory](/config/coverage#coverage-reportsdirectory) Directory to write coverage report to (default: ./coverage) ### coverage.reporter * **CLI:** `--coverage.reporter ` * **Config:** [coverage.reporter](/config/coverage#coverage-reporter) Coverage reporters to use. Visit [`coverage.reporter`](/config/coverage#coverage-reporter) for more information (default: `["text", "html", "clover", "json"]`) ### coverage.reportOnFailure * **CLI:** `--coverage.reportOnFailure` * **Config:** [coverage.reportOnFailure](/config/coverage#coverage-reportonfailure) Generate coverage report even when tests fail (default: `false`) ### coverage.allowExternal * **CLI:** `--coverage.allowExternal` * **Config:** [coverage.allowExternal](/config/coverage#coverage-allowexternal) Collect coverage of files outside the project root (default: `false`) ### coverage.skipFull * **CLI:** `--coverage.skipFull` * **Config:** [coverage.skipFull](/config/coverage#coverage-skipfull) Do not show files with 100% statement, branch, and function coverage (default: `false`) ### coverage.thresholds.100 * **CLI:** `--coverage.thresholds.100` * **Config:** [coverage.thresholds.100](/config/coverage#coverage-thresholds-100) Shortcut to set all coverage thresholds to 100 (default: `false`) ### coverage.thresholds.perFile * **CLI:** `--coverage.thresholds.perFile ` * **Config:** [coverage.thresholds.perFile](/config/coverage#coverage-thresholds-perfile) Check thresholds per file. See `--coverage.thresholds.lines`, `--coverage.thresholds.functions`, `--coverage.thresholds.branches` and `--coverage.thresholds.statements` for the actual thresholds (default: `false`). Object form is available in config files only. ### coverage.thresholds.autoUpdate * **CLI:** `--coverage.thresholds.autoUpdate ` * **Config:** [coverage.thresholds.autoUpdate](/config/coverage#coverage-thresholds-autoupdate) Update threshold values: "lines", "functions", "branches" and "statements" to configuration file when current coverage is above the configured thresholds (default: `false`) ### coverage.thresholds.lines * **CLI:** `--coverage.thresholds.lines ` Threshold for lines. Visit [istanbuljs](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information. This option is not available for custom providers ### coverage.thresholds.functions * **CLI:** `--coverage.thresholds.functions ` Threshold for functions. Visit [istanbuljs](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information. This option is not available for custom providers ### coverage.thresholds.branches * **CLI:** `--coverage.thresholds.branches ` Threshold for branches. Visit [istanbuljs](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information. This option is not available for custom providers ### coverage.thresholds.statements * **CLI:** `--coverage.thresholds.statements ` Threshold for statements. Visit [istanbuljs](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information. This option is not available for custom providers ### coverage.ignoreClassMethods * **CLI:** `--coverage.ignoreClassMethods ` * **Config:** [coverage.ignoreClassMethods](/config/coverage#coverage-ignoreclassmethods) Array of class method names to ignore for coverage. Visit [istanbuljs](https://github.com/istanbuljs/nyc#ignoring-methods) for more information. This option is only available for the istanbul providers (default: `[]`) ### coverage.processingConcurrency * **CLI:** `--coverage.processingConcurrency ` * **Config:** [coverage.processingConcurrency](/config/coverage#coverage-processingconcurrency) Concurrency limit used when processing the coverage results. (default min between 20 and the number of CPUs) ### coverage.customProviderModule * **CLI:** `--coverage.customProviderModule ` * **Config:** [coverage.customProviderModule](/config/coverage#coverage-customprovidermodule) Specifies the module name or path for the custom coverage provider module. Visit [Custom Coverage Provider](/guide/coverage#custom-coverage-provider) for more information. This option is only available for custom providers ### coverage.watermarks.statements * **CLI:** `--coverage.watermarks.statements ` High and low watermarks for statements in the format of `,` ### coverage.watermarks.lines * **CLI:** `--coverage.watermarks.lines ` High and low watermarks for lines in the format of `,` ### coverage.watermarks.branches * **CLI:** `--coverage.watermarks.branches ` High and low watermarks for branches in the format of `,` ### coverage.watermarks.functions * **CLI:** `--coverage.watermarks.functions ` High and low watermarks for functions in the format of `,` ### coverage.changed * **CLI:** `--coverage.changed ` * **Config:** [coverage.changed](/config/coverage#coverage-changed) Collect coverage only for files changed since a specified commit or branch (e.g., `origin/main` or `HEAD~1`). Inherits value from `--changed` by default. ### coverage.excludeAfterRemap * **CLI:** `--coverage.excludeAfterRemap` * **Config:** [coverage.excludeAfterRemap](/config/coverage#coverage-excludeafterremap) Apply exclusions again after coverage has been remapped to original sources. (default: false) ### coverage.htmlDir * **CLI:** `--coverage.htmlDir ` * **Config:** [coverage.htmlDir](/config/coverage#coverage-htmldir) Directory of HTML coverage output to be served in UI mode and HTML reporter. ### coverage.autoAttachSubprocess * **CLI:** `--coverage.autoAttachSubprocess` * **Config:** [coverage.autoAttachSubprocess](/config/coverage#coverage-autoattachsubprocess) Track coverage of the `node:child_process` and `node:worker_threads` spawned during test run. Supported only by `v8` provider. (default: false) ### mode * **CLI:** `--mode ` * **Config:** [mode](/config/mode) Override Vite mode (default: `test`) ### isolate * **CLI:** `--isolate` * **Config:** [isolate](/config/isolate) Run every test file in isolation. To disable isolation, use `--no-isolate` (default: `true`) ### globals * **CLI:** `--globals` * **Config:** [globals](/config/globals) Inject apis globally ### injectCjsGlobals * **CLI:** `--injectCjsGlobals` * **Config:** [injectCjsGlobals](/config/injectcjsglobals) Inject CommonJS variables (`module`, `exports`, `require`, `__filename`, `__dirname`) into every test module. To disable, use `--no-inject-cjs-globals` (default: `true`) ### dom * **CLI:** `--dom` Mock browser API with happy-dom ### browser.enabled * **CLI:** `--browser.enabled` * **Config:** [browser.enabled](/config/browser/enabled) Run tests in the browser. Equivalent to `--browser.enabled` (default: `false`) ### browser.name * **CLI:** `--browser.name ` Run all tests in a specific browser. Some browsers are only available for specific providers (see `--browser.provider`). ### browser.headless * **CLI:** `--browser.headless` * **Config:** [browser.headless](/config/browser/headless) Run the browser in headless mode (i.e. without opening the GUI (Graphical User Interface)). If you are running Vitest in CI, it will be enabled by default (default: `process.env.CI`) ### browser.ui * **CLI:** `--browser.ui` * **Config:** [browser.ui](/config/browser/ui) Show Vitest UI when running tests (default: `!process.env.CI`) ### browser.detailsPanelPosition * **CLI:** `--browser.detailsPanelPosition ` * **Config:** [browser.detailsPanelPosition](/config/browser/detailspanelposition) Default position for the details panel in browser mode. Either `right` (horizontal split) or `bottom` (vertical split) (default: `right`) ### browser.connectTimeout * **CLI:** `--browser.connectTimeout ` * **Config:** [browser.connectTimeout](/config/browser/connecttimeout) If connection to the browser takes longer, the test suite will fail (default: `60_000`) ### browser.dependencySourcemaps * **CLI:** `--browser.dependencySourcemaps` * **Config:** [browser.dependencySourcemaps](/config/browser/dependencysourcemaps) Serve sourcemaps of dependencies to the browser in headless runs, used by devtools when debugging into `node_modules`. Reported test errors are source-mapped either way. Use `--browser.dependencySourcemaps=false` to speed up test runs if you don't step into dependency code (default: `true`) ### browser.trackUnhandledErrors * **CLI:** `--browser.trackUnhandledErrors` * **Config:** [browser.trackUnhandledErrors](/config/browser/trackunhandlederrors) Control if Vitest catches uncaught exceptions so they can be reported (default: `true`) ### browser.trace * **CLI:** `--browser.trace ` * **Config:** [browser.trace](/config/browser/trace) Enable trace view mode. Supported: "on", "off", "on-first-retry", "on-all-retries", "retain-on-failure". ### browser.traceView.enabled * **CLI:** `--browser.traceView.enabled` * **Config:** [browser.traceView.enabled](/config/browser/traceview#traceview-enabled) Enable Vitest trace-view collection for browser tests (default: `false`) ### browser.traceView.recordCanvas * **CLI:** `--browser.traceView.recordCanvas` * **Config:** [browser.traceView.recordCanvas](/config/browser/traceview#traceview-recordcanvas) Capture canvas pixels in trace-view snapshots (default: `false`) ### browser.traceView.inlineImages * **CLI:** `--browser.traceView.inlineImages` * **Config:** [browser.traceView.inlineImages](/config/browser/traceview#traceview-inlineimages) Inline loaded image pixels in trace-view snapshots (default: `false`) ### browser.locators.exact * **CLI:** `--browser.locators.exact` * **Config:** [browser.locators.exact](/config/browser/locators#locators-exact) Should locators match the text exactly by default (default: `true`) ### pool * **CLI:** `--pool ` * **Config:** [pool](/config/pool) Specify pool, if not running in the browser (default: `forks`) ### execArgv * **CLI:** `--execArgv