Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrapping a Mocha test suite

I have numerous tests spread across multiple files in a Node JS application. I'd like to run bootstrap code prior to Mocha's execution of any of the test files. This is so that I can, for example, set globals to be used in each of the actual tests.

Sample bootstrap code

global.chai = require('chai');
global.expect = chai.expect;
global.sinon = require('sinon');

It seems Mocha loads all files under /test alphabetically, so if I name this bootstrap code "bootstrap.js" and everything else with a starting letter after "B" it "works".

Obviously this is fragile and sucky, but I don't want to put this boilerplate requiring of my supporting libraries at the top of every test file.

How do I tell Mocha to load a bootstrap script first, or create something functionally equivalent?

like image 638
Adam Terlson Avatar asked Dec 21 '13 21:12

Adam Terlson


2 Answers

have you tried mocha --require mymodule.js TESTS_DIR

from the documentation

-r, --require

The --require option is useful for libraries such as should.js, so you may simply --require should instead of manually invoking require('should') within each test file. Note that this works well for should as it augments Object.prototype, however if you wish to access a module's exports you will have to require them, for example var should = require('should').

you could also write at the top of each test to load the require("./bootstrap.js") and run tests.

like image 187
Gntem Avatar answered Oct 05 '22 06:10

Gntem


I use mocha's flag --delay

If you need to perform asynchronous operations before any of your suites are run, you may delay the root suite. Simply run Mocha with the --delay flag. This will provide a special function, run(), in the global context.

setTimeout(function() {
    // do some setup

    describe('my suite', function() {
        // ...
    });

    run();
}, 5000);
like image 34
Yuriy Ivanov Avatar answered Oct 05 '22 07:10

Yuriy Ivanov