Skip to content

命令行界面。

命令

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 的别名。

仅运行覆盖一系列源文件的测试。适用于静态导入(例如,import('./index.js')import index from './index.js),但不适用于动态导入(例如,import(filepath))。所有文件应相对于根文件夹。

适合与 lint-staged 或你的 CI 设置一起运行。

bash
vitest related /src/index.ts /src/hello-world.js

TIP

别忘了 Vitest 默认启用监视模式运行。如果你正在使用像 lint-staged 这样的工具,你还应该传递 --run 选项,以便命令可以正常退出。

.lintstagedrc.js
js
export default {
  '*.{js,ts}': 'vitest related --run',
}

vitest bench

仅运行 基准测试 测试,比较性能结果。

vitest init

vitest init <name> 可用于设置项目配置。目前,它仅支持 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 4.1 起,你可以传递 --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 值:每个 worker 都会将其转换请求通过同一个主线程 Vite 服务器处理,因此超过某个数量后,增加 worker 会使运行变慢而不是变快。Doctor 从当前 worker 数量的一半开始,只要测试套件至少快 5%,就会继续将数量减半,并在建议中包含获胜的值。

运行 DOM 环境的测试套件会在两个 vm pool(vmThreadsvmForks)下进行测量:它们通过让每个 worker 保留一个环境来摊销环境创建成本,同时每个文件仍会获得一个全新的 VM 上下文。vmForks 使用子进程而不是 worker 线程:每个子进程都有自己的堆和垃圾回收器,因此根据测试套件的不同,任一 pool 都可能更快;对于无法在 worker 线程中运行的测试套件,应使用 vmForks 这一 vm 选项。

如果安装了 jsdom,运行 jsdom 的项目也会在 environment: 'happy-dom' 下进行测量。该替换会针对每个项目单独应用;使用其他环境的项目会保留原环境。happy-dom 与 jsdom 采用不同的 DOM 实现,因此在采用此替换方案前,应验证依赖布局或导航功能的测试。当 fs 模块缓存 关闭时,doctor 会在一次不计时的预热运行(用于填充缓存)之后测量 fsModuleCache: true,因此报告的时间就是重复运行时实际付出的时间。

每次测量都会运行完整的测试套件,包括浏览器项目:isolate: false 也会影响浏览器模式。无法影响浏览器项目的候选配置(poolenvironment、fs 模块缓存)会根据仅运行 Node 端项目的结果选定。

失败的候选配置会附带其错误信息摘录。如果测试套件在当前配置下失败,doctor 会中止并显示错误:它需要一个通过测试的基准配置才能进行比较。

较短的测试套件会被多次测量,并报告其中的最佳时间,因此比较结果能够反映预热后的稳定状态。Doctor 会多次运行完整的测试套件,因此所需时间是普通运行时间的数倍。有关每个候选配置背后权衡的详细信息,请参阅改进性能

即使没有候选配置可供比较,doctor 也会测量并报告基准配置。在 vm pool 上的配置还会与 pool: 'threads'isolate: false 进行额外比较,该配置同样会复用 worker,但会在文件之间共享模块状态;已经使用其中一个 vm pool 的配置仍会在另一个 vm pool 下进行测量。

Shell 自动补全

Vitest 为命令、选项和选项值提供 Shell 自动补全,由 @bomb.sh/tab 提供支持。

设置

要在 zsh 中永久设置,请将此添加到你的 ~/.zshrc

bash
# 添加到 ~/.zshrc 以实现永久自动补全(其他 shell 也可以这样做)
source <(vitest complete zsh)

包管理器集成

@bomb.sh/tab包管理器集成。直接运行 vitest 时自动补全生效:

bash
npm vitest <Tab>
bash
npm exec vitest <Tab>
bash
pnpm vitest <Tab>
bash
yarn vitest <Tab>
bash
bun vitest <Tab>

对于包管理器自动补全,你应该单独安装 Tab 的包管理器补全

选项

TIP

Vitest 支持 CLI 参数 的驼峰式和短横线式。例如,--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 <path>
  • Config: root

Root path

config

  • CLI: -c, --config <path>

Path to config file

update

  • CLI: -u, --update [type]
  • Config: update

Update snapshot (accepts boolean, "new", "all" or "none")

watch

  • CLI: -w, --watch
  • Config: watch

Enable watch mode

testNamePattern

Run tests with full names matching the specified regexp pattern

dir

  • CLI: --dir <path>
  • Config: dir

Base directory to scan for the test files

ui

  • CLI: --ui

Enable UI

open

  • CLI: --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

Allow API to execute code. (Be careful when enabling this option in untrusted environments)

api.allowWrite

Allow API to edit files. (Be careful when enabling this option in untrusted environments)

silent

  • CLI: --silent [value]
  • 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

Specify reporters (default, agent, minimal, blob, verbose, dot, json, tap, tap-flat, junit, tree, hanging-process, github-actions)

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

Select the tool for coverage collection, available values are: "v8", "istanbul" and "custom"

coverage.enabled

Enables coverage collection. Can be overridden using the --coverage CLI option (default: false)

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

Files to be excluded in coverage. May be specified more than once when using multiple extensions.

coverage.clean

Clean coverage results before running tests (default: true)

coverage.cleanOnRerun

Clean coverage report on watch rerun (default: true)

coverage.reportsDirectory

Directory to write coverage report to (default: ./coverage)

coverage.reporter

Coverage reporters to use. Visit coverage.reporter for more information (default: ["text", "html", "clover", "json"])

coverage.reportOnFailure

Generate coverage report even when tests fail (default: false)

coverage.allowExternal

Collect coverage of files outside the project root (default: false)

coverage.skipFull

Do not show files with 100% statement, branch, and function coverage (default: false)

coverage.thresholds.100

Shortcut to set all coverage thresholds to 100 (default: false)

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

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

Threshold for lines. Visit istanbuljs for more information. This option is not available for custom providers

coverage.thresholds.functions

  • CLI: --coverage.thresholds.functions <number>

Threshold for functions. Visit istanbuljs for more information. This option is not available for custom providers

coverage.thresholds.branches

  • CLI: --coverage.thresholds.branches <number>

Threshold for branches. Visit istanbuljs for more information. This option is not available for custom providers

coverage.thresholds.statements

  • CLI: --coverage.thresholds.statements <number>

Threshold for statements. Visit istanbuljs for more information. This option is not available for custom providers

coverage.ignoreClassMethods

Array of class method names to ignore for coverage. Visit istanbuljs for more information. This option is only available for the istanbul providers (default: [])

coverage.processingConcurrency

Concurrency limit used when processing the coverage results. (default min between 20 and the number of CPUs)

coverage.customProviderModule

Specifies the module name or path for the custom coverage provider module. Visit Custom Coverage Provider for more information. This option is only available for custom providers

coverage.watermarks.statements

  • CLI: --coverage.watermarks.statements <watermarks>

High and low watermarks for statements in the format of <high>,<low>

coverage.watermarks.lines

  • CLI: --coverage.watermarks.lines <watermarks>

High and low watermarks for lines in the format of <high>,<low>

coverage.watermarks.branches

  • CLI: --coverage.watermarks.branches <watermarks>

High and low watermarks for branches in the format of <high>,<low>

coverage.watermarks.functions

  • CLI: --coverage.watermarks.functions <watermarks>

High and low watermarks for functions in the format of <high>,<low>

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

Apply exclusions again after coverage has been remapped to original sources. (default: false)

coverage.htmlDir

Directory of HTML coverage output to be served in UI mode and HTML reporter.

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 <name>
  • Config: mode

Override Vite mode (default: test)

isolate

Run every test file in isolation. To disable isolation, use --no-isolate (default: true)

globals

Inject apis globally

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

Run tests in the browser. Equivalent to --browser.enabled (default: false)

browser.name

  • CLI: --browser.name <name>

Run all tests in a specific browser. Some browsers are only available for specific providers (see --browser.provider).

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

Show Vitest UI when running tests (default: !process.env.CI)

browser.detailsPanelPosition

Default position for the details panel in browser mode. Either right (horizontal split) or bottom (vertical split) (default: right)

browser.connectTimeout

If connection to the browser takes longer, the test suite will fail (default: 60_000)

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

Control if Vitest catches uncaught exceptions so they can be reported (default: true)

browser.trace

Enable trace view mode. Supported: "on", "off", "on-first-retry", "on-all-retries", "retain-on-failure".

browser.traceView.enabled

Enable Vitest trace-view collection for browser tests (default: false)

browser.traceView.recordCanvas

Capture canvas pixels in trace-view snapshots (default: false)

browser.traceView.inlineImages

Inline loaded image pixels in trace-view snapshots (default: false)

browser.locators.exact

Should locators match the text exactly by default (default: true)

pool

  • CLI: --pool <pool>
  • Config: pool

Specify pool, if not running in the browser (default: forks)

execArgv

  • CLI: --execArgv <option>
  • Config: execArgv

Pass additional arguments to node process when spawning worker_threads or child_process.

vmMemoryLimit

Memory limit for VM pools. If you see memory leaks, try to tinker this value.

fileParallelism

Should all test files run in parallel. Use --no-file-parallelism to disable (default: true)

maxWorkers

Maximum number or percentage of workers to run tests in

environment

Specify runner environment, if not running in the browser (default: node)

passWithNoTests

Pass when no tests are found

logHeapUsage

Show the size of heap for each test when running in node

detectAsyncLeaks

Detect asynchronous resources leaking from the test file (default: false)

allowOnly

Allow tests and suites that are marked as only (default: !process.env.CI)

dangerouslyIgnoreUnhandledErrors

Ignore any unhandled errors that occur

changed

  • CLI: --changed [since]
  • Config: changed

Run tests that are affected by the changed files (default: false)

sequence.shuffle.files

Run files in a random order. Long running tests will not start earlier if you enable this option. (default: false)

sequence.shuffle.tests

Run tests in a random order (default: false)

sequence.concurrent

Make tests run in parallel (default: false)

sequence.seed

Set the randomization seed. This option will have no effect if --sequence.shuffle is falsy. Visit "Random Seed" page for more information

sequence.hooks

Changes the order in which hooks are executed. Accepted values are: "stack", "list" and "parallel". Visit sequence.hooks for more information (default: "parallel")

sequence.setupFiles

Changes the order in which setup files are executed. Accepted values are: "list" and "parallel". If set to "list", will run setup files in the order they are defined. If set to "parallel", will run setup files in parallel (default: "parallel")

inspect

  • CLI: --inspect [[host:]port]

Enable Node.js inspector (default: 127.0.0.1:9229)

inspectBrk

  • CLI: --inspectBrk [[host:]port]

Enable Node.js inspector and break before the test starts

testTimeout

Default timeout of a test in milliseconds (default: 5000). Use 0 to disable timeout completely.

hookTimeout

Default hook timeout in milliseconds (default: 10000). Use 0 to disable timeout completely.

bail

  • CLI: --bail <number>
  • Config: bail

Stop test execution when given number of tests have failed (default: 0)

retry.count

Number of times to retry a test if it fails (default: 0)

retry.delay

Delay in milliseconds between retry attempts (default: 0)

retry.condition

Regex pattern to match error messages that should trigger a retry. Only errors matching this pattern will cause a retry (default: retry on all errors)

repeats

  • CLI: --repeats <number>
  • Config: repeats

Repeat every test a specific number of times regardless of the result (default: 0)

diff.aAnnotation

Annotation for expected lines (default: Expected)

diff.aIndicator

Indicator for expected lines (default: -)

diff.bAnnotation

Annotation for received lines (default: Received)

diff.bIndicator

Indicator for received lines (default: +)

diff.commonIndicator

Indicator for common lines (default: )

diff.contextLines

Number of lines of context to show around each change (default: 5)

diff.emptyFirstOrLastLinePlaceholder

Placeholder for an empty first or last line (default: "")

diff.expand

Expand all common lines (default: true)

diff.includeChangeCounts

Include comparison counts in diff output (default: false)

diff.omitAnnotationLines

Omit annotation lines from the output (default: false)

diff.printBasicPrototype

Print basic prototype Object and Array (default: true)

diff.maxDepth

Limit the depth to recurse when printing nested objects (default: 20)

diff.truncateThreshold

Number of lines to show before and after each change (default: 0)

diff.truncateAnnotation

Annotation for truncated lines (default: ... Diff result is truncated)

exclude

  • CLI: --exclude <glob>
  • Config: exclude

Additional file globs to be excluded from test

expandSnapshotDiff

Show full diff when snapshot fails

disableConsoleIntercept

Disable automatic interception of console logging (default: false)

typecheck.enabled

Enable typechecking alongside tests (default: false)

typecheck.only

Run only typecheck tests. This automatically enables typecheck (default: false)

typecheck.checker

Specify the typechecker to use. Available values are: "tsc" and "vue-tsc" and a path to an executable (default: "tsc")

typecheck.allowJs

Allow JavaScript files to be typechecked. By default takes the value from tsconfig.json

typecheck.ignoreSourceErrors

Ignore type errors from source files

typecheck.build

Use TypeScript build mode

typecheck.tsconfig

Path to a custom tsconfig file

typecheck.spawnTimeout

Minimum time in milliseconds it takes to spawn the typechecker

project

  • CLI: -p, --project <name>

The name of the project to run if you are using Vitest workspace feature. This can be repeated for multiple projects: --project=1 --project=2. You can also filter projects using wildcards like --project=packages*, and exclude projects with --project=!pattern. A project runs if it matches no negated pattern and, when regular patterns are also given, matches at least one of them.

slowTestThreshold

Threshold in milliseconds for a test or suite to be considered slow (default: 300)

teardownTimeout

Default timeout of a teardown function in milliseconds (default: 10000)

maxConcurrency

Maximum number of concurrent tests and suites during test file execution (default: 5)

fsModuleCache

Cache transformed modules on the file system and reuse them between reruns (default: false)

fsModuleCachePath

Directory where the fsModuleCache is stored (default: node_modules/.vitest-cache)

expect.requireAssertions

Require that all tests have at least one assertion

expect.poll.interval

Poll interval in milliseconds for expect.poll() assertions (default: 50)

expect.poll.timeout

Poll timeout in milliseconds for expect.poll() assertions (default: 1000)

printConsoleTrace

Always print console stack traces

includeTaskLocation

Collect test and suite locations in the location property

attachmentsDir

The directory where attachments from context.annotate are stored in (default: .vitest/attachments)

run

  • CLI: --run

Disable watch mode

color

  • CLI: --no-color

Removes colors from the console output

clearScreen

  • CLI: --clearScreen

Clear terminal screen when re-running tests during watch mode (default: true)

configLoader

  • CLI: --configLoader <loader>

Use bundle to bundle the config with esbuild or runner (experimental) to process it on the fly. This is only available in vite version 6.1.0 and above. (default: bundle)

standalone

  • CLI: --standalone

Start Vitest without running tests. Tests will be running only on change. If browser mode is enabled, the UI will be opened automatically. This option is ignored when CLI file filters are passed. (default: false)

listTags

  • CLI: --listTags [type]

List all available tags instead of running tests. --list-tags=json will output tags in JSON format, unless there are no tags.

clearCache

  • CLI: --clearCache

Delete all Vitest caches, including the fsModuleCache, without running any tests. This will reduce the performance in the subsequent test run.

tagsFilter

  • CLI: --tagsFilter <expression>

Run only tests with the specified tags. You can use logical operators && (and), || (or) and ! (not) to create complex expressions, see Test Tags for more information.

strictTags

Should Vitest throw an error if test has a tag that is not defined in the config. (default: true)

sharedViteServer

Let inline projects that don't modify the Vite config reuse the Vite server of the config that declares them. (default: true)

experimental.importDurations.print

When to print import breakdown to CLI terminal. Use true to always print, false to never print, or on-warn to print only when imports exceed the warn threshold (default: false).

experimental.importDurations.limit

Maximum number of imports to collect and display (default: 0, or 10 if print or UI is enabled).

experimental.importDurations.failOnDanger

Fail the test run if any import exceeds the danger threshold (default: false).

experimental.importDurations.thresholds.warn

Warning threshold - imports exceeding this are shown in yellow/orange (default: 100).

experimental.importDurations.thresholds.danger

Danger threshold - imports exceeding this are shown in red (default: 500).

experimental.viteModuleRunner

Control whether Vitest uses Vite's module runner to run the code or fallback to the native import. (default: true)

experimental.nodeLoader

Controls whether Vitest will use Node.js Loader API to process in-source or mocked files. This has no effect if viteModuleRunner is enabled. Disabling this can increase performance. (default: true)

experimental.vcsProvider

Custom provider for detecting changed files. (default: git)

experimental.preParse

Parse test specifications before running them. This will apply .only flag and test name pattern across all files without running them. (default: false)

experimental.diagnostics.isolate

Print a hint estimating how much time isolate: false would save when isolate: true spends a significant amount of time spawning a worker per test file. (default: true)

experimental.diagnostics.environment

Print a hint when re-creating a DOM environment for every test file dominates the run and a vm pool would set it up once per worker. (default: true)

experimental.diagnostics.import

Print a hint when test files repeatedly evaluate the same module graph (typical for barrel-file imports) and isolate: false would evaluate it once per worker. (default: true)

experimental.diagnostics.transform

Print a hint when transforming modules dominates the run and fsModuleCache would persist the results across runs. (default: true)

shard

  • 类型: string
  • 默认值: 已禁用

要执行的测试套件分片,格式为 <index>/<count>,其中

  • count 是一个正整数,分割部分的数量
  • index 是一个正整数,分割部分的索引

此命令将所有测试分为 count 个相等的部分,并仅运行恰好位于 index 部分的那些测试。例如,要将测试套件分为三部分,请使用此命令:

sh
vitest run --shard=1/3
vitest run --shard=2/3
vitest run --shard=3/3

WARNING

你不能在启用 --watch 的情况下使用此选项(开发模式下默认启用)。

TIP

如果在未指定输出文件的情况下使用 --reporter=blob,默认路径将包含当前分片配置以及来自 VITEST_BLOB_LABEL 的 blob 标签,或来自 blob reporter 的 label 选项,以避免与其他 Vitest 进程发生冲突。

merge-reports

  • 类型: boolean | string

合并指定文件夹中的所有 blob 报告(默认情况下为 .vitest/blob/)。你可以在此命令中使用任意 reporter(除了 blob):

sh
vitest --merge-reports --reporter=junit