20

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?

user1772306
  • 449
  • 1
  • 7
  • 20

2 Answers2

16

just use as sub-app, and call your authenticated() at parent-app:

var mockApp = express();
mockApp.use(session);
mockApp.all('*', function(req, res, next) {
    //authenticated(req, res, next);
    //OR
    req.session.uid = 'mock uid';
    next();
});
mockApp.use(app);

all your routes will be authenticated before matched!

Jackong
  • 181
  • 1
  • 3
  • Interesting option. What is the purpose of mockApp.use(app)? Don't we have to link the mockApp to the main express? – nishant Jun 24 '20 at 21:55
  • 3
    @nishant `mockApp.use(app)` actually extends mockApp with the original app, so the session overriding handler is inserted into the original app. Worth noting that it's `mockApp` that should be used in the tests: `request(mockApp)…`. Thx for pointing that out! – foudfou May 05 '21 at 22:49
  • 2
    could you add the instantiation of session? – JRichardsz Oct 19 '21 at 00:57
  • @JRichardsz For me it's enough to instantiate `express-session` with a secret: `mockApp.use(session({secret: 'test-secret'}));` – Florian Walther Jun 06 '22 at 08:34
14

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 ...

Tony O'Hagan
  • 21,638
  • 3
  • 67
  • 78
  • Please note the Jake Trent tutorial is outdated as `saveCookies` has been deprecated: https://github.com/visionmedia/superagent/issues/1014 – o01 Jul 07 '20 at 20:56