任务元数据
WARNING
Vitest 暴露了实验性的私有 API。破坏性变更可能不遵循 SemVer 规范,使用时请锁定 Vitest 的版本。
如果您正在开发自定义报告器或使用 Vitest Node.js API,您可能会发现将数据从不同执行上下文中的测试传递给您的报告器或自定义 Vitest 处理程序会非常有用。
要实现这一点,依赖 测试上下文 是不可行的,因为它无法被序列化。然而,使用 Vitest,您可以利用每个任务(套件或测试)上的 meta
属性,在测试与 Node.js 进程之间共享数据。请注意,这种通信是单向的,因为 meta
属性只能在测试上下文中修改。Node.js 上下文中的任何修改都不会反映在您的测试中。
您可以在测试上下文或 beforeAll
/afterAll
钩子中为套件任务设置 meta
属性。
ts
afterAll(suite => {
suite.meta.done = true;
});
test('custom', ({ task }) => {
task.meta.custom = 'some-custom-handler';
});
一旦测试完成,Vitest 将使用 RPC 将包含结果和 meta
的任务发送到 Node.js 进程,然后在 onTestCaseResult
及其他可访问任务的钩子中进行报告。要处理该测试用例,您可以使用报告器实现中的 onTestCaseResult
方法:
ts
import type { Reporter, TestCase, TestModule } from 'vitest/node';
export default {
onTestCaseResult(testCase: TestCase) {
// custom === 'some-custom-handler' ✅
const { custom } = testCase.meta();
},
onTestRunEnd(testModule: TestModule) {
testModule.meta().done === true;
testModule.children.at(0).meta().custom === 'some-custom-handler';
},
} satisfies Reporter;
警告
Vitest 使用不同的方法与 Node.js 进程通信。
- 如果 Vitest 在 worker 线程中运行测试,它将通过 消息端口 发送数据。
- 如果 Vitest 使用子进程,数据会通过
process.send
API 以序列化 Buffer 形式发送。 - 如果 Vitest 在浏览器中运行测试,数据将使用 flatted 包转换为字符串。
此属性在 json
报告器中的每个测试上也存在,因此请确保数据可以序列化为 JSON。
此外,请确保在设置 Error 属性 之前将其序列化。
测试运行完成后,您还可以从 Vitest 的状态中获取此信息:
ts
const vitest = await createVitest('test');
const { testModules } = await vitest.start();
const testModule = testModules[0];
testModule.meta().done === true;
testModule.children.at(0).meta().custom === 'some-custom-handler';
在使用 TypeScript 时,还可以扩展类型定义:
ts
declare module 'vitest' {
interface TaskMeta {
done?: boolean;
custom?: string;
}
}