javascript Jasmine:如何获取当前测试的名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12742726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jasmine: How to get name of current test
提问by GarethOwen
Is there a way of getting the name of the currently running test?
有没有办法获取当前正在运行的测试的名称?
Some (heavily simplified) code may help explain. I want to avoid the duplication of "test1" / "test2"
in the calls to performTest
:
一些(高度简化的)代码可能有助于解释。我想避免重复"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");
});
});
UPDATEI see the information I need is in:
更新我看到我需要的信息在:
jasmine.currentEnv_.currentSpec.description
or probably better:
或者可能更好:
jasmine.getEnv().currentSpec.description
采纳答案by GarethOwen
jasmine.getEnv().currentSpec.description
回答by Ian
For anyone attempting to do this in Jasmine 2: You can introduce a subtle change to your declarations however that fix it. Instead of just doing:
对于在 Jasmine 2 中尝试这样做的任何人:您可以对声明进行细微的更改,但是可以修复它。而不是仅仅做:
it("name for it", function() {});
Define the it
as a variable:
将 定义it
为变量:
var spec = it("name for it", function() {
console.log(spec.description); // prints "name for it"
});
This requires no plug-ins and works with standard Jasmine.
这不需要插件并且可以与标准的 Jasmine 一起使用。
回答by Pace
It's not pretty (introduces a global variable) but you can do it with a custom reporter:
它并不漂亮(引入了一个全局变量),但您可以使用自定义报告器来实现:
// current-spec-reporter.js
global.currentSpec = null;
class CurrentSpecReporter {
specStarted(spec) {
global.currentSpec = spec;
}
specDone() {
global.currentSpec = null;
}
}
module.exports = CurrentSpecReporter;
Add it to jasmine when you add your other reporters...
添加其他记者时将其添加到茉莉花中...
const CurrentSpecReporter = require('./current-spec-reporter.js');
// ...
jasmine.getEnv().addReporter(new CurrentSpecReporter());
Then extract the test name during your test/setup as needed...
然后根据需要在测试/设置期间提取测试名称...
it('Should have an accessible description', () => {
expect(global.currentSpec.description).toBe('Should have an accessible description');
}