问题描述
我已经编写了一个全局函数来要求我的应用程序/框架的某些文件:
I have written a global function for requiring certain files of my app/framework:
global.coRequireModel = function(name) {
// CRASH happens here
return require.main.require('./api/_co' + name + '/_co' + name + '.model');
}
此模块位于/components/coGlobalFunctions中.
This module is in /components/coGlobalFunctions.
在我的主应用程序app.js中,它是必需的,如下所示:
It is required in my main app app.js like this:
require('./components/coGlobalFunctions');
然后在其他模块中使用我使用的框架中的东西":
Then in other modules using "something" from the framework I use:
var baseScheme = coRequireModel('Base');
这是可行的,但在Mocha测试中不起作用,该测试在require.main.require调用之前给我一个错误:找不到模块".
This works but not in the Mocha tests which give me a "Error: Cannot find module" right before the require.main.require call.
测试似乎来自另一个源文件夹.但是我认为require.main.require可以消除必须相对链接到模块的方面.
It seems that the test is coming from another source folder. But I thought the require.main.require would take out the aspect of having to relatively linking to modules.
生活在api/用户中的示例测试文件:
An example test file living in api/user:
var should = require('should');
var app = require('../../app');
var User = require('./user.model');
...
推荐答案
require.main
指向直接从节点运行的模块.因此,如果您运行node app.js
,则require.main
将指向app.js
.另一方面,如果您使用mocha
运行它,则require.main
将指向摩卡.这可能是您的测试失败的原因.
require.main
points to the module that was run directly from node. So, if you run node app.js
, then require.main
will point to app.js
. If, on the other hand, you ran it using mocha
, then require.main
will point to mocha. This is likely why your tests are failing.
有关更多详细信息,请参见节点文档.
See the node docs of more details.
这篇关于require.main.require可以工作,但是不能在Mocha测试中进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!