ExpressJS:如何使用mocha模拟请求处理程序的下一个函数

时间:2015-06-24 09:55:58

标签: node.js express mocha

我有一个处理程序

public ensureAuthenticated(req: express.Request, res: express.Response, next: Function) {
    // check header or url parameters or post parameters for token
      var token = req.body.token || req.param('token') || req.headers['x-access-token'];
    // decode token
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token, config.secret, function(err, decoded) {   
            if (err) {
                return res.status(404).json({ success: false, message: 'Failed to authenticate token.' });      
            } else {
                // if everything is good, save to request for use in other routes
                next();
            }
        });

    } else {
        // if there is no token
        // return an error
        return res.status(403).send({ 
            success: false, 
            message: 'No token provided.'
        });
    }
  }

这里是路线

app.post('/api/article/create', AuthenticationHelper.ensureAuthenticated, this.create);

在单元测试中,如何模拟 ensureAuthenticated 以确保其经过身份验证。

sinon.stub(AuthenticationHelper, 'ensureAuthenticated').returns(true);

1 个答案:

答案 0 :(得分:0)

我将举例说明我在不使用sinon的情况下测试它。

这是我的身份验证-helper.js:

'use strict';

module.exports = function(jwt, config) {
  return {
    ensureAuthenticated: function (req, res, next) {
      var token = req.body.token ||
                req.param('token') ||
                req.headers['x-access-token'];

      if (token) {
        jwt.verify(
              token,
              config.secret,
              function(err, decoded) {
                if (err) {
                  res
                  .status(404)
                  .json({
                    success: false,
                    message: 'Failed to auth.'
                  });
                } else {
                  next();
                }
              }
        );
      } else {
        res
        .status(403)
        .send({
          success: false,
          message: 'No token provided.'
        });
      }
    }
  };
}

这是我的测试文件:

'use strict';

var jwt = {};
jwt.verify = function (token, secret, fn) {
  fn(null, 'something');
};

var config = {};
config.secret = 'shh';

var req = {};
req.body = {};
req.body.token = 'mytoken';

var res = {};

var AuthenticationHelper = require('./authentication-helper.js')(jwt, config);

describe('Test Express Middleware', function() {
  it('should call next on middlware', function(done) {
    var next = function () {
      console.log('next was called');
      done();
    };

    AuthenticationHelper.ensureAuthenticated(req, res, next);
  });
});