require.main.require工作但不在Mocha测试中

Mat*_*Max 9 unit-testing path require mocha.js node.js

我编写了一个全局函数来要求我的app/framework的某些文件:

global.coRequireModel = function(name) {
    // CRASH happens here
    return require.main.require('./api/_co' + name + '/_co' + name + '.model');
}
Run Code Online (Sandbox Code Playgroud)

该模块位于/ components/coGlobalFunctions中.

它在我的主应用程序app.js中是必需的,如下所示:

require('./components/coGlobalFunctions');
Run Code Online (Sandbox Code Playgroud)

然后在其他模块中使用我使用的框架中的"东西":

var baseScheme = coRequireModel('Base');
Run Code Online (Sandbox Code Playgroud)

这可以工作但不是在Mocha测试中,它在require.main.require调用之前给出了一个"错误:找不到模块".

似乎测试来自另一个源文件夹.但是我认为require.main.require会取出必须相对链接到模块的方面.

编辑:

生活在api/user中的示例测试文件:

var should = require('should');
var app = require('../../app');
var User = require('./user.model');
...
Run Code Online (Sandbox Code Playgroud)

JME*_*JME 7

require.main指向直接从节点运行的模块.所以,如果你跑node app.js,那么require.main将指向app.js.另一方面,如果你使用它来运行它mocha,那么require.main将指向mocha.这可能是您的测试失败的原因.

请参阅节点文档以获取更多详细信息.

  • 这里的最佳做法是什么? (2认同)

小智 5

因为在运行mocha测试时,我的node-webkit应用程序中的require.main不是index.html,所以它左右错误地告诉我们无法解析模块.Hacky修复了​​我的test-helper.js(所有测试中必需的第一件事)修复它:

var path = require('path')
require.main.require = function (name) {
    // navigate to main directory
    var newPath = path.join(__dirname, '../', name)
    return require(newPath)
}
Run Code Online (Sandbox Code Playgroud)

这感觉不对,虽然它有效.有没有更好的方法来解决这个问题?这就像将上述一些解决方案与#7结合起来以使mocha测试工作一样,但是修改main需要只是在测试感觉真的错误时让一切工作正常.

对于其他避免 - "......" - 混乱解决方案,请参见此处:https: //gist.github.com/branneman/8048520