Skip to content

Commit

Permalink
bg(test): improve test coverage
Browse files Browse the repository at this point in the history
- cover untested lines in middlewares/returnTrip.js
- make sendEmail.js re-usable
- fix view all accommodation
- fix socialLogin missing strategies

[Finishes #171947441]
  • Loading branch information
T2Wil committed Mar 26, 2020
1 parent fe1a621 commit 1876373
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 67 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ module.exports = {
'treatUndefinedAsUnspecified': 0,
'import/extensions': ['off', 'never'],
'no-unused-expressions': [2, { allowTernary: true }],
'no-underscore-dangle': 0
'no-underscore-dangle': 0,
'no-nested-ternary': 0
}
};
5 changes: 2 additions & 3 deletions src/controllers/accommodation.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default class accomodationFacility {
return res.status(400)
.json({ status: 400, errorMessage: 'You forget to chose image' });
}
req.body.imageOfBuilding = `${process.env.HOST_NAME}/${req.file.url}`;
req.body.imageOfBuilding = req.file.url;
await accommodation.update(req.body, { id: req.params.id }, Accommodation);
return res.status(200).json({ status: 200, message: 'image uploaded successfully' });
} catch (error) {
Expand All @@ -63,8 +63,7 @@ export default class accomodationFacility {

static async createAccomodation(req, res) {
try {
req.body.imageOfBuilding = (typeof req.file === 'undefined') ? 'image'
: `${process.env.HOST_NAME}/${req.file.url}`;
req.body.imageOfBuilding = (typeof req.file === 'undefined') ? 'image' : req.file.url;
req.body.userId = req.user.id;
const newAccommodation = await Accommodation.create(req.body);
return res.status(201).json({ status: 200, data: newAccommodation });
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/booking.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default class bookAccomodation {
const { id } = req.user;
try {
const allBookings = await Accomodation.getAccommodation('getAll', id, Bookings);
if (!allBookings) {
if (allBookings) {
return res.status(200).json({ message: ' My bookings', allBookings });
}
return res.status(404).json({ message: 'No Booking found' });
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export default class requestsController {
} = request;
if (isRequestEmpty === false) {
const emailTitle = 'This is to inform you that a new request was made by:';
sendEmail(process.env.BN_EMAIL_NO_REPLY, manager.dataValues.email, request, 'New request was made', emailTitle);
sendEmail(process.env.BN_EMAIL_NO_REPLY, manager, request, 'New request was made', emailTitle);
const newNotification = await models.Notification.create({
requesterId: id, managerId, status: 'non_read', message: 'a new request was made', type: 'new_request', owner: 'manager',
});
Expand Down
4 changes: 4 additions & 0 deletions src/helpers/Request.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export default class Request {
);
}

static getAllRequests(requesterId) {
return models.Request.findAll({ where: { requesterId } });
}

static isRequestBelongsToManager(requestId, managerId) {
return models.Request.findOne(
{ where: { id: requestId, managerId } },
Expand Down
17 changes: 17 additions & 0 deletions src/helpers/getConflictingRequest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const getConflictingRequest = (request) => {
let conflictingRequest;
const {
createdAt, updatedAt, returnDate: returningDate, cities, ...oneWayTrip
} = request;
const {
createdAt: creationDate, updatedAt: updatedDate, cities: cit, ...twoWayTrip
} = request;
const { createdAt: creationDat, updatedAt: updatedDAt, ...multiWayTrip } = request;

request.type === 'one_way' ? conflictingRequest = oneWayTrip
: request.type === 'two_way' ? conflictingRequest = twoWayTrip
: conflictingRequest = multiWayTrip;
return conflictingRequest;
};

export default getConflictingRequest;
3 changes: 3 additions & 0 deletions src/helpers/getUrlAddress.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const getUrlAddress = (splitURL) => (splitURL ? splitURL[splitURL.length - 2] || null : null);

export default getUrlAddress;
2 changes: 1 addition & 1 deletion src/helpers/returnNotification.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { config } from 'dotenv';
config();

const returnNotification = (notification, url) => {
const html = `<p> ${notification.message} click <a href="${process.env.HOST_NAME}/${url}">here</a> to see the changes
const html = `<p> ${notification.message} click <a href="https://${process.env.HOST_NAME}/${url} "target="_blank">here</a> to see the changes
</p><br><p>Modified date: ${notification.updatedAt}</p> `;

return html;
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/sendEmail.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import dotenv from 'dotenv';

dotenv.config();
const sendEmail = async (businessEmail, requester, request, subject, title) => {
const url = `${process.env.HOST_NAME}/api/v1/trips/request/${request.id}`;
const url = `${process.env.HOST_NAME === 'localhost:4000' ? 'http://' : 'https://'}${process.env.HOST_NAME}/api/v1/trips/request/${request.id}`;
sendGrid.setApiKey(process.env.BN_API_KEY);
const msg = {
to: `${requester.email}`,
Expand All @@ -13,7 +13,7 @@ const sendEmail = async (businessEmail, requester, request, subject, title) => {
html: `<div>
<strong>Dear ${requester.firstName},<strong><br><br>
<p>${title}<p>
<strong>Open this <a href="${url}">link</a> to view request details.</strong>
Open this <a href="${url}">link</a> to view request details.
<br><br>Barefoot Nomad Team<br>
<br>Thank you<br>
</div>`,
Expand Down
59 changes: 15 additions & 44 deletions src/middlewares/validateReturnTrip.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import models from '../db/models';
import getTodayDate from '../helpers/getTodayDate';
import {
editRequestSchema,
createTwoWayTripSchema,
} from '../helpers/validationSchemas';
import isObjectEmpty from '../helpers/isObjectEmpty';
import getConflictingRequest from '../helpers/getConflictingRequest';
import Request from '../helpers/Request';
import getUrlAddress from '../helpers/getUrlAddress';

let conflictingTripRequest;
let conflictingRequest;

export default async (req, res, next) => {
try {
let schema;
let address;
const {
origin,
destination,
Expand All @@ -25,8 +26,7 @@ export default async (req, res, next) => {
const reqReturnDate = new Date(returnDate);

const urlSections = req.urlPathSections;
if (urlSections) address = urlSections[urlSections.length - 2] || null;

const address = getUrlAddress(urlSections);
if (address === 'edit') {
const isRequestEmpty = isObjectEmpty(req.body);
if (isRequestEmpty === true) throw ('Empty request');
Expand All @@ -49,81 +49,52 @@ export default async (req, res, next) => {
else if (reqReturnDate < reqDepartureDate) throw 'departureDate > returnDate';
else if (reqDepartureDate < todayDate) throw 'past departure date';
else if (departureDate || returnDate) {
const requests = await models.Request.findAll({
where: {
requesterId: req.user.id,
},
raw: true,
});
const requests = await Request.getAllRequests(req.user.id);
requests.map((request) => {
if (((request.departureDate <= reqDepartureDate)
&& (reqDepartureDate <= request.returnDate))
|| ((request.departureDate <= reqReturnDate) && (reqReturnDate <= request.returnDate))) {
if (request.type === 'one_way') {
const {
createdAt,
updatedAt,
returnDate,
cities,
...otherTripInfo
} = request;
conflictingTripRequest = otherTripInfo;
} else if (request.type === 'two_way') {
const {
createdAt,
updatedAt,
cities,
...otherTripInfo
} = request;
conflictingTripRequest = otherTripInfo;
} else if (request.type === 'multi_way') {
const {
createdAt,
updatedAt,
...otherTripInfo
} = request;
conflictingTripRequest = otherTripInfo;
}
conflictingRequest = getConflictingRequest(request);
throw 'conflicting trip';
}
});
}
next();
return next();
} catch (error) {
if (error === 'Empty request') {
return res.status(200).json({
res.status(200).json({
error: 'Empty request body.',
});
}
if (error.name === 'ValidationError') {
return res.status(422).json({
res.status(422).json({
status: res.statusCode,
error: error.message,
});
}
if (error === 'similar origin and destination') {
return res.status(422).json({
res.status(422).json({
status: res.statusCode,
error: 'Origin has to differ from destination.',
});
}
if (error === 'departureDate > returnDate') {
return res.status(422).json({
res.status(422).json({
status: res.statusCode,
error: "Returning date has to be the day after your departure's date!",
});
}
if (error === 'past departure date') {
return res.status(422).json({
res.status(422).json({
status: res.statusCode,
error: 'Please select travel date starting from today.',
});
}
if (error === 'conflicting trip') {
res.status(422).json({
res.status(409).json({
status: res.statusCode,
error: 'conflicting trip request.',
conflictingTripRequest,
conflictingRequest,
});
}
return res.status(500).json({
Expand Down
2 changes: 1 addition & 1 deletion src/routes/accommodation.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import { searchIndisLike, searchInLike } from '../middlewares/dislikeUser';
"application/x-www-form-urlencoded"
],
"consumes": [
"application/x-www-form-urlencoded"
"multipart/form-data"
],
"parameters": [
{
Expand Down
2 changes: 1 addition & 1 deletion src/routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@
*/

import express from 'express';
import passport from 'passport';
import passport from '../config/passport';
import usersController from '../controllers/users';
import userLoginValidation from '../middlewares/userLoginValidation';
import userValidation from '../middlewares/newUser';
Expand Down
2 changes: 1 addition & 1 deletion src/tests/mainTest.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ import testUserRoles from './userRoles.test';
routeExistance();
signUpTest();
userLoginTest();
twoWayTrip();
muliltiRequest();
allRequestTest();
notification();
twoWayTrip();
commentTest();
rejectRequest();
rememberMe();
Expand Down
19 changes: 8 additions & 11 deletions src/tests/twoWayTrip.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ chai.use(chaiHttp);

const { expect } = chai;
const {
validRequest, requestDateSetInThePast,
requestWithDepartureDateSetAfterReturnDate, repeatedRequest,
requestDateSetInThePast, requestWithDepartureDateSetAfterReturnDate,
requestWithMissedComponent, requestWithSimilarOriginAndDestination,
invalidTrip, sameDirection,
} = returnTripMock;

const testTwoWayTrip = () => {
Expand Down Expand Up @@ -86,8 +84,8 @@ const testTwoWayTrip = () => {
.end((err, res) => {
expect(res.status).to.equal(422);
expect(res.body).to.have.property('error');
done();
});
done();
});
it('should return 422 when similar origin and destination', (done) => {
chai
Expand All @@ -97,8 +95,8 @@ const testTwoWayTrip = () => {
.end((err, res) => {
expect(res.status).to.equal(422);
expect(res.body).to.have.property('error').that.equals('Origin has to differ from destination.');
done();
});
done();
});
it('should return 422 if departure date > return date', (done) => {
chai
Expand All @@ -108,8 +106,8 @@ const testTwoWayTrip = () => {
.end((err, res) => {
expect(res.status).to.equal(422);
expect(res.body).to.have.property('error').that.equals("Returning date has to be the day after your departure's date!");
done();
});
done();
});
it('should return 422 when departureDate is set in the past', (done) => {
chai
Expand All @@ -119,10 +117,10 @@ const testTwoWayTrip = () => {
.end((err, res) => {
expect(res.status).to.equal(422);
expect(res.body).to.have.property('error').that.equals('Please select travel date starting from today.');
done();
});
done();
});
it('should return 422 on a conflicting trip request', (done) => {
it('should return 409 on a conflicting trip request', () => {
chai
.request(app)
.post('/api/v1/trips/returnTrip')
Expand All @@ -135,9 +133,8 @@ const testTwoWayTrip = () => {
accommodation: 'Z campus',
})
.end((err, res) => {
expect(res.status).to.equal(422);
expect(res.status).to.equal(409);
expect(res.body).to.have.property('error').that.equals('conflicting trip request.');
done();
});
});
it('should return 401 if no token ', (done) => {
Expand All @@ -149,8 +146,8 @@ const testTwoWayTrip = () => {
.end((err, res) => {
expect(res.body).to.have.property('status').equals(401);
expect(res.body).to.have.property('error').equals('you are not logged in');
done();
});
done();
});
});
};
Expand Down

0 comments on commit 1876373

Please sign in to comment.