Skip to content

Commit b12b463

Browse files
authored
Merge pull request #247 from osahner/develop
Add test for JWT Authorization
2 parents 19150d4 + 9054397 commit b12b463

File tree

2 files changed

+61
-2
lines changed

2 files changed

+61
-2
lines changed

server/controllers/auth.controller.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import jwt from 'jsonwebtoken';
22
import httpStatus from 'http-status';
33
import APIError from '../helpers/APIError';
4-
5-
const config = require('../../config/env');
4+
import config from '../../config/env';
65

76
// sample user, used for authentication
87
const user = {

server/tests/auth.test.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import request from 'supertest-as-promised';
2+
import httpStatus from 'http-status';
3+
import jwt from 'jsonwebtoken';
4+
import chai, { expect } from 'chai';
5+
import app from '../../index';
6+
import config from '../../config/env';
7+
8+
chai.config.includeStack = true;
9+
10+
describe('## AUTH APIs', () => {
11+
const user = {
12+
username: 'react',
13+
password: 'express'
14+
};
15+
let jwtToken;
16+
17+
describe('# POST /api/auth/login', () => {
18+
it('should get (valid) JWT token', (done) => {
19+
request(app)
20+
.post('/api/auth/login')
21+
.send(user)
22+
.expect(httpStatus.OK)
23+
.then((res) => {
24+
expect(res.body).to.have.property('token');
25+
jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => {
26+
expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions
27+
expect(decoded.username).to.equal(user.username);
28+
jwtToken = `Bearer ${res.body.token}`;
29+
done();
30+
});
31+
})
32+
.catch(done);
33+
});
34+
});
35+
36+
describe('# GET /api/auth/random-number', () => {
37+
it('should fail to get random number because of missing Authorization', (done) => {
38+
request(app)
39+
.get('/api/auth/random-number')
40+
.expect(httpStatus.UNAUTHORIZED)
41+
.then((res) => {
42+
expect(res.body.message).to.equal('Unauthorized');
43+
done();
44+
})
45+
.catch(done);
46+
});
47+
48+
it('should get a random number', (done) => {
49+
request(app)
50+
.get('/api/auth/random-number')
51+
.set('Authorization', jwtToken)
52+
.expect(httpStatus.OK)
53+
.then((res) => {
54+
expect(res.body.num).to.be.a('number');
55+
done();
56+
})
57+
.catch(done);
58+
});
59+
});
60+
});

0 commit comments

Comments
 (0)