首先我要说的是,我对 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');
}
}
您可以使用
this.currentTest.title
获取当前测试的名称
afterEach(function(){
console.log(this.currentTest.title)
})
我发现我使用
this.currentTest.fullTitle()
的次数多于 this.currentTest.title
——我也更喜欢使用 describe
的名字。
如果您有嵌套的描述块,并且由于某种原因您想要分隔标题部分,您可以在
beforeEach
或 afterEach
方法中执行类似以下操作:
function titles(test) {
console.log(test.title)
if (test.parent) {
titles(test.parent)
}
}
titles(this.currentTest)
更现代的严格打字稿兼容解决方案:
afterEach(this: Mocha.Context) {
console.log(this.currentTest?.title)
},