NodeJS supertest access to session object

user1772306 picture user1772306 · Nov 26, 2013 · Viewed 7.6k times · Source

I'm testing my Node.js application with supertest. In my controller I access the session object. In order to make a valid request this session object needs to be filled with some data.

Controller

        // determine whether it is user's own profile or not
        var ownProfile = userId == req.session.user._id ? true : false;

Test

it('profile', function (done) {
    testUserOne.save(function(error, user){

        request
            .agent(server)
            .get('/profile?userId=' + user._id)
            .expect('Content-Type', /html/)
            .expect(200)
            .expect(/Profile/)
            .end(done);
    })
});

Question

How can I mock the req/session object?

Answer

Tony O'Hagan picture Tony O'Hagan · Jan 31, 2014

This new lib should do the trick:

You might also have a look at superagent that is part of supertest. Here's a nice tutorial on this:

Don't want another lib? Try this one ...