1. 模块定位

Runner 是 Vitest 中唯一不依赖 Vite 的核心模块——这意味着它可以在任何 JS 运行时中使用。它承担三个核心职责:

  1. 测试 API 定义:suite/test/describe/it 等用户可见的接口
  2. 执行编排:按正确的顺序运行钩子和测试,管理并发和超时
  3. 任务模型:定义 Suite / Test / File 等任务类型及其状态机

🎯 独立设计

Runner 与 Vite 完全解耦。它只接收一个 VitestRunner 接口(定义了 import 模块的能力),不关心模块从哪里来——可以是 Vite SSR、Node import()、甚至是浏览器的 <script> 标签。

2. 执行架构

sequenceDiagram
    participant O as 调度器
(core.ts) participant W as Worker participant R as Runner
(run.ts) participant S as Suite
(suite.ts) O->>W: 分配测试文件 W->>R: startTests(specs) R->>S: runSetupFiles() Note over R: for each file R->>S: collectSuite(file) S-->>R: Suite tree R->>R: beforeAll hooks loop for each test R->>R: aroundAll hooks R->>R: beforeEach hooks R->>S: execute test fn R->>R: afterEach hooks end R->>R: afterAll hooks R-->>W: test results

图:Runner 执行时序 —— 从调度到测试结果的完整流程

3. Suite & Test 定义

Runner 使用一个惰性收集模型:当调用 suite(name, fn) 时,不会立即创建 Suite 对象,而是创建一个 SuiteCollector——它持有工厂函数,在文件被实际执行时才展开。

packages/runner/src/suite.ts:305-317IDE 打开
// ★ SuiteCollector: 惰性收集器 —— 延迟执行 suite 工厂函数
function createSuiteCollector(
  name: string,
  factory: SuiteFactory = () => {},
  mode: RunMode,
  each?: boolean,
  suiteOptions?: SuiteOptions,
) {
  const tasks: (Test | Suite | SuiteCollector)[] = []
  let suite!: Suite
  initSuite(true)
  // ... 工厂在文件实际运行时才调用
}

Test 函数内部会创建一个完整的 Task 对象,包含:

  • id — 运行时自动分配
  • fullName — 整个 suite 层级拼接的名称
  • mode — run / skip / only / todo
  • timeout — 超时时间(从配置/标签继承)
  • retry — 重试配置
  • concurrent — 是否并发执行
  • tags — 标签(用于过滤)
  • meta — 自定义元数据(可被子任务继承)
packages/runner/src/suite.ts:342-403IDE 打开
// ★ 标签优先级排序 + 元数据继承
const tagsOptions = testTags
  .map((tag) => { /* 查找 tag 定义 */ })
  .sort((tag1, tag2) =>
    (tag2.priority ?? POSITIVE_INFINITY) - (tag1.priority ?? POSITIVE_INFINITY))
  // 高优先级的标签排前面 → 低优先级的配置先被覆盖
  .reduce((acc, tag) => {
    const { name, description, priority, meta, ...options } = tag
    Object.assign(acc, options)
    return acc
  }, {} as TestOptions)

// ★ 元数据继承链: Tag Meta → Suite Meta → Test Meta
const testMeta = Object.create(null)
if (tagMeta) Object.assign(testMeta, tagMeta)
if (parentMeta) Object.assign(testMeta, parentMeta)
if (testOwnMeta) Object.assign(testMeta, testOwnMeta)
🧠 标签配置继承的设计意图

为什么标签要按优先级排序?Vitest 支持为标签关联配置(如超时时间、并发等)。多个标签可能冲突——通过 优先级(priority)机制,高优先级标签的配置覆盖低优先级的,与 CSS 层叠类似。这是一种优雅的冲突解决策略。

4. 钩子系统

Runner 支持 6 种钩子,分三个层次:

