Reputation: 379
In my mocha tests I always require the same libs. For example:
var mongoose = require('mongoose'),
User = mongoose.model('User'),
_ = require('underscore');
I want to use them in every test file like this:
describe('xxx', function () {
it('xxx', function (done) {
var user = new User();
done();
});
});
without using any prefix like var user = new somefile.User();
How to do this or are there any better solutions? Thanks.
Upvotes: 1
Views: 491
Reputation: 150614
Basically, this is not possible.
Mocha has a -r
(or --require
in the long version) parameter which helps you to require modules, but as the documentation states:
The
--require
option is useful for libraries such as should.js, so you may simply--require should
instead of manually invokingrequire('should')
within each test file. Note that this works well for should as it augmentsObject.prototype
, however if you wish to access a module's exports you will have to require them, for examplevar should = require('should')
.
What I could imagine as a workaround is to introduce a helper file which basically does nothing but export all the required modules you need using a single module (which basically comes to down to what you suggested with a prefix
):
module.exports = {
mongoose: require('mongoose'),
User: mongoose.model('User'),
_: require('underscore')
};
This allows you to only import one module in your actual test files (the helper file), and access all the other modules as sub-objects, such as:
var helper = require('./helper');
describe('xxx', function () {
it('xxx', function (done) {
var user = new helper.User();
done();
});
});
Probably there is a better name than helper
that you can use, but basically this could be a way to make it work.
Upvotes: 1