How to authenticate Supertest requests using Passport / Facebook /?

I use Passport.js for authentication (Facebook strategy) and testing using Mocha and Supertest. How to create a session and execute authenticated requests using the Supertest for Facebook strategy?

Here is an example test when the user is 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) 

Thanks for the tip: D

+6
source share
3 answers

There are a few different things here, so I divided my answer into two parts.

1) First you need to create test users via Facebook. You can do this in one of two ways: 1) Facebook Graph API or 2) through the Roles page of your application.

2) The recommended method for persistent sessions with SuperTest uses the SuperAgent method .agent () to continue the sessions. Everything you can do with SuperAgent you can do with SuperTest. See Github for more details.

 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(); })); }); }); 

VisionMedia Github has some more good code snippets. Find them here .

+12
source

A common solution is to create a cookie jar that will be reused between requests.

The following example does not apply to the passport, but should work:

 var request = require('request'); describe('POST /api/posts', function () { // Create a new cookie jar var j = request.jar(); var requestWithCookie = request.defaults({jar: j}), // Authenticate, thus setting the cookie in the cookie jar before(function(done) { requestWithCookie.post('http://localhost/user', {user: 'foo', password: 'bar'}, done); }); it('should get the user profile', function (done) { requestWithCookie.get('http://localhost/user', function (err, res, user) { assert.equal(user.login, 'foo'); done(); }); }); }); 
+2
source

This example shows how to complete the SuperTest testing part:

 describe('request', function() { describe('persistent agent', function() { var agent1 = request.agent(); var agent2 = request.agent(); var agent3 = request.agent(); var agent4 = request.agent(); it('should gain a session on POST', function(done) { agent3 .post('http://localhost:4000/signin') .end(function(err, res) { should.not.exist(err); res.should.have.status(200); should.not.exist(res.headers['set-cookie']); res.text.should.include('dashboard'); done(); }); }); 

Here 's a blog post about it.

0
source

All Articles