任務中繼資料
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 在工作執行緒中執行測試,它將透過 訊息埠 傳送資料。
- 如果 Vitest 使用子進程,資料將透過
process.send
API 以序列化的 Buffer 形式傳送。 - 如果 Vitest 在瀏覽器中執行測試,資料將使用 flatted 套件進行字串化。
此屬性也存在於 json
報告器中的每個測試上,因此請確保資料可以序列化為 JSON 格式。
此外,請確保在設定 錯誤屬性之前將其序列化。
當測試執行完成後,您也可以從 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;
}
}