How to authenticate Supertest requests with Passport?

后端 未结 8 1455
囚心锁ツ
囚心锁ツ 2020-11-28 21:22

I\'m using Passport.js for authentication (local strategy) and testing with Mocha and Supertest.

How can I create a session and make authenticated requests with Supe

8条回答
  •  不知归路
    2020-11-28 22:17

    As an addendum to Andy's answer, in order to have Supertest startup your server for you, you can do it like this:

    var request = require('supertest');
    
    /**
     * `../server` should point to your main server bootstrap file,
     * which has your express app exported. For example:
     * 
     * var app = express();
     * module.exports = app;
     */
    var server = require('../server');
    
    // Using request.agent() is the key
    var agent = request.agent(server);
    
    describe('Sessions', function() {
    
      it('Should create a session', function(done) {
        agent.post('/api/session')
        .send({ username: 'user', password: 'pass' })
        .end(function(err, res) {
          expect(req.status).to.equal(201);
          done();
        });
      });
    
      it('Should return the current session', function(done) {
        agent.get('/api/session').end(function(err, res) {
          expect(req.status).to.equal(200);
          done();
        });
      });
    });
    

提交回复
热议问题