|
| 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 validUserCredentials = { |
| 12 | + username: 'react', |
| 13 | + password: 'express' |
| 14 | + }; |
| 15 | + |
| 16 | + const invalidUserCredentials = { |
| 17 | + username: 'react', |
| 18 | + password: 'IDontKnow' |
| 19 | + }; |
| 20 | + |
| 21 | + let jwtToken; |
| 22 | + |
| 23 | + describe('# POST /api/auth/login', () => { |
| 24 | + it('should return Authentication error', (done) => { |
| 25 | + request(app) |
| 26 | + .post('/api/auth/login') |
| 27 | + .send(invalidUserCredentials) |
| 28 | + .expect(httpStatus.UNAUTHORIZED) |
| 29 | + .then((res) => { |
| 30 | + expect(res.body.message).to.equal('Authentication error'); |
| 31 | + done(); |
| 32 | + }) |
| 33 | + .catch(done); |
| 34 | + }); |
| 35 | + |
| 36 | + it('should get valid JWT token', (done) => { |
| 37 | + request(app) |
| 38 | + .post('/api/auth/login') |
| 39 | + .send(validUserCredentials) |
| 40 | + .expect(httpStatus.OK) |
| 41 | + .then((res) => { |
| 42 | + expect(res.body).to.have.property('token'); |
| 43 | + jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => { |
| 44 | + expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions |
| 45 | + expect(decoded.username).to.equal(validUserCredentials.username); |
| 46 | + jwtToken = `Bearer ${res.body.token}`; |
| 47 | + done(); |
| 48 | + }); |
| 49 | + }) |
| 50 | + .catch(done); |
| 51 | + }); |
| 52 | + }); |
| 53 | + |
| 54 | + describe('# GET /api/auth/random-number', () => { |
| 55 | + it('should fail to get random number because of missing Authorization', (done) => { |
| 56 | + request(app) |
| 57 | + .get('/api/auth/random-number') |
| 58 | + .expect(httpStatus.UNAUTHORIZED) |
| 59 | + .then((res) => { |
| 60 | + expect(res.body.message).to.equal('Unauthorized'); |
| 61 | + done(); |
| 62 | + }) |
| 63 | + .catch(done); |
| 64 | + }); |
| 65 | + |
| 66 | + it('should get a random number', (done) => { |
| 67 | + request(app) |
| 68 | + .get('/api/auth/random-number') |
| 69 | + .set('Authorization', jwtToken) |
| 70 | + .expect(httpStatus.OK) |
| 71 | + .then((res) => { |
| 72 | + expect(res.body.num).to.be.a('number'); |
| 73 | + done(); |
| 74 | + }) |
| 75 | + .catch(done); |
| 76 | + }); |
| 77 | + }); |
| 78 | +}); |
0 commit comments