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

如何在Express中模拟中间件以跳过身份验证以进行单元测试?,第1张

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

您可以使用

sinon
to stub
isAuthenticated
方法,但是应该
auth.isAuthenticated
在将对的引用设置为中间件之前进行此 *** 作,因此在创建
index.js
and
之前需要这样做
app
。您最有可能希望将其
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
实例也将具有存根作为中间件,因此,
app
如果由于某种原因需要获得原始行为,则需要创建另一个实例。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5476831.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存