How to authenticate Supertest requests with Passport /Facebook strategy/?

Zeck picture Zeck · Dec 17, 2013 · Viewed 7.8k times · Source

I'm using Passport.js for authentication (Facebook strategy) and testing with Mocha and Supertest. How can I create a session and make authenticated requests with Supertest for Facebook strategy?

Here is the example test for when user not logged in:

  describe 'when user not logged in', ->

    describe 'POST /api/posts', ->
      it 'respond with 401', (done)->
        request(app).
          post(API.url('posts')).
          set('Accept', 'application/json').
          send(post: data).
          expect('Content-Type', /json/).
          expect(401, done)

Thank you for advice :D

Answer

erichrusch picture erichrusch · Dec 22, 2013

There are few different things here it looks like, so I've divided my answer into two parts.

1) You first must create test users through the Facebook. You can do so via one of two methods, 1) Facebook's Graph API, or 2) Through the Roles page of your application.

2) The recommend method for persisting sessions with SuperTest is using a SuperAgent method called .agent() to persist sessions. Anything you can do with SuperAgent, you can do with SuperTest. See this Github post for more.

var supertest = require('supertest');
var app = require('../lib/your_app_location');

describe('when user not logged in', function() {
    describe('POST /api/posts', function() {
        var agent1 = supertest.agent(app);

        agent1
            .post(API.url('posts'))
            .set('Accept', 'application/json')
            .send(post: data)
            .(end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(401);
                should.exist(res.headers['set-cookie']);
                done();
            }));
    });
});

There are some other good code snippets on the VisionMedia Github. Please find them here.