Friday, 21 April 2017

Mocking req.user object for MochaJS tests

In one of my ExpressJS routes, I'm using PassportJS' HTTP Bearer Strategy and Local Strategy together. It means user must be logged in and must have a bearer token to reach that route.

function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/login');
}
app.route('/api/someaction')
        .get(passport.authenticate('bearer', { session: false }), isLoggedIn, function(req, res, next) {
      console.log(req.user.userID);
});

When I browse to this route with my browser or with Postman (after setting cookies for local strategy) it's working as expected.

Now I need to write integration tests for this route with MochaJS/ChaiJS. This is my test file:

var server = require('../app.js');
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var expect = chai.expect;

chai.use(chaiHttp);

  describe('...', () => {
      it('...', (done) => {
        chai.request(server)
            .get('/api/someaction')
            .set('Authorization', 'Bearer 123')
            .end((err, res) => {
              // asserts here
              done();
            });
      });
});

While testing this file with MochaJS, req.user.userID in /api/someaction is always undefined.

How can I mock PassportJS strategies to get a req.user object inside route?



via Eray

No comments:

Post a Comment