node.js - 在使用 jasmine 需要它后如何将其删除?

标签 node.js express jasmine jasmine-node

当我想到我已经在该文件的顶部包含了express时,我正在尝试测试下面的代码。你能知道如何在加载 Express 对象后对其进行猴子修补吗?

var express = require('express')

Helper = (function() {                                                                           

  var HelperObject = function(params) {
    this.directories = params.directories;
  };

  HelperObject.prototype.addStaticPath = function(app) {
    for(i = 0; i < this.directories.length; i++) {                                               
      var static = express.static('/public');
      app.use(static);
    }
  };

  return HelperObject;
})();

最佳答案

问题是,当您创建 Node 模块时,所需的模块会绑定(bind)在模块的闭包中,并且您无法开始监视它,因为它在测试中不可见。

Gently您可以在其中覆盖 require,但它会在您的代码中添加与样板测试相关的代码。

来自文档:

Returns a new require functions that catches a reference to all required modules into gently.hijacked.

To use this function, include a line like this in your 'my-module.js'.

if (global.GENTLY) require = GENTLY.hijack(require);

var sys = require('sys');
exports.hello = function() {
  sys.log('world');
};

Now you can write a test for the module above:

var gently = global.GENTLY = new (require('gently'))
  , myModule = require('./my-module');

gently.expect(gently.hijacked.sys, 'log', function(str) {
  assert.equal(str, 'world');
});

myModule.hello();

关于node.js - 在使用 jasmine 需要它后如何将其删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12344896/

相关文章:

node.js - 如何在 Linux VM 中运行 Node 项目?

angular - Jasmine 测试,导致 mat-select 发出 selectionChange 事件?

javascript - karma 错误参数 'Controller' 不是函数,未定义

javascript - 查找 Mongo 集合,始终返回未定义

node.js - 在 Windows 7 上 npm install mongoose 失败

node.js - REST API 仅在 Express 中获取 'Error: No default engine was specified and no extension was provided'

javascript - 如何在javascript文件之间共享数据?

node.js - 没有服务器的 Angular 2 应用程序?

javascript - 解析错误: Adjacent JSX elements must be wrapped in an enclosing tag

node.js - 生产环境动态生成 Express 路由失败