How to properly require modules from mocha.opts file

后端 未结 3 1574
天命终不由人
天命终不由人 2021-02-03 10:52

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         


        
3条回答
  •  别跟我提以往
    2021-02-03 11:50

    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:

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

    or

    class Buzz{...}
    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 (typeof require !== '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");
    

提交回复
热议问题