Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly require modules from mocha.opts file

I'm using the expect.js library with my mocha unit tests. Currently, I'm requiring the library on the first line of each file, like this:

var expect = require('expect.js');

describe('something', function () {
    it('should pass', function () {
        expect(true).to.be(true); // works
    });
});

If possible, I'd like to remove the boilerplate require code from the first line of each file, and have my unit tests magically know about expect. I thought I might be able to do this using the mocha.opts file:

--require ./node_modules/expect.js/index.js

But now I get the following error when running my test:

ReferenceError: expect is not defined

This seems to make sense - how can it know that the reference to expect in my tests refers to what is exported by the expect.js library?

The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:

"Error: Cannot find module './does-not-exist.js'"

Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.

like image 452
Mike Chamberlain Avatar asked Jul 08 '15 03:07

Mike Chamberlain


People also ask

Do mocha tests run in order?

Mocha will run the tests in the order the describe calls execute. @Gnucki Alphabetical order is, by definition, not random.

Which of the following are incompatible with parallel mode when working with mocha in testing?

Incompatible options include --sort , --delay , and importantly, --file . In short, it's because we cannot run tests in any specific order.


1 Answers

You are requiring the module properly but as you figured out, the symbols that the module export won't automatically find themselves into the global space. You can remedy this with your own helper module.

Create test/helper.js:

var expect = require("expect.js")

global.expect = expect;

and set your test/mocha.opts to:

--require test/helper
like image 135
Louis Avatar answered Nov 15 '22 20:11

Louis