【问题标题】:Scoping mecanism with nodejs and require使用 node js 和 require 的作用域机制
【发布时间】:2014-02-22 23:49:24
【问题描述】:

尝试使用 nodejs 和 jasmine-node 执行客户端 JavaScript 的单元测试。 我能够创建窗口和文档变量,一个 $ 变量,设置环境(使用 npm,不要忘记定义 NODE_PATH!)。但现在我被困在了这个问题上。

我要测试的功能在一个模块中。我可以导入(需要)模块,但导入模块的变量无法从 nodejs(或出于我想象的相同原因的 jasmine 规范文件)访问。

这是模块:

var test_module = (function () {
  var init = function () {
    return "toto";
  }

  return { init: init };
})();

在变量test_module中,我们应该找到包含所有导出函数的字典的变量(这里只有一个叫做init)。

在nodejs中:

> require('test.js');
{}
> test_module
ReferenceError: test_module is not defined
    at repl:1:2
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)

我不确定在 nodejs 中作用域是如何工作的。我试着说:

global.test_module = (function () {

这是可行的,但这不是我想做的。我的 javascript 应该在经过测试后在浏览器中运行,而 global 不会这样做...

旁注:我猜想,使用命令行、无浏览器和无服务器解决方案对客户端 JavaScript 进行单元测试应该值得一读。那里有一些,但它们通常不完整。

【问题讨论】:

  • 您还需要在模块文件的末尾导出您的模块module.exports = test_module。然后从你的主文件var test_module = require("test.js");
  • 你不应该在 node.js 中测试浏览器代码
  • 致 htatche:是的,但那是 nodejs 的事情......浏览器将如何管理这个。我认为它不会喜欢这种出口业务。这里的目的是对客户端 javascript 模块进行单元测试,因此从 html 页面中的
  • 致 vkurchatkin:好的,那么你如何通过命令行进行单元测试(无需加载浏览器页面)?

标签: javascript node.js unit-testing jasmine


【解决方案1】:

好的,感谢 htatche 的回答,我找到了一种解决方法(似乎客户端 javascript 单元测试是解决方法的领域......):

var test_module = (function () {
  var init = function () {
    return "toto";
  }

  return { init: init };
})();

if(typeof exports != 'undefined'){
    module.exports = test_module;
}

在这里解释:http://caolanmcmahon.com/posts/writing_for_node_and_the_browser/
这样我就可以让 nodejs 和浏览器满意了。

【讨论】:

  • 这是一个 common.js 模式,请进一步研究。
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 2018-12-30
  • 2016-06-27
  • 2014-07-11
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多