2014-12-18 43 views
4

我试图获取当前describebefore钩内,像这样:如何在“before”钩子中获得Mocha测试名称?

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

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

    ... 

}); 

我基本上要检索前的勾了“增加3倍”的字符串。

这是如何实现的?

谢谢!

+0

如果摩卡没有为此提供API,则可以将该名称存储在变量中。尽管如此,它不会阅读。 –

+0

真的..我试图避免这种情况。 –

回答

4

以下是说明了如何可以做到这一点代码:与spec记者

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

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

运行,这将输出:

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


    1 passing (4ms) 

当摩卡调用传递给它的各种功能的功能( describe,before,it等)this的值是Context的对象。此对象的其中一个字段被命名为test。这有点不恰当,因为它可以指向除实际测试之外的其他事物。在像before这样的钩子的情况下,它指向为before调用创建的当前Hook对象。在此对象上调用fullTitle()将为您提供对象的分层名称:对象自己的名称前面是包含它的测试套件名称(describe)。 A Hook对象还有一个指向包含挂钩的套件的parent字段。该套件有一个title字段,它是传递给describe的第一个参数。

相关问题