Stubbing连接中间件

时间:2014-10-14 20:52:45

标签: javascript express connect sinon

我有一个中间件(coffeescript):

 basic = (req, res, next) ->
    return next() if not app.settings.auth?
    express.basicAuth(app.settings.auth.username, app.settings.auth.password) req, res, next

如何存根basicAuth函数来控制流程?

我试过了:

express = require 'express'
sinon.stub express, 'basicAuth'

并收到错误:

 TypeError: Cannot set property basicAuth of function createApplication() {
  var app = connect();
  utils.merge(app, proto);
  app.request = { __proto__: req };
  app.response = { __proto__: res };
  app.init();
  return app;
} which has only a getter

我也尝试过:

connect = require 'connect'
sinon.stub connect, 'basicAuth'

哪些错误因为连接不是我的应用程序的直接可用依赖项(表达需要它)

1 个答案:

答案 0 :(得分:1)

您可以创建自己的模块,导出您希望存根的方法。

# stub.coffee
express = require 'express'

# export basicAuth as a stub-friendly export
module.exports.basicAuth = express.basicAuth

除了表达之外,你需要这样做。

stubpress = require 'stubbableExpress'

basic = (req, res, next) ->
  return next() if not app.settings.auth?
  stubpress.basicAuth(app.settings.auth.username, app.settings.auth.password) req, res, next

这给了你一些可以存根的东西:

stubpress = require 'stubbableExpress'
sinon.stub(stubpress, 'basicAuth')