1

I have a compound js application in node.js. For some actions i have a filter checking the existence of "session.user" value which gets populated only after successful authentication. But whenever writing the unit test cases for such actions, the session.user value gets undefined. I use supertest, sinon modules to make get,post requests to actions but due to undefined value of "session.user" value, it doesn't authenticate and gets redirected to proper action. Please help me out as I am stuck with the same.

Please guide me what exactly I need to mock so that I can authenticate the session.user value. Thanks in advance,

waiting for positive answers,

Thanks,

1 Answers1

0

I used a combination of mocking passport.initialize, a test helper, and a listener on the compound configure event.

This provided two things:

  1. DRY - reuse of beforeEach code across controller tests.
  2. Unobtrusive testing - mock passport.initialize so I didn't have to modify configuration based on testing.

In test/init.js I added the method to mock passport.initialize**:

** Found it at:

http://hackerpreneurialism.com/post/48344246498/node-js-testing-mocking-authenticated-passport-js

// Fake user login with passport.
app.mockPassportInitialize = function () {
    var passport = require('passport');
    passport.initialize = function () {
        return function (req, res, next) {
            passport = this;
            passport._key = 'passport';
            passport._userProperty = 'user';
            passport.serializeUser = function(user, done) {
                return done(null, user.id);
            };
            passport.deserializeUser = function(user, done) {
                return done(null, user);
            };
            req._passport = {
                instance: passport
            };
            req._passport.session = {
                user: new app.models.User({ id: 1, name: 'Joe Rogan' })
            };

            return next();
        };
    };
};

Then I added a helpers.js file to be called in each controller:

module.exports = {
    prepApp: function (done) {
        var app = getApp();
        compound = app.compound;
        compound.on('configure', function () { app.mockPassportInitialize(); });
        compound.on('ready', function () { done(); });
        return app;
    }
};

This will be called in the beforeEach of each controller:

describe('UserController', function () {
    beforeEach(function (done) {
        app = require('../helpers.js').prepApp(done);
    });
    [...]
});
absynce
  • 1,399
  • 16
  • 29