Mocha Test Suite

I have many tests distributed across multiple files in a Node JS application. I would like to run bootstrap code before Mocha executes any of the test files. This means that I can, for example, set global values ​​for each of the actual tests.

Example boot code

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

Mocha seems to download all the files under / test in alphabetical order, so if I call this bootstrap code “bootstrap.js” and everything else with the start letter after “B”, it “works”.

Obviously, this is fragile and juicy, but I do not want to put this template, which requires my supporting libraries at the beginning of each test file.

How do I tell Mocha to first load the boot script file or create something functionally equivalent?

+8
mocha
source share
3 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 can simply - write the request instead of manually calling require ('should') in each test file. Note that this works well for should, as it increases Object.prototype, however, if you want to access you can require them, for example var should = require ('should').

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

+9
source share

I use the mocha flag --delay

If you need to perform asynchronous operations before any of your packages are running, you can defer the root package. Just run Mocha with the -delay flag. This will provide a special function, run (), in a global context.

 setTimeout(function() { // do some setup describe('my suite', function() { // ... }); run(); }, 5000); 
+2
source share

If before starting Mocha you want to first run some boot code in a file that uses the syntax of the ECMAScript 2015 module (i.e. import instead of require )

  • Create the following files:

./setupBabel.js (for bootstrap Babel transpiler)

 require('babel-polyfill'); require('babel-register'); 

./setupDependencies.js (for bootstrap Chai and Sinon using ES2015 syntax)

 import chai from 'chai'; import sinon from 'sinon'; global.expect = chai.expect; global.sinon = sinon; 

./test/codeSpec.js (Unit Test example using the syntaxes of Chai, Sinon Stubs, Spies and ES2015, such as arrow functions, let and const )

 describe('test suite', () => { it('does not modify immutable constant value', () => { const myStub = sinon.stub(); const mySpy = sinon.spy(myStub); myStub.returns({}); let val = 1; expect(val).to.not.equal(2); sinon.assert.notCalled(mySpy); }); }); 
  • Run the following terminals to install the appropriate NPM packages:

npm install babel-polyfill babel-register chai sinon mocha

  • Run the test suite using the following terminal command and flags:

mocha --require ./setupBabel.js --require ./setupDependencies.js ./test/codeSpec.js

0
source share

All Articles