26

有没有办法获取当前正在运行的测试的名称?

一些(高度简化的)代码可能有助于解释。我想避免重复"test1" / "test2"调用performTest

describe("some bogus tests", function () {

    function performTest(uniqueName, speed) {
        var result = functionUnderTest(uniqueName, speed);
        expect(result).toBeTruthy();
    }

    it("test1", function () {
        performTest("test1", "fast");
    });

    it("test2", function () {
        performTest("test2", "slow");
    });
});

更新 我看到我需要的信息在:

jasmine.currentEnv_.currentSpec.description

或者可能更好:

jasmine.getEnv().currentSpec.description
4

3 回答 3

14
jasmine.getEnv().currentSpec.description
于 2012-10-10T07:47:30.517 回答
9

它并不漂亮(引入了一个全局变量),但您可以使用自定义报告器来做到这一点:

// current-spec-reporter.js

global.currentSpec = null;

class CurrentSpecReporter {

  specStarted(spec) {
    global.currentSpec = spec;
  }

  specDone() {
    global.currentSpec = null;
  }

}

module.exports = CurrentSpecReporter;

添加其他记者时将其添加到茉莉花中...

const CurrentSpecReporter = require('./current-spec-reporter.js');
// ...
jasmine.getEnv().addReporter(new CurrentSpecReporter());

然后根据需要在测试/设置期间提取测试名称...

  it('Should have an accessible description', () => {
    expect(global.currentSpec.description).toBe('Should have an accessible description');
  }

于 2019-03-06T01:28:41.113 回答
6

对于尝试在 Jasmine 2 中执行此操作的任何人:您可以对声明进行细微更改,但可以修复它。而不是仅仅做:

it("name for it", function() {});

定义it为变量:

var spec = it("name for it", function() {
   console.log(spec.description); // prints "name for it"
});

这不需要插件并且可以与标准 Jasmine 一起使用。

于 2015-09-17T08:45:40.953 回答