NodeJS supertest access to session object

余生颓废 提交于 2019-12-21 03:58:12

问题


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?


回答1:


This new lib should do the trick:

  • https://github.com/rjz/supertest-session

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

  • http://jaketrent.com/post/authenticated-supertest-tests/

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

  • https://gist.github.com/joaoneto/5152248



回答2:


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!



来源:https://stackoverflow.com/questions/20213674/nodejs-supertest-access-to-session-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!