【问题标题】:Including modules in mocha unit test在 mocha 单元测试中包含模块
【发布时间】:2016-02-23 19:05:09
【问题描述】:

我正在尝试将我制作的模块 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 的任何其他模块的路径。

谁能解释这种奇怪的行为?当我运行单元测试时,似乎相对路径搞砸了。

谢谢

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 1970-01-01
      • 2019-05-04
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多