钩子作用域执行时机支持
beforeAllSuiteSuite 开始时parallel/stack
afterAllSuiteSuite 结束时stack(反转)
beforeEachSuite每个 test 前parallel/stack + 父级继承
afterEachSuite每个 test 后stack(反转)+ 父级继承
aroundAllSuite包裹整个 suite洋葱模型
aroundEachSuite包裹每个 test洋葱模型 + 父级继承

钩子的父级继承:beforeEach/afterEach/aroundEach 会从父 Suite 递归继承——子 Suite 的测试会先运行父 Suite 的同名钩子。

packages/runner/src/run.ts:167-224IDE 打开
// ★ 钩子继承实现:递归向上调用父 Suite 的钩子
export async function callSuiteHook(suite, currentTask, name, runner, args) {
  const callbacks: unknown[] = []
  const parentSuite = 'filepath' in suite ? null : suite.suite || suite.file

  // ★ beforeEach 递归到父 Suite
  if (name === 'beforeEach' && parentSuite) {
    callbacks.push(
      ...(await callSuiteHook(parentSuite, currentTask, name, runner, args)),
    )
  }

  const hooks = getSuiteHooks(suite, name, sequence)
  if (sequence === 'parallel') {
    callbacks.push(...(await Promise.all(hooks.map(hook => runHook(hook)))))
  } else {
    for (const hook of hooks) callbacks.push(await runHook(hook))
  }

  // ★ afterEach 也在当前 Suite 之后调用父级
  if (name === 'afterEach' && parentSuite) {
    callbacks.push(...(await callSuiteHook(parentSuite, currentTask, name, runner, args)))
  }
  return callbacks
}

5. Around Hooks — 洋葱模型

aroundEach 和 aroundAll 是 Vitest 独有的高级钩子,实现了一个洋葱模型:

graph LR
    A[aroundEach setup] --> B[beforeEach] --> C[test fn] --> D[afterEach] --> E[aroundEach teardown]

图:aroundEach 包裹结构 —— setup 在 beforeEach 之前,teardown 在 afterEach 之后

每个 around hook 接收一个 use() 回调——调用它才会执行内层逻辑:

  • setup 阶段:hook 被调用 → 执行用户代码(setup 逻辑)→ 调用 use()
  • teardown 阶段:use() 返回后 → 执行 use() 之后的代码
packages/runner/src/run.ts:263-399IDE 打开
// ★ callAroundHooks: 实现洋葱模型的 setup/teardown 分离
const use = async () => {
  // ⚠️ setup 超时检查:防止 hook 长时间不调 use()
  if (setupTimeout.isTimedOut()) throw new Error('__VITEST_INTERNAL_…')
  if (useCalled) throw new AroundHookMultipleCallsError('use() called twice')
  useCalled = true
  setupTimeout.clear()  // ★ setup 完成 → 清除 setup 计时器

  await runNextHook(index + 1)  // ★ 执行内层逻辑(递归)

  // ★ 启动 teardown 计时器
  teardownTimeout = createTimeoutPromise(timeout, 'teardown', stackTraceError)
}
💡 实际应用

aroundEach 的典型用法:在 setup 中创建数据库事务,测试在事务中运行,teardown 时回滚——保证测试之间完全隔离。这比 beforeEach + afterEach 更语义化,也更容易处理异步清理。

6. 并发控制

Runner 使用 limitConcurrency 进行并发限制:

  • maxConcurrency:全局最大并发数(默认 5)
  • sequence.concurrent:是否允许 test 并发执行
  • sequence.hooks:钩子执行策略(parallel / stack)
packages/runner/src/utils/limit-concurrency.ts
// ★ 一个信号量模式的并发限制器
export function limitConcurrency(maxConcurrency = 5): ConcurrencyLimiter {
  let running = 0
  const queue: (() => void)[] = []

  return {
    run: async <T>(fn: () => Promise<T>): Promise<T> => {
      await this.acquire()
      try { return await fn() }
      finally { this.release() }
    },
    acquire: async () => {
      if (running < maxConcurrency) { running++; return }
      return new Promise(resolve => queue.push(resolve))
    },
    release: () => { running--; queue.shift()?.() },
  }
}

