Linked Questions

Popular Questions

Set session in Request for node js unit test

Asked by At

I have a route .route(myapp/profile) .get(myProfileMiddleware.checkAccessToken(), myProfileController.getProfile )

Here the middleware method

checkAccessToken

checks whether a session token is set as below.

checkAccessToken() { 
return (req, rex, next) => {      
  if (!req.session || !req.session.accessToken) {
   // throws 403 Forbidden error
  }
  // Executes next() method      
}}

If the access token is present the route executes the corresponding controller method myProfileController.getProfile, else throws 403 forbidden error.

I need to write the unit test for this route. I am using mocha, chai , sinon and supertest. I tried to set the session variable in request method using "express-session" as below

app.use(session({accessToken: 'ssshhhhh'}));

Also tried set('cookie', ['accessToken=sssh'], but didnt work. The session token is not getting set and the route shows 403 Forbidden error

Could anybody have a working solution for this? Thanks in advance.

I am using the below versions:

Node : 8.7, chai: ^4.1.0, mocha: ^5.0.4, node-mocks-http: ^1.6.6, sinon:^2.3.2 supertest: ^3.0.0

Related Questions