包括摩卡单元测试中的模块

时间:2015-11-21 08:07:45

标签: javascript node.js unit-testing mocha

我试图将我制作的模块luaScripts.js包含在mocha单元测试中。以下是单元测试中包含的内容:

test.js

luaScripts = require("../app/luaScripts.js");

在luaScripts.js中,我包含对配置文件的引用:

luaScripts.js

var fs = require("fs"),
nconf = require("nconf");

nconf.file({ file: "../../config.json" });
var config = nconf.get("dev");

当我尝试运行单元测试时,它失败了;原因是var config未定义'因为包含的luaScripts.js无法从config.json读取,似乎mocha正在运行测试目录级别低于预期。如果我将luaScripts.js中的路径更改为以下内容:

nconf.file({ file: "../config.json" });
然后测试工作正常。但是,这将破坏使用luaScripts.js的任何其他模块的路径。

任何人都可以解释这种奇怪的行为吗?当我运行我的单元测试时,似乎相遇的路径搞砸了。

由于

1 个答案:

答案 0 :(得分:0)

显然,测试运行者有时会在自己的目录中运行测试。如果要在单元测试中需要非全局模块,而不是使用相对路径,请使用节点的__dirname全局。如果需要向上移动目录,可以使用节点的路径模块:

path.join(__dirname, "../", "myfile.js");