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

查看:25
本文介绍了如何在 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?

推荐答案

您可以使用 sinon 来存根 isAuthenticated 方法,但您应该在引用 isAuthenticated 方法之前执行此操作code>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实例也会有stub作为中间件,因此您需要创建另一个appcode> 实例,如果您出于某种原因需要获得原始行为.

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天全站免登陆