1
votes

I hava an express app which the authentication is handled by JWT, and I simply store the token in session after login.

req.session.JWToken = '<token>';

The authentication middleware looks like:

this.use('(^\/admin')', expressJWT({
      secret: 'secret',
      getToken: function fromHeaderOrQuerystring (req) {
          if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
              return req.headers.authorization.split(' ')[1];
          } else if (req.query && req.query.token) {
              return req.query.token;
          } else if (req.session.JWToken) {
              return req.session.JWToken;
          }

          return null;
        }
  }).unless({path: ['/login', '/signup']}));

I need to test this using mocha and supertest, I tried code below:

var app = require('./../app');
var request = require('supertest');

describe('app', function() {
  var agent = request.agent(app);

  it('should signin', function(done) {

    agent
      .post('/login')
      .send({_email: '<email>', _password: '<password>'})
      .expect(200, done)
      .end(function(err, res){
        if(err) throw err;
          done();
      });
  });

  // how to persist session here ?
  it('should get a restricted page', function(done) {
    agent
      .get('/admin')
      .expect(200)
      .end(function(err, res){
          if(err) throw err;
          done();
      });
  });

});

Have no idea how to persist the session on the second it.Please guide me a direction.

1
Did you ever figure this out? - frogbandit
unfortunately not yet.. please let me know if you do - egig

1 Answers

4
votes

I was running into the same issue yesterday and figured it out. Try setting agent outside of the describe block:

var app = require('./../app');
var request = require('supertest');

var agent = request.agent(app);

describe('app', function() {

  it('should signin', function(done) {

    agent
      .post('/login')
      .send({_email: '<email>', _password: '<password>'})
      .expect(200, done)
      .end(function(err, res){
        if(err) throw err;
          done();
      });
  });

  // how to persist session here ?
  it('should get a restricted page', function(done) {
    agent
      .get('/admin')
      .expect(200)
      .end(function(err, res){
          if(err) throw err;
          done();
      });
  });

});

If that doesn't work, try doing the login POST in a beforeEach loop using sinon.

beforeEach((done) => {      
    agent
        .post('/login')
        .send({_email: '<email>', _password: '<password>'})
        .end((err, res) => {
            if (err) throw err;
            done();
        });
});

If that doesn't work, try and make sure your email and password parameters are correct.