Created
December 17, 2014 15:55
-
-
Save bq1990/595c615970250e97f3ea to your computer and use it in GitHub Desktop.
Supertest authenticate with bearer token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var should = require('should'); | |
var app = require('../../app'); | |
var request = require('supertest')(app); | |
describe('GET /api/incidents', function() { | |
it('should require authorization', function(done) { | |
request | |
.get('/api/incidents') | |
.expect(401) | |
.end(function(err, res) { | |
if (err) return done(err); | |
done(); | |
}); | |
}); | |
var auth = {}; | |
before(loginUser(auth)); | |
it('should respond with JSON array', function(done) { | |
request | |
.get('/api/incidents') | |
.set('Authorization', 'bearer ' + auth.token) | |
.expect(200) | |
.expect('Content-Type', /json/) | |
.end(function(err, res) { | |
if (err) return done(err); | |
res.body.should.be.instanceof(Array); | |
done(); | |
}); | |
}); | |
}); | |
function loginUser(auth) { | |
return function(done) { | |
request | |
.post('/auth/local') | |
.send({ | |
email: '[email protected]', | |
password: 'test' | |
}) | |
.expect(200) | |
.end(onResponse); | |
function onResponse(err, res) { | |
auth.token = res.body.token; | |
return done(); | |
} | |
}; | |
} |
You can use the
auth
method instead of setting the Authorization header by hand:it('should respond with JSON array', function(done) { request .get('/api/incidents') .auth(auth.token, { type: 'bearer' }) .expect(200) .expect('Content-Type', /json/) .end(function(err, res) { if (err) return done(err); res.body.should.be.instanceof(Array); done(); }); }); ``'
This worked for me. Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
please i have a question ... how do i test a secured route with jest (supertest) ....... where when a user login it generate a jwt and then that jwt generated will be used as a middleware to test other routes?????