在mocha中获取afterEach函数中的测试名称

时间:2013-07-27 00:53:13

标签: node.js mocha

首先让我说我对node.js和mocha很新。它只是让我失望。我开始使用tdd方法,我正在尝试从beforeEach和afterEach函数中开始或刚刚完成的测试,但我没有运气。(我最感兴趣的是afterEach)。至少我无法想出一个干净利落的方式。我唯一能想到的是将测试和套件保存在变量中,然后在afterEach()上进行一些匹配以查看哪个测试已经完成。

理想情况下,它说“测试名称”我希望有类似suite.test.name

的内容
suite('my test suite', function() {
    beforeEach(function () {
        console.log('test name');
    });
    test('first test', function (done) {
        var testarray = ['1', '3', '5', '7'];
        testarray.forEach(function(num, index) {
            console.log('num: ' + num + ' index: ' + index);
        }, 
        done());
    });
    afterEach(){
        console.log('test name');
    }
}

3 个答案:

答案 0 :(得分:22)

您可以使用this.currentTest.title

获取当前测试的名称
afterEach(function(){
    console.log(this.currentTest.title)
})

答案 1 :(得分:12)

我发现我使用的this.currentTest.fullTitle()超过this.currentTest.title - 我更喜欢拥有describe名称。

答案 2 :(得分:0)

如果您有嵌套的描述块,并且由于某种原因您希望将标题部分分开,则可以使用beforeEachafterEach方法执行以下操作:

function titles(test) {
    console.log(test.title)
    if (test.parent) {
        titles(test.parent)
    }
}

titles(this.currentTest)
相关问题