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

如何在Jest(Jasmine)测试内获取当前执行的测试/describe名称?

在Jest中获取当前测试/describe块名称的解决方案

嘿,这个问题我之前也碰到过!Jest虽然脱胎于Jasmine,但确实砍掉了不少旧的Jasmine API,不过别担心,现在有两种可靠的方式能获取到当前测试的名称:

方法一:利用测试上下文的this.test对象(推荐)

Jest会在每个测试用例的执行上下文里注入this.test对象,里面包含了当前测试的所有元数据——包括测试名称、所属的describe块信息等等。这里要注意:必须用普通函数作为测试回调,不能用箭头函数,不然this会绑定到外层作用域,拿不到正确的对象。

举个和你示例对应的代码:

test('Error missing body', function(done) {
  // 获取当前测试用例的名称
  const currentTestName = this.test.name;
  console.log('Currently executing: ' + currentTestName); // 会输出 "Currently executing: Error missing body"
  
  // 如果还需要获取它所属的describe块名称
  const parentDescribeName = this.test.parent.name;
  console.log('This test belongs to: ' + parentDescribeName);
  
  done();
});

要是你在describe块的钩子(比如beforeEach、afterEach)里想获取describe的名称,同样适用:

describe('User Authentication Tests', function() {
  beforeEach(function() {
    const currentDescribeName = this.test.parent.name;
    console.log('Setting up for describe block: ' + currentDescribeName);
  });

  test('should reject invalid credentials', function() {
    console.log('Running test: ' + this.test.name);
    // 你的测试逻辑...
  });
});

方法二:用expect.getState()(支持箭头函数)

如果你习惯用箭头函数写测试回调,不想改写成普通函数,可以用expect.getState()来获取当前测试的信息,这个方法不依赖this:

test('Error missing body', (done) => {
  const currentTestName = expect.getState().currentTestName;
  console.log('Currently executing: ' + currentTestName);
  done();
});

不过要提一句,expect.getState()返回的结构可能会随Jest版本微调,所以优先推荐第一种方法,兼容性更稳定。

为啥旧的Jasmine方法不管用了?

Jest虽然一开始基于Jasmine,但后来对内部API做了大量重构,像jasmine.getEnv().currentSpec.name这类旧方法已经被移除或者封装起来了,所以没办法再用啦,换成上面的Jest原生方法就没问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:19:33