Testing authenticated oauth routes
I am using koa passport and koa to handle my login and registration with twitter oauth. It works great, but I am having difficulty understanding how I should validate my authenticated routes using superether and mocha.
Most of the examples I've seen involve using supertest to send the username and password to the login endpoint to create a user session first. My problem is that I don't have a username and passport authorization strategy. I need to emulate a login process that will set the appropriate session variables and therefore validate certain routes.
Any clue as to how I can achieve this?
source to share
My solution to this problem these days is to temporarily push a dummy authenticated user onto the middleware stack when needed. Here is 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.
source to share