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 环境中,此命令将回退到 vitest run

vitest dev

vitest watch 的别名。

仅运行涵盖源文件列表的测试。 适用于静态惰性导入(例如, import('./index.ts') 或者 import index from './index.ts),但不适用于动态导入(例如, 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

选项

TIP

Vitest 支持 CLI 参数的 both camel case 和 kebab case 。例如,--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
  • Config: update

Update snapshot

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

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

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>

mode

  • CLI: --mode <name>
  • Config: mode

Override Vite mode (default: test or benchmark)

isolate

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

globals

Inject apis globally

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

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

browser.api.strictPort

Set to true to exit if port is already in use, instead of automatically trying the next available port

browser.isolate

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

browser.ui

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

browser.fileParallelism

  • CLI: --browser.fileParallelism

Should browser test files run in parallel. Use --browser.fileParallelism=false to disable (default: true)

browser.connectTimeout

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

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

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

allowOnly

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

dangerouslyIgnoreUnhandledErrors

Ignore any unhandled errors that occur

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

  • CLI: --retry <times>
  • Config: retry

Retry the test specific number of times if it fails (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.tsconfig

Path to a custom tsconfig file

typecheck.spawnTimeout

Minimum time in milliseconds it takes to spawn the typechecker

project

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

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 in a suite (default: 5)

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. This option is ignored when CLI file filters are passed. (default: false)

clearCache

  • CLI: --clearCache

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

experimental.fsModuleCache

Enable caching of modules on the file system between reruns.

changed

  • 类型: boolean | string
  • 默认值: false

Run tests only against changed files. If no value is provided, it will run tests against uncommitted changes (including staged and unstaged). To run tests against changes made in the last commit, you can use --changed HEAD~1. You can also pass commit hash (e.g. --changed 09a9920) or branch name (e.g. --changed origin/develop).

When used with code coverage the report will contain only the files that were related to the changes.

If paired with the forceRerunTriggers config option it will run the whole test suite if at least one of the files listed in the forceRerunTriggers list changes. By default, changes to the Vitest config file and package.json will always rerun the whole suite.

shard

  • 类型: string

  • 默认值: disabled

    测试套件分片,格式为 <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 进程发生冲突。

merge-reports

  • 类型: boolean | string

合并位于指定文件夹中的每个 blob 报告(默认情况下为.vitest-reports)。你可以将任何报告程序与此命令一起使用(blob 除外):

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

Released under the MIT License.