【问题标题】:Jasmine: How to get name of current testJasmine:如何获取当前测试的名称
【发布时间】:2012-09-26 09:38:30
【问题描述】:

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

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

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

【问题讨论】:

  • 仅供参考,expect(result).toBeTruthy 不会测试任何东西,expect(result).toBeTruthy() 会进行测试。
  • 查看此答案以添加 Jasmine 自定义报告器:stackoverflow.com/a/48664485/293280

标签: javascript unit-testing jasmine


【解决方案1】:

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

// current-spec-reporter.js

global.currentSpec = null;

class CurrentSpecReporter {

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

  specDone() {
    global.currentSpec = null;
  }

}

module.exports = CurrentSpecReporter;

添加其他记者时将其添加到 jasmine...

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');
  }

【讨论】:

  • 这是 Jasmine 2+ 中的方法。
【解决方案2】:

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

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

it定义为变量:

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

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

【讨论】:

  • 'it' 不再返回 spec 对象,很遗憾。
  • 这种方法的问题是每个规范需要有不同的变量。例如 let spec = it('name for it', function () { console.log(spec.description); // 打印 "name for it" }); spec = it('name for it 2', function () { console.log(spec.description); // 打印“name for it” });将打印 'name for it 2' 两次
【解决方案3】:
jasmine.getEnv().currentSpec.description

【讨论】:

  • 在 Jasmine 2 中,此功能不再可用。
  • @strongriley:我添加了 Jasmine 2 解决方案。这有点烦人,但它可以相对轻松地完成工作。
猜你喜欢
  • 1970-01-01
  • 2016-05-04
  • 2022-12-25
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多