[英]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();
而不使用任何前缀,例如
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: Mocha具有
-r
(或长版本中的--require
)参数,该参数可帮助您需要模块,但如文档所述:
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.--require
选项对诸如should.js之类的库很有用,因此您可以简单地--require should
而不是在每个测试文件中手动调用require('should')
。 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')
.请注意,这应该很好,因为它可以
Object.prototype
,但是,如果您希望访问模块的导出,则必须要求它们,例如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
): 我可以想象出一种解决方法是引入一个辅助文件,该文件除了使用单个模块导出所需的所有必需模块外,基本上什么也没做(基本上归结为您建议的带
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. 可以使用比
helper
更好的名称,但是基本上这可以使它起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.