9

I know about before, beforeEach, after and afterEach but how do I run some code before ALL tests.

In other words I files like this

test
  test1.js
  test2.js
  test3.js

I run the tests with

mocha --recursive

I don't want to have to put a before in every test file. I need a beforeAllTests or a --init=setup.js or something that I can execute some JavaScript before any tests have been executed. In this particular case I have to configure my system's logging module before the tests run

Is there a way to call some init function that get executed before all tests?

gman
  • 100,619
  • 31
  • 269
  • 393

3 Answers3

5

If only initialization code is required, then mocha -r ./init might be enough for you. even put it into test/mocha.opts

--require ./test/init
--ui tdd

But if you need teardown actions, there is a dilemma, for example:

var app = require('../app.js');
app.listen(process.env.WEB_PORT);

after(function(done) {
    var db = mongoskin.db(process.env.DB_URL, {safe:true});
    db.dropDatabase(function(err) {
        expect(err).to.not.be.ok();
        db.close(done);
    });
});

you'll get the error:

ReferenceError: after is not defined

I guess mocha hasn't been initialized itself while handling '--require'.

Simon Shi
  • 106
  • 1
  • 6
3

I figured it out recently in our node app:

  1. reorganize test files as below (only one js file "bootstrap.js" under test/, and put all test files in sub folders):
       test
       ├──unit
       │  ├── test1
       │  ├── test2
       │  └── ...
       ├──integeration
       │  ├── test1
       │  ├── test2
       │  └── ...
       ├── bootstrap.js
       └── mocha.opts
    
  2. put '--recursive' into mocha.opts
  3. put your initialization code into bootstrap.js (global before/after works here!)

done.

Simon Shi
  • 106
  • 1
  • 6
  • 2
    Depends on the name of your file. In your case `bootstrap.js` starts with `b` so it's the first to be found by --recursive mocha. – drinchev Oct 02 '16 at 09:10
  • This was my fave answer until I found my new approach - see my answer (which is the official mocha solution) – danday74 Jan 26 '17 at 14:56
3

This is the official mocha solution:

Mocha tests with extra options or parameters

It allows you to define code that can be:

1 - Executed before npm start and npm test

2 - Executed before npm test only

Community
  • 1
  • 1
danday74
  • 52,471
  • 49
  • 232
  • 283