NodeJS supertest access to session object

2020-06-11 15:49发布

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?

2条回答
Deceive 欺骗
2楼-- · 2020-06-11 16:29

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

查看更多
聊天终结者
3楼-- · 2020-06-11 16:53

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!

查看更多
登录 后发表回答