跳至內容

測試執行器

警告

這是進階 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.dev.org.tw/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)