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

feat: Add tests for routes #5

Open
wants to merge 1 commit into
base: Day-3-Onboarding
Choose a base branch
from
Open
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
32 changes: 27 additions & 5 deletions config/paths.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { SCOPE_TYPE } from '@utils/constants';
import { hasScopeOverUser } from '@utils/index';

/**
* An array of path definitions representing different endpoints in the application.
*/
const paths = [
{
path: '/me',
Expand Down Expand Up @@ -30,7 +33,7 @@ const paths = [
{
path: '/oauth2/scopes',
scopes: [SCOPE_TYPE.SUPER_ADMIN, SCOPE_TYPE.ADMIN],
method: 'POST',
method: 'PATCH',

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this patch ?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to create a seperate item for patch

},
{
path: '/oauth2/scopes/{scopeId}',
Expand Down Expand Up @@ -78,15 +81,34 @@ const paths = [
customValidator: async (payload) => hasScopeOverUser(payload),
},
{
path: "/cabs/fetch",
path: '/cabs/fetch',
scopes: [
SCOPE_TYPE.INTERNAL_SERVICE,
SCOPE_TYPE.SUPER_ADMIN,
SCOPE_TYPE.ADMIN,
SCOPE_TYPE.USER,
],
method: 'POST',
},
{
path: '/driver',
scopes: [
SCOPE_TYPE.INTERNAL_SERVICE,
SCOPE_TYPE.SUPER_ADMIN,
SCOPE_TYPE.ADMIN,
SCOPE_TYPE.USER
],
method: "POST"
}
method: 'GET',
},
{
path: '/driver/{driverId}',
scopes: [
SCOPE_TYPE.INTERNAL_SERVICE,
SCOPE_TYPE.SUPER_ADMIN,
SCOPE_TYPE.ADMIN,
SCOPE_TYPE.USER,
],
method: 'GET',
},
];

export default paths;
14 changes: 8 additions & 6 deletions lib/models/rides.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ module.exports = function(sequelize, DataTypes) {
},
startPoint: {
field: "start_point",
type: DataTypes.GEOMETRY,
type: DataTypes.GEOMETRY('POINT'),
allowNull: false
},
endPoint: {
field: "end_point",
type: DataTypes.GEOMETRY,
allowNull: false
type: DataTypes.GEOMETRY('POINT'),
allowNull: true
},
timeStart: {
field: "time_start",
Expand All @@ -42,21 +42,23 @@ module.exports = function(sequelize, DataTypes) {
timeEnd: {
field: "time_end",
type: DataTypes.DATE,
allowNull: false
allowNull: true
},
fare: {
type: DataTypes.DECIMAL(10,2),
allowNull: false
allowNull: true
},
rideTime: {
field: "ride_time",
type: DataTypes.DECIMAL(10,2),
allowNull: false
allowNull: true
}
}, {
sequelize,
tableName: 'rides',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
indexes: [
{
name: "PRIMARY",
Expand Down
63 changes: 63 additions & 0 deletions lib/routes/cabs/tests/routes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { resetAndMockDB } from '@utils/testUtils';

describe('cabs route tests', () => {
let server;
beforeEach(async () => {
server = await resetAndMockDB(async (allDbs) => {
allDbs.models.cabs.$queryInterface.$useHandler((query) => {
if (query === 'findById') {
return null;
}
});
});
});
it('should return 500 if no body is passed', async () => {
const payload = {};
const res = await server.inject({
method: 'POST',
url: '/cabs/fetch',
payload,
});
// console.log(res)
expect(res.statusCode).toBe(500);
expect(res.statusMessage).toEqual('Internal Server Error');
});
it('should return 400 for invalid payload', async () => {
const payload = {
userid: 1,
currentLocation: {
latitude: 1,
longitude: 2,
},
}; // payload missing the currentLocation
const resp = await server.inject({
method: 'POST',
url: '/cabs/fetch',
payload,
});
expect(resp.statusCode).toBe(400);
expect(resp.statusMessage).toEqual('Bad Request');
});
it('should return 200', async () => {
const payload = {
userId: '1',
currentLocation: {
latitude: 1,
longitude: 2,
},
};
const res = await server.inject({
method: 'POST',
url: '/cabs/fetch',
payload,
});
expect(res.statusCode).toBe(200);
expect(Array.isArray(res.result)).toBe(true);
expect(res.result.length).toBeGreaterThan(0);
const firstCab = res.result[0];
expect(firstCab.id).toEqual(1);
expect(firstCab.driverId).toEqual(1);
expect(firstCab.carDetailsId).toEqual(1);
expect(firstCab.status).toEqual('available');
});
});
69 changes: 69 additions & 0 deletions lib/routes/driver/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { findAllDrivers, findOneDriver } from '@daos/driversDao';
import { badImplementation, notFound } from '@utils/responseInterceptors';
import { transformDbArrayResponseToRawResponse } from '@utils/transformerUtils';
import Joi from 'joi';
import { get } from 'lodash';

export default [
{
method: 'GET',
path: '/{driverId}',
options: {
description: 'get one driver by id',
notes: 'GET driver info API',
tags: ['api', 'driver'],
cors: true,
validate: {
params: Joi.object({
driverId: Joi.string().required(),
}),
},
},

handler: async (request, h) => {
// circuit breaker, rate-limiter can be used here
const { driverId } = request.params;
const driverInfo = await findOneDriver(driverId);
if (driverId){
return h.response(driverInfo).code(200);
}
return notFound(`No driver found with id: ${driverId}`);
},
},
{
method: 'GET',
path: '/',
handler: async (request, h) => {
const { page, limit } = request.query;
return findAllDrivers(page, limit)
.then((driversData) => {
if (get(driversData.allDrivers, 'length')) {
const { totalCount } = driversData;
const allDrivers = transformDbArrayResponseToRawResponse(
driversData.allDrivers,
).map((driver) => driver);

return h.response({
results: allDrivers,
totalCount,
});
}
return notFound('No drivers found');
})
.catch((error) => badImplementation(error.message));
},
options: {
description: 'get all drivers',
notes: 'GET drivers API',
tags: ['api', 'driver'],
plugins: {
pagination: {
enabled: true,
},
query: {
pagination: true,
},
},
},
}
];
120 changes: 120 additions & 0 deletions lib/routes/driver/tests/routes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { mockData } from '@utils/mockData';
import { resetAndMockDB } from '@utils/testUtils';

const { MOCK_DRIVER: drivers } = mockData;

describe('/driver route tests', () => {
let server;
beforeEach(async () => {
server = await resetAndMockDB(async (allDbs) => {
allDbs.models.drivers.$queryInterface.$useHandler((query) => {
if (query === 'findById') {
return drivers;
}
});
});
});
it('should return all the drivers', async () => {
server = await resetAndMockDB(async (allDbs) => {
allDbs.models.drivers.$queryInterface.$useHandler((query) => {
if (query === 'findById') {
return drivers;
}
});
});
const res = await server.inject({
method: 'GET',
url: '/driver',
});
const expectedResult = {
results: [
{
id: 1,
name: 'Test Driver',
license_number: 'ABC1234',
contact_number: '123456789',
ratings: 5,
status: 'available',
},
],
total_count: 1,
};
const { result } = res;
expect(res.statusCode).toBe(200); // this means route exists with above parametres
expect(result.results.length).toBe(expectedResult.results.length);
const driver = result.results[0];
const expectedDriver = expectedResult.results[0];
expect(driver.id).toBe(expectedDriver.id);
expect(driver.name).toBe(expectedDriver.name);
expect(driver.license_number).toBe(expectedDriver.license_number);
expect(driver.contact_number).toBe(expectedDriver.contact_number);
expect(driver.ratings).toBe(expectedDriver.ratings);
expect(driver.status).toBe(expectedDriver.status);
expect(result.total_count).toBe(expectedResult.total_count);
});

it('should return notFound if no drivers are found', async () => {
server = await resetAndMockDB(async (allDbs) => {
allDbs.models.drivers.$queryInterface.$useHandler((query) => {
if (query === 'findById') {
return null;
}
});
allDbs.models.drivers.findAll = () => null;
});
const resp = await server.inject({
method: 'GET',
url: '/driver',
});

expect(resp.statusCode).toBe(404);
});
it('should return badImplementation if findAllDrivers fails', async () => {
server = await resetAndMockDB(async (allDbs) => {
allDbs.models.drivers.$queryInterface.$useHandler((query) => {
if (query === 'findById') {
return null;
}
});
allDbs.models.drivers.findAll = () =>
new Promise((resolve, reject) => {
reject(new Error());
});
});

const res = await server.inject({
method: 'GET',
url: '/driver',
});

expect(res.statusCode).toBe(500);
});
});

describe("/driver/{driverId} routes tests",()=> {
let server;
beforeEach(async () => {
server = await resetAndMockDB(async (allDbs) => {
allDbs.models.drivers.$queryInterface.$useHandler((query) => {
if (query === 'findById') {
return drivers;
}
});
});
});
it("should return 200",async () => {
const resp = await server.inject({
method: "GET",
url: "/driver/1"
});
expect(resp.statusCode).toBe(200);
});
it("should return 404",async ()=> {
const res = await server.inject({
method:"GET",
url: "/drivers/2"
});
expect(res.statusCode).toBe(404);
expect(res.result.message).toEqual("Not Found")
})
})
Loading
Loading