Skip to content

Instantly share code, notes, and snippets.

@bitliner
Forked from bq1990/gist:595c615970250e97f3ea
Last active July 18, 2020 07:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitliner/3eb1e8291853279e4e9830bde7f036ed to your computer and use it in GitHub Desktop.
Save bitliner/3eb1e8291853279e4e9830bde7f036ed to your computer and use it in GitHub Desktop.
Supertest authenticate with bearer token
'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: 'test@test.com',
password: 'test'
})
.expect(200)
.end(onResponse);
function onResponse(err, res) {
auth.token = res.body.token;
return done();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment