javascript 如何在 Mocha 测试中检索当前测试的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18304280/
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
How can I retrieve the current test's name within a Mocha test?
提问by lairtech
For additional logging, I need to be able to print the current test's description.
对于额外的日志记录,我需要能够打印当前测试的描述。
How can I do this (with Mocha BDD)?
我该怎么做(使用 Mocha BDD)?
采纳答案by Dan Kohn
Here you go:
干得好:
console.log(this.title);
回答by Louis
If you are directly inside a callback to describe
, you can use this.title
for the title of the describe
or this.fullTitle()
to get the hierarchical title of the describe
(ancestors' titles + the title of this one). If you are inside a callback to it
you can use this.test.title
or this.test.fullTitle()
respectively. So:
如果您直接在对 的回调中describe
,则可以使用或this.title
的标题来获取(祖先的标题+ 此标题的标题)的分层标题。如果您在回调中,则可以分别使用或。所以:describe
this.fullTitle()
describe
it
this.test.title
this.test.fullTitle()
describe("top", function() {
console.log(this.title);
console.log(this.fullTitle());
it("test", function () {
console.log(this.test.title);
console.log(this.test.fullTitle());
});
});
The console.log
statements above will output:
console.log
上面的语句将输出:
top
top
test
top test
Here's a fuller example that shows how the titles change depending on nesting:
这是一个更完整的示例,显示标题如何根据嵌套而变化:
function dump () {
console.log("running: (fullTitle)", this.test.fullTitle(), "(title)",
this.test.title);
}
function directDump() {
console.log("running (direct): (fullTitle)", this.fullTitle(), "(title)",
this.title);
}
describe("top", function () {
directDump.call(this);
it("test 1", dump);
it("test 2", dump);
describe("level 1", function () {
directDump.call(this);
it("test 1", dump);
it("test 2", dump);
});
});
The console.log
statements will output:
该console.log
语句将输出:
running (direct): (fullTitle) top (title) top
running (direct): (fullTitle) top level 1 (title) level 1
running: (fullTitle) top test 1 (title) test 1
running: (fullTitle) top test 2 (title) test 2
running: (fullTitle) top level 1 test 1 (title) test 1
running: (fullTitle) top level 1 test 2 (title) test 2
回答by Andrew Homeyer
From within a beforeEach
, try this.currentTest.title
.
从内beforeEach
,尝试this.currentTest.title
。
Example:
例子:
beforeEach(function(){
console.log(this.currentTest.title);
})
Using Mocha 3.4.1
.
使用摩卡3.4.1
。
回答by Ken
For mocha "^5.1.0" you can use console.log(this.ctx.test.title);
对于摩卡“^5.1.0”,您可以使用 console.log(this.ctx.test.title);
回答by Amado Saladino
Inside any test method
在任何测试方法中
it('test method name'), function() { var testName= this.test.title; }
and you may use :
你可以使用:
afterEach(function(){
console.log(this.currentTest.title); //displays test title for each test method
});