You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vitest的beforeEach中通过编程获取测试套件及用例名称?

在Vitest的beforeEach中获取测试套件和用例名称

Vitest的beforeEach钩子可以接收一个测试上下文对象,通过这个对象就能直接拿到当前测试套件和测试用例的名称,具体实现如下:

修改你的代码,给beforeEach添加context参数,然后通过context.suite.name获取测试套件名称,context.test.name获取测试用例名称:

beforeEach(async (context) => {
  // 获取测试套件名称
  const suiteName = context.suite.name; // 输出:'Subject Under Test'
  // 获取测试用例名称
  const testName = context.test.name; // 输出:'should behave as expected'
  
  console.log(`当前测试套件:${suiteName}`);
  console.log(`当前测试用例:${testName}`);
})

describe('Subject Under Test', () => {
    test('should behave as expected', async () => {
    });
});

需要注意的是:

  • 当beforeEach在多层嵌套的describe中时,context.suite.name会对应当前所在的最内层测试套件名称
  • 如果是在所有describe外部的顶层beforeEach,context.suite会指向根测试套件,名称通常是项目相关的默认值

内容的提问来源于stack exchange,提问作者Noel Yap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 10:24:51