Skip to content

Commit

Permalink
Merge pull request #247 from osahner/develop
Browse files Browse the repository at this point in the history
Add test for JWT Authorization
  • Loading branch information
kunalkapadia committed Feb 13, 2017
2 parents 19150d4 + 9054397 commit b12b463
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
3 changes: 1 addition & 2 deletions server/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import jwt from 'jsonwebtoken';
import httpStatus from 'http-status';
import APIError from '../helpers/APIError';

const config = require('../../config/env');
import config from '../../config/env';

// sample user, used for authentication
const user = {
Expand Down
60 changes: 60 additions & 0 deletions server/tests/auth.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import request from 'supertest-as-promised';
import httpStatus from 'http-status';
import jwt from 'jsonwebtoken';
import chai, { expect } from 'chai';
import app from '../../index';
import config from '../../config/env';

chai.config.includeStack = true;

describe('## AUTH APIs', () => {
const user = {
username: 'react',
password: 'express'
};
let jwtToken;

describe('# POST /api/auth/login', () => {
it('should get (valid) JWT token', (done) => {
request(app)
.post('/api/auth/login')
.send(user)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body).to.have.property('token');
jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => {
expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions
expect(decoded.username).to.equal(user.username);
jwtToken = `Bearer ${res.body.token}`;
done();
});
})
.catch(done);
});
});

describe('# GET /api/auth/random-number', () => {
it('should fail to get random number because of missing Authorization', (done) => {
request(app)
.get('/api/auth/random-number')
.expect(httpStatus.UNAUTHORIZED)
.then((res) => {
expect(res.body.message).to.equal('Unauthorized');
done();
})
.catch(done);
});

it('should get a random number', (done) => {
request(app)
.get('/api/auth/random-number')
.set('Authorization', jwtToken)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body.num).to.be.a('number');
done();
})
.catch(done);
});
});
});

0 comments on commit b12b463

Please sign in to comment.