如何在mocha中访问describe和it消息?

时间:2014-05-30 05:32:24

标签: mocha

在摩卡,

describe('this message text', function(){
    it('and this message text', function(done){
        console.log(this); // {} is empty
    });
});

如何从测试中访问'this message text' 'and this message text'

我尝试了this对象,但它是空的。

2 个答案:

答案 0 :(得分:5)

正如您所发现的,在this的回调中访问it不起作用。这是一种方法:

describe('this message text', function () {
    var suite_name = this.title;
    var test_name;

    beforeEach(function () {
        test_name = this.currentTest.title;
    });

    it('and this message text', function () {
        console.log(suite_name, test_name);
    });

    it('and this other message text', function () {
        console.log(suite_name, test_name);
    });
});

上面代码中的解决方法是beforeEach挂钩在测试运行之前抓取测试名称并将其保存在test_name中。

如果您想知道this在测试回调中的值是什么,那么它就是测试所属的套件上的ctx字段的值。例如,console.log中的describe('suite', function () { this.ctx.foo = 1; it('test', function () { console.log(this); }); }); 语句:

{
  "foo": 1
}

会输出:

{{1}}

答案 1 :(得分:3)

this.test.parent.title;

套件的Ctx有一个测试对象,它代表当前正在执行的测试,它上面有套件(描述)的父级。

您还可以通过this.test.title等访问当前测试的标题。

此方法允许获取您正在查找的数据(和其他数据),而无需在before()等函数中获取它。

相关问题