在每个套件之前运行Mocha设置,而不是在每个testing之前

使用NodeJS和Mocha进行testing。 我想我明白before()和beforeEach()是如何工作的。 问题是,我想添加一个在每个“描述”之前运行的安装脚本,而不是在每个“它”之前运行。

如果我before()使用它,整个套件只运行一次,如果使用beforeEach()它会在每次testing之前执行,所以我试图find一个中间的基础。

所以,如果这是我的testing文件:

 require('./setupStuff'); describe('Suite one', function(){ it('S1 Test one', function(done){ ... }); it('S1 Test two', function(done){ ... }); }); describe('Suite two', function(){ it('S2 Test one', function(done){ ... }); }); 

我希望“setupStuff”包含一个在“套件一”和“套件二”之前运行的函数,

或者换句话说,在“S1testing一”和“S2testing一”之前,而不是在“S1testing二”之前。

可以这样做吗?

没有任何类似beforeEachbefore那样做你想要的。 但这不是必须的,因为你可以这样做:

 function makeSuite(name, tests) { describe(name, function () { before(function () { console.log("shared before"); }); tests(); after(function () { console.log("shared after"); }); }); } makeSuite('Suite one', function(){ it('S1 Test one', function(done){ done(); }); it('S1 Test two', function(done){ done(); }); }); makeSuite('Suite two', function(){ it('S2 Test one', function(done){ done(); }); }); 

你也可以用更灵活的方式来做到这一点:

 require('./setupStuff'); describe('Suite one', function(){ loadBeforeAndAfter(); //<-- added it('S1 Test one', function(done){ ... }); it('S1 Test two', function(done){ ... }); }); describe('Suite two', function(){ loadBeforeAndAfter();//<-- added it('S2 Test one', function(done){ ... }); }); describe('Suite three', function(){ //use some other loader here, before/after, or nothing it('S3 Test one', function(done){ ... }); }); function loadBeforeAndAfter() { before(function () { console.log("shared before"); }); after(function () { console.log("shared after"); }); } 

我发现这种方法为我工作,它修补所有描述套件。

 function suitePatches() { before(function() { // before suite behaviour }); after(function() { // after suite behaviour }); } let origDescribe = describe; describe = function(n,tests) { origDescribe(n,function() { suitePatches(); tests.bind(this)(); }); } let origOnly = origDescribe.only; describe.only = function(n,tests) { origOnly(n,function() { suitePatches(); tests.bind(this)(); }); } describe.skip = origDescribe.skip; 

与其他答案的区别是:

  • 使用bind来调用tests ,确保如果他们调用this函数,如this.timeout(1000)仍然可以工作。
  • 处理.skip.only意味着你仍然可以使用你的套件,例如describe.skip来临时压缩套件。
  • 用名称replacedescribe函数可以减less侵入性注入。
    • 这可能不符合每个人的口味,在这种情况下,显然可以使用替代的函数名称,同时仍然使用调用tests的正确处理,并且only skip