7. 重试机制

Vitest 的重试有三个维度:retry.count(重试次数)、retry.delay(延迟毫秒)、retry.condition(条件匹配)。一个测试失败时,Runner 会按 condition 判断是否重试:

packages/runner/src/run.ts:45-75
function getRetryCount(retry): number { /* 支持 number 和 { count } 两种配置 */ }
function getRetryDelay(retry): number { /* 支持 { delay } 配置 */ }
function getRetryCondition(retry): RegExp | ((error) => boolean) {
  // ★ 支持正则匹配错误消息 或 自定义条件函数
}

8. 文件收集(collectTests)

在执行测试之前,Runner 需要收集 Suite 结构。每个文件通过 createFileTask 创建一个 File task,然后执行文件中的 suite() / test() 调用,构建一棵 Suite/Test 树——这个阶段不执行实际的测试函数,只为后续的 startTests 提供结构信息。

packages/runner/src/collect.ts:23-65IDE 打开
export async function collectTests(specs, runner): Promise<File[]> {
  const files: File[] = []
  for (const spec of specs) {
    const file = createFileTask(filepath, config.root, config.name, runner.pool, ...)
    file.shuffle = config.sequence.shuffle
    // ★ 运行文件 → 收集 suite/test 调用 → 构建任务树
    files.push(file)
  }
  return files
}

9. "如果我来写" 对比思考

🧠 问题:如何处理测试超时?

直觉方案:Promise.race(testFn, timeout)——简单、直接。

Vitest 的做法:使用 setTimeout + performance.now() 双重检查(见 context.ts:40-80)。在 Promise resolve 时复检 elapsed time——因为 setTimeout 可能因事件循环繁忙而延迟触发,而微任务可能在超时后仍然执行。

差异分析:Promise.race 只会在 setTimeout 触发时 reject,但如果测试在微任务中耗时过长(比如一个巨大的同步循环),Promise.race 会等到 setTimeout 触发才 reject,而 Vitest 在 Promise resolve 时主动检查时间。这源于 GitHub Issue #2920 的真实 Bug:测试函数同步耗时超过 timeout,但 setTimeout 未触发。

🧠 问题:钩子执行顺序如何管理?

直觉方案:硬编码执行顺序——beforeAll → beforeEach → test → afterEach → afterAll。

Vitest 的做法:sequence.hooks 配置 + beforeEach 向上递归继承。支持 parallel(并发执行同级钩子)和 stack(顺序执行,afterAll 反转)。

差异分析:硬编码无法满足"父 Suite 的 beforeEach 也要在子 Suite 的 test 前执行"这种场景。递归继承 + 运行时配置让钩子系统变得可组合——每个 Suite 只声明自己的钩子,执行时由框架递归组装。

🧠 问题:如何保证并发安全?

直觉方案:使用 Promise.all 并行执行所有测试。

Vitest 的做法:limitConcurrency 信号量 + suite.concurrent 逐测试控制。每个 Task 有独立的 concurrent 标志,未标记的测试即使全局开启了并发也会顺序执行。

差异分析:全量 Promise.all 会导致数据库连接池耗尽、文件描述符不够等资源问题。逐测试控制 + 全局限流 = 精细化的并发策略,让用户可以对包含副作用的测试关闭并发。

10. 学习要点

🏗️ 学习主题关键收获
惰性收集模型SuiteCollector 延迟执行工厂函数——分离"定义"与"执行"
递归钩子继承beforeEach 向上递归,实现父 Suite 钩子被子 Suite 继承
洋葱模型aroundEach setup/teardown 分离——比 before/after 更灵活的包裹模式
超时双重检查setTimeout + performance.now() 解决微任务超时问题
信号量并发limitConcurrency 实现可配置的并发限制
标签优先级配置继承 + 优先级排序——CSS 层叠风格的设计