Jasmine:如何获得当前测试的名称

Gar*_*wen 17 javascript unit-testing jasmine

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

一些(大大简化)代码可能有助于解释.我想避免"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");
    });
});
Run Code Online (Sandbox Code Playgroud)

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

jasmine.currentEnv_.currentSpec.description
Run Code Online (Sandbox Code Playgroud)

或者可能更好:

jasmine.getEnv().currentSpec.description
Run Code Online (Sandbox Code Playgroud)

Gar*_*wen 12

jasmine.getEnv().currentSpec.description
Run Code Online (Sandbox Code Playgroud)

  • 在Jasmine 2中,这已不再可用. (11认同)

Pac*_*ace 8

它不太漂亮(引入了全局变量),但您可以使用自定义报告器来完成:

// current-spec-reporter.js

global.currentSpec = null;

class CurrentSpecReporter {

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

  specDone() {
    global.currentSpec = null;
  }

}

module.exports = CurrentSpecReporter;
Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)


Ian*_*Ian 5

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

it("name for it", function() {});
Run Code Online (Sandbox Code Playgroud)

将 定义it为变量:

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

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

  • 遗憾的是,“它”不再返回规范对象。 (2认同)