Making Chai functions global in mocha

Shows how to make the chai “expect”, “spy” etc functions global so you don’t have to keep adding lots of repeating require(…) to every test

So you’ve binned Jasmine and moved to Mocha and everything works great. Except one thing; you keep having to add this to every test:

var chai = require('chai');
var spies = require('chai-spies');
var expect = chai.expect;

This is clearly sub-optimal.

Fortunately there is a simple way to set globals with Mocha. First you need to edit your mocha.opts file to point to a file you’d like to include in all your tests:

--require ./test/_includes.js

Now make expect and spy global:

var chai = require('chai');
global.spy = chai.spy;
global.expect = chai.expect;

Obviously this can be tailored to your specific needs.

Tags: , , , ,

Leave a Reply