跳至内容

测试运行器

警告

这是高级 API。如果你只是运行测试,你可能不需要它。它主要用于库作者。

你可以在你的配置文件中使用 runner 选项指定你的测试运行器的路径。此文件应该有一个默认导出,其中包含一个实现这些方法的类

ts
export interface VitestRunner {
  /**
   * First thing that's getting called before actually collecting and running tests.
   */
  onBeforeCollect?: (paths: string[]) => unknown
  /**
   * Called after collecting tests and before "onBeforeRun".
   */
  onCollected?: (files: File[]) => unknown

  /**
   * Called when test runner should cancel next test runs.
   * Runner should listen for this method and mark tests and suites as skipped in
   * "onBeforeRunSuite" and "onBeforeRunTask" when called.
   */
  onCancel?: (reason: CancelReason) => unknown

  /**
   * Called before running a single test. Doesn't have "result" yet.
   */
  onBeforeRunTask?: (test: TaskPopulated) => unknown
  /**
   * Called before actually running the test function. Already has "result" with "state" and "startTime".
   */
  onBeforeTryTask?: (test: TaskPopulated, options: { retry: number; repeats: number }) => unknown
  /**
   * Called after result and state are set.
   */
  onAfterRunTask?: (test: TaskPopulated) => unknown
  /**
   * Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
   */
  onAfterTryTask?: (test: TaskPopulated, options: { retry: number; repeats: number }) => unknown

  /**
   * Called before running a single suite. Doesn't have "result" yet.
   */
  onBeforeRunSuite?: (suite: Suite) => unknown
  /**
   * Called after running a single suite. Has state and result.
   */
  onAfterRunSuite?: (suite: Suite) => unknown

  /**
   * If defined, will be called instead of usual Vitest suite partition and handling.
   * "before" and "after" hooks will not be ignored.
   */
  runSuite?: (suite: Suite) => Promise<void>
  /**
   * If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
   * "before" and "after" hooks will not be ignored.
   */
  runTask?: (test: TaskPopulated) => Promise<void>

  /**
   * Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
   */
  onTaskUpdate?: (task: [string, TaskResult | undefined][]) => Promise<void>

  /**
   * Called before running all tests in collected paths.
   */
  onBeforeRunFiles?: (files: File[]) => unknown
  /**
   * Called right after running all tests in collected paths.
   */
  onAfterRunFiles?: (files: File[]) => unknown
  /**
   * Called when new context for a test is defined. Useful, if you want to add custom properties to the context.
   * If you only want to define custom context with a runner, consider using "beforeAll" in "setupFiles" instead.
   *
   * This method is called for both "test" and "custom" handlers.
   *
   * @see https://vitest.vuejs.ac.cn/advanced/runner.html#your-task-function
   */
  extendTaskContext?: <T extends Test | Custom>(context: TaskContext<T>) => TaskContext<T>
  /**
   * Called, when certain files are imported. Can be called in two situations: when collecting tests and when importing setup files.
   */
  importFile: (filepath: string, source: VitestRunnerImportSource) => unknown
  /**
   * Publicly available configuration.
   */
  config: VitestRunnerConfig
}

在初始化此类时,Vitest 会传递 Vitest 配置 - 你应该将其公开为 config 属性。

警告

Vitest 还将 ViteNodeRunner 的实例注入为 __vitest_executor 属性。你可以在 importFile 方法中使用它来处理文件(这是 TestRunnerBenchmarkRunner 的默认行为)。

ViteNodeRunner 公开了 executeId 方法,该方法用于在 Vite 友好的环境中导入测试文件。这意味着它将在运行时解析导入并转换文件内容,以便 Node 可以理解它。

提示

快照支持和其他一些功能依赖于运行器。如果你不想丢失它,你可以从 vitest/runners 导入的 VitestTestRunner 扩展你的运行器。它还公开了 BenchmarkNodeRunner,如果你想扩展基准功能。

你的任务函数

你可以使用你的任务扩展 Vitest 任务系统。任务是一个对象,它是套件的一部分。它会自动使用 suite.task 方法添加到当前套件中

js
// ./utils/custom.js
import { , ,  } from 'vitest/suite'

export { , ,  } from 'vitest'

// this function will be called during collection phase:
// don't call function handler here, add it to suite tasks
// with "getCurrentSuite().task()" method
// note: createTaskCollector provides support for "todo"/"each"/...
export const  = (
  function (, , ) {
    ().(, {
      ...this, // so "todo"/"skip"/... is tracked correctly
      : {
        : true
      },
      : ,
      ,
    })
  }
)
js
// ./garden/tasks.test.js
import { , , ,  } from '../custom.js'
import {  } from './gardener.js'

('take care of the garden', () => {
  (() => {
    .putWorkingClothes()
  })

  ('weed the grass', () => {
    .weedTheGrass()
  })
  .todo('mow the lawn', () => {
    .mowerTheLawn()
  })
  ('water flowers', () => {
    .waterFlowers()
  })

  (() => {
    .goHome()
  })
})
bash
vitest ./garden/tasks.test.js

警告

如果你没有自定义运行器或没有定义 runTest 方法,Vitest 将尝试自动检索任务。如果你没有使用 setFn 添加函数,它将失败。

提示

自定义任务系统支持钩子和上下文。如果你想支持属性链(例如,onlyskip 和你的自定义属性),你可以从 vitest/suite 导入 createChainable 并用它包装你的函数。如果你决定这样做,你需要将 custom 作为 custom.call(this) 调用。