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

标签 mocha.js

<分区>

在 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 对象,但它是空的。

最佳答案

如您所见,在 it 的回调中访问 this 是行不通的。这是一种方法:

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 Hook 在测试运行之前获取测试名称并将其保存在 test_name 中。

如果您想知道 this 的值在测试回调中是什么,它就是测试所属套件上的 ctx 字段的值。例如,console.log 中的语句:

describe('suite', function () {
    this.ctx.foo = 1;

    it('test', function () {
        console.log(this);
    });
});

会输出:

{
  "foo": 1
}

关于mocha.js - 如何在 mocha 中访问 describe 和 it 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23947688/

相关文章:

testing - 如何在测试脚本中检查 Hubot 日志输出

javascript - 如何对动态加载javascript文件的javascript代码进行单元测试?

javascript - chai eql 将相等数组报告为不同

node.js - '#' 在 Mocha 中有特殊含义吗?

javascript - 测试 promise 导致未定义的值

javascript - 用 sinon 监视 javascript 中的构造函数

javascript - Mocha : Can't seem to call module's methods that use jQuery from inside mocha tests

node.js - 在 mocha 中测试 nodeJS 时域未正确捕获错误

testing - 如何确保对象数组中的所有项目都具有 mocha 中所有必需的键?

mocha.js - 如何跨各种文件共享 Cypress.io 中的 describe() block ,类似于 Mocha 的 'Shared Behaviour' 设施