Skip to content

快速起步 advanced

注意

本指南列出了通过 Node.js 脚本运行测试的高级 API。如果你只是想 运行测试,你可能不需要这些内容。这些 API 主要用于库作者。

你可以从 vitest/node 入口点导入任何方法。

startVitest

ts
function startVitest(
  cliFilters: string[] = [],
  options: CliOptions = {},
  viteOverrides?: ViteUserConfig,
  vitestOptions?: VitestOptions,
): Promise<Vitest>

你可以使用 Vitest 的 Node API 开始运行测试:

js
import { startVitest } from 'vitest/node'

const vitest = await startVitest()

await vitest.close()

startVitest 函数如果可以启动测试,将返回一个 Vitest 实例。

如果未启用监视模式,Vitest 将自动调用 close 方法。

如果启用了监视模式且终端支持 TTY,Vitest 将注册控制台快捷键。

你可以将过滤器列表作为第二个参数传递。Vitest 将仅运行文件路径中包含至少一个传递字符串的测试。

此外,你可以使用第三个参数传递 CLI 参数,这些参数将覆盖任何测试配置选项。或者,你可以将完整的 Vite 配置作为第四个参数传递,这将优先于任何其他用户定义的选项。

运行测试后,你可以从 state.getTestModules API 获取结果:

ts
import type { TestModule } from 'vitest/node'

const vitest = await startVitest()

console.log(vitest.state.getTestModules()) // [TestModule]

提示

“运行测试” 指南中有使用示例。

createVitest

ts
function createVitest(
  options: CliOptions,
  viteOverrides: ViteUserConfig = {},
  vitestOptions: VitestOptions = {},
): Promise<Vitest>

你可以使用 createVitest 函数创建一个 Vitest 实例。它返回与 startVitest 相同的 Vitest 实例,但不会启动测试也不会验证已安装的包。

js
import { createVitest } from 'vitest/node'

const vitest = await createVitest('test', {
  watch: false,
})

提示

“运行测试” 指南中有使用示例。

resolveConfig

ts
function resolveConfig(
  options: UserConfig = {},
  viteOverrides: ViteUserConfig = {},
  harness?: PluginHarness,
): Promise<ResolvedViteConfig>

此方法使用自定义参数解析配置,而不会创建 Vite 服务器。如果未提供任何参数,root 将设为 process.cwd()。

It returns the resolved Vite config. The fully resolved Vitest config, including every project, lives on its test property.

ts
import { resolveConfig } from 'vitest/node'

const viteConfig = await resolveConfig({
  mode: 'custom',
  configFile: false,
  resolve: {
    conditions: ['custom']
  },
  test: {
    setupFiles: ['/my-setup-file.js'],
    pool: 'threads',
  },
})

viteConfig.test.pool // 'threads'

说明

由于 Vite 的 createServer 工作方式, Vitest 必须在插件的 configResolve 钩子中解析配置。因此,此方法实际上并未在内部使用,而是仅作为公共 API 暴露。如果你将配置传递给 startVitestcreateVitest API , Vitest 仍然会重新解析配置。

注意

resolveConfig 不会解析 workspace。要解析工作区配置, Vitest 需要一个已建立的 Vite 服务器。

另外请注意,viteConfig.test 不会被完全解析。如果你需要 Vitest 配置,请使用 vitestConfig 代替。

Project Configuration Resolution

This section describes how the arguments of startVitest, createVitest, and resolveConfig interact with test projects. Without projects, all resolved options apply to the single root project and none of this matters.

The root configuration is resolved from three inputs, in ascending priority:

  1. the root config file
  2. viteOverrides, merged on top of the config file values
  3. CLI options (options), applied on top of everything else

Every project then resolves its own Vite config independently:

  • A project referenced as a config file or a directory resolves only its own file. It does not inherit any options from the root configuration.
  • An inline project inherits the root configuration by default (see extends): the root config file is re-executed for the project, viteOverrides are merged on top of it, and the project's own options are merged last. Inheritance works even when there is no root config file, because viteOverrides are part of the effective root configuration.
  • With extends: false, an inline project resolves only its own options. With extends: './path', the referenced file is re-executed instead of the root config file, and viteOverrides are not merged.

A few options are excluded from inheritance:

  • plugins from viteOverrides are never inherited. A config file is re-executed for every project, which creates fresh plugin instances, but plugin instances passed in viteOverrides belong to the root Vite server and cannot be shared with project servers.
  • test.browser and test.tagsFilter from viteOverrides are never inherited: browser describes the instances of a single project, and tagsFilter applies to the whole run.
  • name and projects are never inherited; the root globalSetup is not inherited because it already runs once per test run.
  • The project's own tags always replace the tags array merged from an extended config instead of being concatenated with it, so the same tag names can be redefined.

Independently of extends, two groups of options reach every project:

  • A fixed subset of CLI options that configure how tests run (--testTimeout, --retry, --pool, and similar) is applied to every project at the highest priority, mirroring the root resolution.
  • Run-level options only make sense for the test run as a whole: every project receives the root's resolved coverage, attachmentsDir, and mergeReportsLabel values.

parseCLI

ts
function parseCLI(argv: string | string[], config: CliParseOptions = {}): {
  filter: string[]
  options: CliOptions
}

你可以使用此方法来解析 CLI 参数。它接受一个字符串(其中参数以单个空格分隔)或一个与 Vitest CLI 使用的格式相同的 CLI 参数字符串数组。它返回一个过滤器和 options,你可以在稍后传递给 createViteststartVitest 方法。

ts
import { parseCLI } from 'vitest/node'

const result = parseCLI('vitest ./files.ts --coverage --browser=chrome')

result.options
// {
//   coverage: { enabled: true },
//   browser: { name: 'chrome', enabled: true }
// }

result.filter
// ['./files.ts']

createCLI

ts
function createCLI(options?: CliParseOptions): CAC

Creates the Vitest command-line interface: a cac instance with all of Vitest's commands and options registered. parseCLI is built on top of it; use createCLI directly if you need the raw parser.

ts
import { createCLI } from 'vitest/node'

const cli = createCLI()

PluginHarness

ts
class PluginHarness {
  vitest?: Vitest
  version: string
  logger: Logger
  packageInstaller: VitestPackageInstaller
  getVitest(): Vitest
}

A container that Vitest passes to its internal plugins while the config is being resolved, before a Vitest instance exists. It holds the Logger, the package installer and the resolved version, and exposes the Vitest instance via getVitest() once it has been created (calling it earlier throws).

This is an advanced, plugin-facing API. You rarely construct one directly, but you can pass a shared instance to resolveConfig to reuse a logger and package installer.

Logger

ts
class Logger {
  constructor(
    outputStream?: Writable,
    errorStream?: Writable,
  )
}

Vitest's terminal logger, exposed as vitest.logger. It handles formatted output, the error summary, the run banner and screen clearing. Construct one with custom stdout/stderr streams to capture or redirect Vitest's output when running it programmatically.

ts
import { Logger } from 'vitest/node'

const logger = new Logger(process.stdout, process.stderr)