🏃 Runner 执行引擎
@vitest/runner — 测试执行的"心脏"。定义 suite/test API、管理钩子生命周期、控制并发与重试。
1. 模块定位
Runner 是 Vitest 中唯一不依赖 Vite 的核心模块——这意味着它可以在任何 JS 运行时中使用。它承担三个核心职责:
- 测试 API 定义:
suite/test/describe/it等用户可见的接口 - 执行编排:按正确的顺序运行钩子和测试,管理并发和超时
- 任务模型:定义
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——它持有工厂函数,在文件被实际执行时才展开。
// ★ 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 / todotimeout— 超时时间(从配置/标签继承)retry— 重试配置concurrent— 是否并发执行tags— 标签(用于过滤)meta— 自定义元数据(可被子任务继承)
// ★ 标签优先级排序 + 元数据继承
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 种钩子,分三个层次:
| 钩子 | 作用域 | 执行时机 | 支持 |
|---|---|---|---|
beforeAll | Suite | Suite 开始时 | parallel/stack |
afterAll | Suite | Suite 结束时 | stack(反转) |
beforeEach | Suite | 每个 test 前 | parallel/stack + 父级继承 |
afterEach | Suite | 每个 test 后 | stack(反转)+ 父级继承 |
aroundAll | Suite | 包裹整个 suite | 洋葱模型 |
aroundEach | Suite | 包裹每个 test | 洋葱模型 + 父级继承 |
钩子的父级继承:beforeEach/afterEach/aroundEach 会从父 Suite 递归继承——子 Suite 的测试会先运行父 Suite 的同名钩子。
// ★ 钩子继承实现:递归向上调用父 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()之后的代码
// ★ 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)
// ★ 一个信号量模式的并发限制器
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 判断是否重试:
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 提供结构信息。
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 层叠风格的设计 |