Skip to content Skip to sidebar Skip to footer

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'); descr

Solution 1:

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:

varexpect = require("expect.js")

global.expect = expect;

and set your test/mocha.opts to:

--require test/helper

Solution 2:

While Louis's answer is spot on, in the end I solved this with a different approach by using karma and the karma-chai plugin:

Install:

npm install karma-chai --save-dev

Configure:

karma.set({

    frameworks: ['mocha', 'chai']
    // ... 
});

Use:

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

Solution 3:

Thanks to Louis answer and a bit of fiddling around I sorted out my test environment references using mocha.opts. Here is the complete setup.

My project is a legacy JavaScript application with a lot of "plain" js files which I wish to reference both in an html file using script tags and using require for unit testing with mocha.

I am not certain that this is good practice but I am used to Mocha for unit testing in node project and was eager to use the same tool with minimal adaptation.

I found that exporting is easy:

classFoo{...}
classBar{...}
if (typeof module !== 'undefined') module.exports = { Foo, Bar };

or

classBuzz{...}
if (typeof module !== 'undefined') module.exports = Buzz;

However, trying to use require in all the files was an issue as the browser would complain about variables being already declared even when enclosed in an if block such as:

if (typeofrequire !== 'undefined') {
    var {Foo,Bar} = require('./foobar.js');    
}

So I got rid of the require part in the files and set up a mocha.opts file in my test folder with this content. The paths are relative to the root folder:

--require test/mocha.opts.js

mocha.opts.js content. The paths are relative to the location of the file:

global.assert = require('assert');global.Foo = require("../foobar.js").Foo;global.Bar = require("../foobar.js").Bar;global.Buzz = require("../buzz.js");

Post a Comment for "How To Properly Require Modules From Mocha.opts File"