4

I'm using koa-passport & koa to handle my login and registration using twitter oauth. It works great, but I'm having difficulties understanding how I should test my authenticated routes using supertest and mocha.

Most examples I have seen involve using supertest to send a username and password to a login endpoint to first create a user session. My problem is that I don't have a username/passport auth strategy. I need to emulate an oauth login process that will set the appropriate session variables, and therefore test certain routes.

Any clue on how I can achieve this?

laggingreflex
  • 32,948
  • 35
  • 141
  • 196
bento
  • 4,846
  • 8
  • 41
  • 59

1 Answers1

0

My solution these days to this problem is to basically insert a mock authenticated user in the middleware stack temporarily when needed. Here's my basic code for express.

var Layer = require('express/lib/router/layer');
var app = require('../../../server');

exports.login = login;
exports.logout = logout;

function login(user){

  var fn = function insertUser(req, res, next){
    req.user = user;
    next();
  }

  var layer = new Layer('/', {
    sesitive: false,
    strict: false,
    end: false
  }, fn);
  layer.route = undefined;

  app._router.stack.unshift(layer);
}

function logout(){
  app._router.stack.shift();
}

And then within your tests, you call:

it('should allow the user to edit something', function(done){
  login(this.user);
  // perform supertest task
  logout();
});

This is obviously pretty rudimentary... but seems to do the job for testing purposes.

bento
  • 4,846
  • 8
  • 41
  • 59
  • There is a spelling mistake in the Layer configuration. The first options property should be `sensitive`. – ligaz Nov 08 '16 at 14:44