Global `before` and` beforeEach` for mocha?

I use mocha for unit testing javascript.

I have several test files, each file has before and beforeEach , but they are exactly the same.

How to provide global before and beforeEach for all of them (or some of them)?

+46
javascript unit-testing mocha
May 12 '12 at 6:31
source share
3 answers

Declare before or beforeEach in a separate file (I use spec_helper.coffee ) and require it.

spec_helper.coffee

 afterEach (done) -> async.parallel [ (cb) -> Listing.remove {}, cb (cb) -> Server.remove {}, cb ], -> done() 

test_something.coffee

 require './spec_helper' 
+25
May 12 '12 at 6:36 a.m.
source share

In the root folder of the test, create a global test helper test/helper.js , which has yours before and before each

 // globals global.assert = require('assert'); // setup before(); beforeEach(); // teardown after(); afterEach(); 
+63
Dec 26 '13 at 7:05
source share

Using modules can make it easy to globally configure / disable your test suite. The following is an example of using RequireJS (AMD modules):

First, let's define a test environment with our global install / disable:

 // test-env.js define('test-env', [], function() { // One can store globals, which will be available within the // whole test suite. var my_global = true; before(function() { // global setup }); return after(function() { // global teardown }); }); 

In our JS runner (included in the HTML mocha runner, for other libraries and test files, like <script type="text/javascript">…</script> or better, as an external JS file):

 require([ // this is the important thing: require the test-env dependency first 'test-env', // then, require the specs 'some-test-file' ], function() { mocha.run(); }); 

some-test-file.js can be implemented as follows:

 // some-test-file.js define(['unit-under-test'], function(UnitUnderTest) { return describe('Some unit under test', function() { before(function() { // locally "global" setup }); beforeEach(function() { }); afterEach(function() { }); after(function() { // locally "global" teardown }); it('exists', function() { // let specify the unit under test }); }); }); 
-one
Jul 04
source share



All Articles