Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a mock session for express-session when using SuperTest?

I have the following session setup...

setupSession(){
  const session = {
    secret: process.env.SESSION_SECRET,
    cookie: {},
    resave: false,
    saveUninitialized: false,
  };
  this.app.use(expressSession(session));
}

I have the following test...

it("User should pass", (done)=>{
  supertest(app)
    .get("/user")
    .set('Cookie', ['connect.sid=...'])
    .expect(200)
    .end(function(err, res){
      if (err) done(err);
      done();
    });
})

I now need to mock out a session in the app to make sure that the login is valid? How do I mock a session in the session store so it thinks it is logged in during supertests?

like image 209
Jackie Avatar asked Oct 15 '25 04:10

Jackie


1 Answers

I am not going to accept this, however, my workaround was to wrap the existing Express App in a Test Wrapper that overrode the properties needed for Auth. Like this...

const mockAuth = (app)=>{
  const parentApp = express();
  parentApp.use(function(req, res, next) { // lets stub session middleware
    req.isAuthenticated = ()=>true;
    next();
  });
  parentApp.use(app);
  return parentApp;
};
like image 133
Jackie Avatar answered Oct 16 '25 19:10

Jackie