Bootstrapping a Mocha test suite

Viewed 6553

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?

4 Answers
describe('异步钩子测试', function () {

  const lover = {
    bodyname: 'yueyue',
    girlname: 'fangfang'
  }

  const test = 'lihang'

  beforeEach('每一个测试之前的钩子', function () {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('通过')
      })
    })
  })

  it('方方爱张越', function () {
    // 是否等于yueuyue
    expect(lover.bodyname).to.equal('yueyue')

    // 是否是一个字符串
    lover.girlname.should.equal('fangfang')
  })
})
Related