如何在 Express 中模拟中间件以跳过单元测试的身份验证?

How to mock middleware in Express to skip authentication for unit test?

我在 Express 中有以下内容

 //index.js

 var service = require('./subscription.service');
 var auth = require('../auth/auth.service');
 var router = express.Router();

 router.post('/sync', auth.isAuthenticated, service.synchronise);

 module.exports = router;

我想覆盖或模拟 isAuthenticated 到 return 这个

auth.isAuthenticated = function(req, res, next) { 
  return next(); 
}

这是我的单元测试:

it('it should return a 200 response', function(done) {

  //proxyquire here?

  request(app).post('/subscriptions/sync')
  .set('Authorization','Bearer '+ authToken)
  .send({receipt: newSubscriptionReceipt })
  .expect(200,done);
});

我已经尝试使用 proxyquire 模拟 index.js - 我想我需要对路由器进行存根? 我也尝试在测试中覆盖

app.use('/subscriptions', require('./api/subscription'));

必须有一种简单的方法来模拟它,这样我就不需要对请求进行身份验证。有什么想法吗?

您可以使用 sinon 存根 isAuthenticated 方法,但是您应该在将对 auth.isAuthenticated 的引用设置为中间件之前执行此操作,因此在您需要 index.jsapp 被创建。您很可能希望在 beforeEach 挂钩中使用它:

var app;
var auth;

beforeEach(function() {
  auth = require('../wherever/auth/auth.service');
  sinon.stub(auth, 'isAuthenticated')
      .callsFake(function(req, res, next) {
          return next();
      });

  // after you can create app:
  app = require('../../wherever/index');
});

afterEach(function() {
  // restore original method
  auth.isAuthenticated.restore();
});

it('it should return a 200 response', function(done) {
  request(app).post('/subscriptions/sync')
  .set('Authorization','Bearer '+ authToken)
  .send({receipt: newSubscriptionReceipt })
  .expect(200,done);
});

请注意,即使在 auth.isAuthenticated 恢复后,现有的 app 实例仍将存根作为中间件,因此如果需要获取出于某种原因的原始行为。

更新: 有一种方法可以改变中间件的行为,而无需每次都重新创建服务器,如 中所述。