Skip to content

Instantly share code, notes, and snippets.

@zladuric
Last active August 29, 2015 14:15
Show Gist options
  • Save zladuric/bee4cb07893d9f3cd840 to your computer and use it in GitHub Desktop.
Save zladuric/bee4cb07893d9f3cd840 to your computer and use it in GitHub Desktop.
Test REST endpoints with auth

(In response to a comment here: http://stackoverflow.com/questions/28525954/how-to-disable-passportjs-authentication-in-local/28526181?noredirect=1#comment45389632_28526181)

Assume we're testing /addresses route. User needs to be authenticated before getting data.

var app = require('../'); // point to your express app
var request = require('supertest');
var agent = request.agent(app);
describe('Addresses endpoint', function() {
  before(function(done) {
  
    agent.post('/login')
    .send({username: 'joe', password: 'tester'})
    .end(function(err, res) {
      // now store a session cookie, auth token
      // or whatever else you use for auth/session tracking
      // then
    done();
  });
  // now the test
  // first, unauthenticated
  it('should not get addresses without authentication', function(done) {
  
    agent.get('/addresses')
    .expect(401)
    .end(function(err, res) {
       if(err) {
          throw err;
       }
        // or maybe check for that redirect you have
        (res.location.indexOf('/login') > -1).should.be.true;
       done();
    });
  });
  // then, authenticated
  it('should get addresses without authentication', function(done) {
  
    agent.get('/addresses')
    .set(/*header, cookie, token, whatever */)
    .expect(200)
    .end(function(err, res) {
      if(err) {
          throw err;
      }
      res.body.should.have.length(5); // or whatever you test
      done();
    });
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment