1

我正在尝试对一个简单的 Express 中间件进行单元测试,这是一个级联认证器,它首先使用 a 检查 JWT 令牌passport-jwt-strategy,然后如果失败,使用 a passport-openid-strategy。每个策略都已经过很好的测试,所以我要测试的是它们的集成。

我正在测试的模块如下所示:

"use strict";

let passport = require('passport');
let Strategies = require('./strategies');
let setupDone = false;

// set up passport
let setup = function(app) {
  passport.serializeUser(function(user, done) {
    done(null, user);
  });

  passport.deserializeUser(function(obj, done) {
    done(null, obj);
  });

  passport.use('jwt',    Strategies.jwt);
  passport.use('openid', Strategies.openId);
  app.use(passport.initialize());
  app.use(passport.session());
  setupDone = true;
};

let authenticate = function(req, res, next) {
  if (!setupDone) throw new Error('You must have run setup(app) before you can use the middleware');
  console.log(' cascadingAuthentication');
  // first try the token option
  passport.authenticate('jwt', function(jwterr, user, info) {
    console.log(' jwt auth', jwterr, user, info);
    if (jwterr || !user) {
      passport.authenticate('openid, function(oautherr, user, info) {
        if (oautherr || !user) {
          return next(oautherr);
        } else {
          next();
        }
      });
    } else {
      req.user = user;
      next();
    }
  });
};

module.exports = {
  setup: setup,
  authenticate: authenticate
}

我的Jasmine测试看起来像这样

"use strict";

let CascadingAuthentication = require('../../lib/middleware/cascadingAuthentication');
let TokenUtils = require('../support/tokenUtils');
let email = 'testing@test.tes;

describe('cascadingAuthentication', function() {

  describe('when there is a token in the header', function() {
    let req;
    let res = {};
    let app = {
      use: function(used) { console.log('app.use called with', typeof used); }
    };

    beforeEach(function(done) {
      let token = TokenUtils.makeJWT(email);
      req = {
        app: app,
        header: {
          Authorization: `Bearer ${token}`
        }
      }
      CascadingAuthentication.setup(app);
      CascadingAuthentication.authenticate(req, res, function() {
        done();
      });
    });

    it('populates req.user', function() {
      expect(req.user).toEqual(jasmine.any(Object));
    });
  });

});

我遇到的问题是,当我运行测试时,我看到了第一个console.log(' cascadingAuthentication')但我从来没有看到过第二个console.log('jwt auth', err, user, info)。代码只是死在里面passport.authenticate,没有调用回调,没有引发错误,或者根本没有提供任何类型的反馈。

我正在通过gulpusing运行我的测试Jasmine

我的问题是:按顺序,

  1. 你能看到我所做的任何我可能错过的明显事情吗?
  2. 还有什么我应该在我的req,中模拟出来的res,或者app可以使这个测试工作的东西吗?
  3. 有什么方法可以交互调试吗?在运行时单步执行被测代码,而不仅仅是添加console.log语句(这对我来说似乎有点 1980 年代)。
4

2 回答 2

0

挖掘passport's source 我发现我的代码有两个问题。

第一个是passport.authenticate返回一个中间件函数,它实际上并不执行该函数。所以解决方案就是调用返回的函数。

所以我的身份验证方法现在看起来像:

let authenticate = function(req, res, next) {
  if (!setupDone) throw new Error('You must have run setup(app) before you can use the middleware');
  // first try the token option
  passport.authenticate('jwt', function(jwterr, user, info) {
    if (jwterr || !user) {
      passport.authenticate('openid', function(autherr, user, info) {
        if (autherr || !user) {
          return next(autherr);
        } else {
          next();
        }
      })(req, res, next);
    } else {
      req.user = user;
      next();
    }
  })(req, res, next);
};

(上面的例子被修剪以用于问题)

另一个问题是在我使用的测试中,header而不是headers在我的模拟req对象中,并且authorization应该有一个小写的a.

通过这两个修复,测试现在通过了。

于 2015-11-11T05:45:04.623 回答
0

我摆弄了很长一段时间,最终进入了以下设置(测试passport.authenticate('local', () => {}))。

auth-router.js

const express = require('express');
const passport = require('passport');

const login = (req, res, next) => {
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      next(err);
      return;
    }

    if (!user) {
      const error = new Error(info.message);
      error.status = 404;
      next(error);
      return;
    }

    // Add the found user record to the request to 
    // allow other middlewares to access it.
    req.user = user;
    next();
  })(req, res, next);
};

const router = express.Router();
router.post('/auth/login', login);

module.exports = {
  login,
  router
};

auth-router.spec.js

const passport = require('passport');

describe('login', () => {
  it('should login and add the user to the request object', (done) => {
    spyOn(passport, 'authenticate').and.callFake((strategy, callback) => {
      const err = null;
      const user = {};
      const info = {};
      callback(err, user, info);
      return (req, res, next) => {};
    });

    const auth = require('./auth'); // my middleware function
    const req = { body: {} };
    const res = {};
    const next = () => {
      expect(req.user).toBeDefined();
      done();
    };

    auth.login(req, res, next);
  });
});

于 2017-07-10T14:00:42.743 回答