2014-09-29 28 views
11

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

如果我使用before()它将只运行整个套件一次,如果我使用beforeEach()它会在每次测试之前执行,所以我试图找到一个中间立场。

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

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”包含一个运行函数之前“套房一个”和“套房两个”

或者,换句话说,在'S1测试一'和'S2测试一'之前,但不在'S1测试二'之前。

可以这样做吗?

回答

15

没有类似于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(); 
    }); 
}); 
+0

这是行得通!谢谢 – FuzzyYellowBall 2014-09-30 11:21:21

4

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

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"); 
    }); 
} 
+1

精美的模块化! – colsen 2016-07-29 21:12:27

0

我发现这种方法为我工作,这补丁更新所有描述套房。从其他的答案

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调用确保,如果他们呼吁this功能,如this.timeout(1000)仍然有效的tests
  • 处理.skip.only意味着您仍然可以使用套件中的套件,例如describe.skip暂时禁止套件。
  • 通过名称替换describe功能可以减少侵入性注射。
    • 这可能不是每个人的口味,在这种情况下,显然是一个别名功能名称可以同时仍利用的调用testsonlyskip正确处理使用。
相关问题