简体   繁体   中英

How to reuse variables in Mocha tests?

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.

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 invoking require('should') within each test file. Note that this works well for should as it augments Object.prototype , however if you wish to access a module's exports you will have to require them, for example var 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM