Search code examples
node.jsmocha.jssupertestpassport.js

How to authenticate Supertest requests with Passport?


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 Supertest?


Solution

  • You should use superagent for that. It is lower level module and used by supertest. Take a look at the section Persisting an agent:

    var request = require('superagent');
    var user1 = request.agent();
    user1
      .post('http://localhost:4000/signin')
      .send({ user: 'hunter@hunterloftis.com', password: 'password' })
      .end(function(err, res) {
        // user1 will manage its own cookies
        // res.redirects contains an Array of redirects
      });
    

    Now you can use user1 to make authenticated requests.