Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve test coverage using mocks and stubs #52

Merged
merged 6 commits into from
Jun 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion UI/js/common/user_card_address.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ const home = document.getElementById('home');
const office = document.getElementById('office');

home.textContent = address.home;
office.textContent = address.office;
office.textContent = address.office;
2 changes: 1 addition & 1 deletion UI/js/common/user_loans.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ for (const [ i, loan ] of user_loans.entries()) {
</tr>
`;
table_ref.insertRow(-1).innerHTML = data;
}
}
2 changes: 1 addition & 1 deletion controllers/AuthController.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import
sendSignUpMessage
} from './helpers/AuthController';

const users_model = new Model('users');
export const users_model = new Model('users');

const AuthController = {
signup: async (req, res) => {
Expand Down
4 changes: 2 additions & 2 deletions controllers/LoansController.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import
sendNewApplicationMessage
} from './helpers/LoansController';

const loans_model = new Model('loans');
const repayments_model = new Model('repayments');
export const loans_model = new Model('loans');
export const repayments_model = new Model('repayments');
const rows = `id, userid, createdon, status, repaid, useremail,
amount, tenor, interest, balance, paymentinstallment`;

Expand Down
2 changes: 1 addition & 1 deletion controllers/UsersController.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from './helpers/AuthController';
import { aws_signed_url, } from './helpers/UsersController';

const users_model = new Model('users');
export const users_model = new Model('users');

const reset_password = async (model_instance, email, clause, res) => {
const new_password = generatePassword();
Expand Down
6 changes: 3 additions & 3 deletions controllers/helpers/AuthController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import bcrypt from 'bcrypt';
import titlecase from 'titlecase';

import { InternalServerError } from '../../utils/errorHandlers';
import sendEmail from '../../utils/sendEmail';
import Messenger from '../../utils/Messenger';
import hashPassword from '../../utils/hashPassword';

export const sendSignUpMessage = (user, req) => {
Expand All @@ -18,7 +18,7 @@ export const sendSignUpMessage = (user, req) => {
email: user.email,
template_name: 'confirm_account',
};
sendEmail(data, template_data);
Messenger.sendEmail(data, template_data);
return;
};

Expand All @@ -30,7 +30,7 @@ export const sendPassword = (email, new_password) => {
email,
template_name: 'new_password',
};
sendEmail(data, template_data);
Messenger.sendEmail(data, template_data);
return;
};

Expand Down
6 changes: 3 additions & 3 deletions controllers/helpers/LoansController.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import titlecase from 'titlecase';

import { InternalServerError } from '../../utils/errorHandlers';
import sendEmail from '../../utils/sendEmail';
import Messenger from '../../utils/Messenger';
// import { dev_logger } from '../../utils/loggers';

export const sendNewApplicationMessage = loan => {
Expand All @@ -15,7 +15,7 @@ export const sendNewApplicationMessage = loan => {
email: loan.useremail,
template_name: 'new_loan_application',
};
sendEmail(data, template_data);
Messenger.sendEmail(data, template_data);
return;
};

Expand All @@ -35,7 +35,7 @@ export const sendFollowUpMessage = (status, loan) => {
email: loan.useremail,
template_name: 'loan_status',
};
sendEmail(data, template_data);
Messenger.sendEmail(data, template_data);
return;
};

Expand Down
3 changes: 0 additions & 3 deletions middleware/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ const AuthenticationMiddleware = {
},

verifyToken: (req, res, next) => {
if (Settings.skipTokenVerification()) {
return next();
}
const token = req.headers['x-access-token'];
if (!token) {
const msg = 'Include a valid token in the x-access-token header';
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"start": "set NODE_ENV=production&node --require @babel/register ./bin/www ",
"devstart": "set NODE_ENV=development&set DEBUG=dev&nodemon --exec babel-node ./bin/www",
"lint": "./node_modules/.bin/eslint ./",
"test": "set NODE_ENV=test&set DEBUG=test&set DBNAME=testdb&nyc --reporter=html --reporter=text --reporter=lcov mocha -r @babel/register -r should",
"test": "set NODE_ENV=test&set DEBUG=test&set DBNAME=testdb&nyc --reporter=html --reporter=text --reporter=lcov mocha -r @babel/register -r should -r test/stubs.js",
"cover": "nyc report --reporter=text-lcov | coveralls",
"coverage": "nyc report --reporter=text-lcov | coveralls",
"devtables": "set DEBUG=dev&set DBNAME=quick_credit&node --require @babel/register utils/createTables",
Expand Down Expand Up @@ -52,13 +52,16 @@
"underscore": "^1.9.1"
},
"devDependencies": {
"chai": "^4.2.0",
"coveralls": "^3.0.3",
"debug": "^4.1.1",
"eslint": "^5.16.0",
"mocha": "^6.1.4",
"nodemon": "^1.18.11",
"nyc": "^14.1.1",
"should": "^13.2.3",
"sinon": "^7.3.2",
"sinon-chai": "^3.3.0",
"supertest": "^4.0.2"
},
"nyc": {
Expand Down
2 changes: 0 additions & 2 deletions settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ const Settings = {
region: 'eu-west-2',
signatureVersion: 'v4'
},
skipTokenVerification: () => (process.env.NODE_ENV === 'test'),
skipEmailSend: () => (process.env.NODE_ENV === 'test'),
};

dev_logger(Settings);
Expand Down
8 changes: 8 additions & 0 deletions test/beforeEach.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// import sinon from 'sinon';
// import Messenger from '../utils/Messenger';

// beforeEach(() => {
// sinon.stub(Messenger, 'sendEmail').callsFake(
// ((data, template_data) => { return; })
// );
// });
19 changes: 19 additions & 0 deletions test/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import sinon from 'sinon';

import { test_logger } from '../utils/loggers';
import { createDB, clearDB } from '../utils/localDbOps';


before(async () => {
test_logger('Creating DB');
await createDB();
});

after(async () => {
test_logger('Clearing DB');
await clearDB();
});

afterEach(() => {
sinon.restore(); // restore the globally stubbed AuthenticationMiddleware
});
80 changes: 53 additions & 27 deletions test/loans-spec.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,35 @@
// should is not used directly in the file but is added as a mocha requirement
import sinon from 'sinon';
import sgMail from '@sendgrid/mail';
import supertest from 'supertest';
import chai from 'chai';
import sinonChai from 'sinon-chai';

import { mockRequest, mockResponse } from './mocks';

import supertest from 'supertest';
import assert from 'assert';
import app from '../app';
import LoansController, { loans_model } from '../controllers/LoansController';

import { test_logger } from '../utils/loggers';
import { createDB, clearDB } from '../utils/localDbOps';
chai.use(sinonChai);
const { expect } = chai;

const server = supertest.agent(app);
const BASE_URL = '/api/v1';

describe('/loans', () => {
before(async () => {
test_logger('Creating DB in loans-spec');
await createDB();

const sandbox = sinon.createSandbox();

before(() => {
sandbox.stub(sgMail, 'send').returns();
});

after(async () => {
test_logger('Clearing DB in loans-spec');
await clearDB();
after(() => {
sandbox.restore();
});

describe('/loans: Get all loans', () => {
it('should be return a list of all loans', done => {
it('should return a list of all loans', done => {
server
.get(`${BASE_URL}/loans`)
.expect(200)
Expand All @@ -45,6 +51,15 @@ describe('/loans', () => {
done();
});
});

it('should throw error while getting all loans', async () => {
const req = mockRequest();
const res = mockResponse();
sinon.stub(loans_model, 'select').throws();
await LoansController.get_all_loans(req, res);
expect(res.status).to.have.been.calledWith(500);
sinon.restore();
});

it('should return all loans which have BEEN repaid', done => {
server
Expand All @@ -55,8 +70,8 @@ describe('/loans', () => {
res.status.should.equal(200);
res.body.data.should.be.an.instanceOf(Array);
for (const loan of res.body.data) {
assert(loan.status === 'approved');
assert(loan.repaid === true);
loan.should.have.property('status', 'approved');
loan.should.have.property('repaid', true);
}
done();
});
Expand All @@ -71,25 +86,36 @@ describe('/loans', () => {
res.status.should.equal(200);
res.body.data.should.be.an.instanceOf(Array);
for (const loan of res.body.data) {
assert(loan.status === 'approved');
assert(loan.repaid === false);
loan.should.have.property('status', 'approved');
loan.should.have.property('repaid', false);
}
done();
});
});

it('should return all loans for specified user', done => {
const id = 1;
server
.get(`${BASE_URL}/loans/user/${id}`)
.expect(200)
.end((err, res) => {
res.status.should.equal(200);
for (const each of res.body.data) {
each.should.have.property('userid', id);
}
done();
});
describe('/loans/user', () => {
it('should return all loans for specified user', done => {
const id = 1;
server
.get(`${BASE_URL}/loans/user/${id}`)
.expect(200)
.end((err, res) => {
res.status.should.equal(200);
for (const each of res.body.data) {
each.should.have.property('userid', id);
}
done();
});
});

it('should throw error while getting user loans', async () => {
const req = { params: { id: 5 } };
const res = { status() {}, json() {} };
sinon.stub(res, 'status').returnsThis();
sinon.stub(loans_model, 'select').throws();
await LoansController.get_user_loans(req, res);
expect(res.status).to.have.been.calledWith(500);
});
});
});

Expand Down
78 changes: 78 additions & 0 deletions test/middleware-spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import jwt from 'jsonwebtoken';

import sinon from 'sinon';
import chai from 'chai';
import sinonChai from 'sinon-chai';

import { mockRequest, mockResponse } from './mocks';
import AuthenticationMiddleware from '../middleware/authentication';

chai.use(sinonChai);
const { expect, } = chai;

describe('Middleware', () => {

beforeEach(() => { sinon.restore(); });

describe('generateToken', () => {
it('should generate and add token to reqeuest', done => {
const req = mockRequest();
const res = mockResponse();
const next = sinon.stub();
sinon.stub(jwt, 'sign').returns('token-string');
AuthenticationMiddleware.generateToken(req, res, next);
expect(req.token).to.equal('token-string');
expect(next).to.have.been.called;
done();
});
});

describe('AuthenticationMiddleware', () => {
describe('verifyToken', () => {
it('should return error if token is missing', done => {
const req = mockRequest();
const res = mockResponse();
const next = sinon.stub();
AuthenticationMiddleware.verifyToken(req, res, next);
expect(res.status).to.have.been.calledWith(422);
expect(res.json).to.have.been.calledWith({
error: 'No token provided',
msg: 'Include a valid token in the x-access-token header'
});
done();
});

it('should return next for correct token', done => {
const token = '123456';
const options = {
headers: { 'x-access-token': token }
};

const req = mockRequest(options);
const res = mockResponse();
const next = sinon.stub();
sinon.stub(jwt, 'verify').returns(token);
AuthenticationMiddleware.verifyToken(req, res, next);
expect(next).to.have.been.called;
done();
});

it('should throw error on token verification', done => {
const options = {
headers: { 'x-access-token': '123456' }
};

sinon.stub(jwt, 'verify').throws();
const req = mockRequest(options);
const res = mockResponse();
const next = sinon.stub();
AuthenticationMiddleware.verifyToken(req, res, next);
expect(res.status).to.have.been.calledWith(422);
expect(res.json).to.have.been.calledWith({
error: 'Invalid token'
});
done();
});
});
});
});
Loading