网站搜索

javascript - 如何在 “before” 钩子中获取 Mocha 测试名称?


我正在尝试在 before 钩子中获取当前 describe 名称,像这样:

describe('increasing 3 times', function() {

  before(function() {
    console.log('test name');
  });

  ...

});

我基本上想在 before 钩子中获取 '增加三倍' 字符串。

这如何才能实现?

谢谢!

答案#1

下面是演示如何操作的代码:

describe("top", function () {
    before(function () {
        console.log("full title:", this.test.fullTitle());
        console.log("parent title:", this.test.parent.title);
    });

    it("test 1", function () {});
});

使用 spec 报告器运行,这将输出:

full title: top "before all" hook
parent title: top
    ✓ test 1 


  1 passing (4ms)

当 Mocha 调用你传递给它的各种函数(describe、before、it 等)时,this 的值是一个 Context 对象。这个对象的一个字段名为 test。这个名称有点误导,因为它可能指向除实际测试之外的其他东西。在像 before 这样的钩子中,它指向为该 before 调用创建的当前 Hook 对象。在这个对象上调用 fullTitle() 将会得到对象的层级名称:对象本身的名称前面是包含它的测试套件(describe)的名称。Hook 对象还有一个 parent 字段,它指向包含该钩子的套件。套件中有一个 title 字段,它是传递给 describe 的第一个参数。