如何检索当前测试'Mocha测试中的名字

How can I retrieve the current test's name within a Mocha test?

本文关键字:测试 Mocha 检索 何检索      更新时间:2023-09-26

对于额外的日志记录,我需要能够打印当前测试的描述。

我该怎么做(用Mocha BDD)?

如果直接在describe的回调中,则可以使用this.title作为describethis.fullTitle()的标题,以获得describe的分层标题(祖先的标题+此标题)。如果您在it的回调中,则可以分别使用this.test.titlethis.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());
    });
});

上面的console.log语句将输出:

top
top
test
top test

下面是一个更完整的例子,展示了标题如何根据嵌套而变化:

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

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

beforeEach中,尝试this.currentTest.title

示例:

beforeEach(function(){
  console.log(this.currentTest.title); 
})

使用Mocha 3.4.1

对于摩卡"^5.1.0",您可以使用console.log(this.ctx.test.title);

在任何测试方法内部

it('test method name'), function()  { var testName= this.test.title; }

您可以使用:

afterEach(function(){
    console.log(this.currentTest.title); //displays test title for each test method      
});

开始:

console.log(this.title);