如何在Express中模拟中间件以跳过身份验证以进行单元测试? [英] How to mock middleware in Express to skip authentication for unit test?

查看:115
本文介绍了如何在Express中模拟中间件以跳过身份验证以进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Express中有以下内容

I have the following in 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以返回此值

I want to override or mock isAuthenticated to return this

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-我想我需要对路由器存根吗? 我还尝试在测试中覆盖

I have tried mocking index.js using proxyquire - I think I need to stub the router? I have also tried to override in the test

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

必须有一种简单的方法可以模拟这种情况,因此我不需要对请求进行身份验证.有什么想法吗?

There must be a simple way to mock this out so I don't need to authenticate the request. Any ideas?

推荐答案

可以使用sinonisAuthenticated方法进行存根,但是应该在将对auth.isAuthenticated的引用设置为中间件之前进行此操作.您需要index.jsapp已创建.您最有可能希望在beforeEach钩中使用此方法:

You can use sinon to stub isAuthenticated method, but you should do that before a reference to auth.isAuthenticated is set as a middleware, so before you require the index.js and app is created. Most likely you would want this in a beforeEach hook:

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实例也将具有存根作为中间件,因此,如果由于某种原因需要恢复原始行为,则需要创建另一个app实例.

Please note that even after auth.isAuthenticated is restored, existing app instance will have stub as a middleware, so you need to create another app instance if you need to get an original behavior by some reason.

更新:有一种方法可以更改中间件的行为,而无需每次都重新创建服务器,如另一个这样回答.

Update: there is a way to alter middleware's behavior without recreating the server each time as explained in another SO answer.

这篇关于如何在Express中模拟中间件以跳过身份验证以进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