Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 茉莉花:如何获得当前测试的名称_Javascript_Unit Testing_Jasmine - Fatal编程技术网

Javascript 茉莉花:如何获得当前测试的名称

Javascript 茉莉花:如何获得当前测试的名称,javascript,unit-testing,jasmine,Javascript,Unit Testing,Jasmine,有没有办法获取当前正在运行的测试的名称 一些(高度简化的)代码可能有助于解释。我想避免调用performTest时重复“test1”/“test2”: describe("some bogus tests", function () { function performTest(uniqueName, speed) { var result = functionUnderTest(uniqueName, speed); expect(result).to

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

一些(高度简化的)代码可能有助于解释。我想避免调用
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

对于任何试图在Jasmine 2中做到这一点的人:您可以对您的声明引入一个微妙的更改,但这可以修复它。而不仅仅是做:

it("name for it", function() {});
it
定义为变量:

var spec = it("name for it", function() {
   console.log(spec.description); // prints "name for it"
});
这不需要插件,可以与标准Jasmine一起使用

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

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


仅供参考。
expect(result)。toBeTruthy
不会测试任何东西,
expect(result)。toBeTruthy()
将进行测试。请查看添加Jasmine自定义报告程序的此答案:在Jasmine 2中,此选项不再可用。@strongriley:我已添加到Jasmine 2解决方案中。这有点烦人,但它相对容易完成任务。遗憾的是,“It”不再返回spec对象。这种方法的问题是每个spec都需要不同的变量。例如,让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”});将打印“名称为它2”两次这是在Jasmine 2+中实现的方法。
  it('Should have an accessible description', () => {
    expect(global.currentSpec.description).toBe('Should have an accessible description');
  }