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

increase order coverages #114

Merged
merged 15 commits into from
Jun 5, 2024
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 jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default {
resetMocks: true,
restoreMocks: true,
collectCoverageFrom: [
'src/services/**/*.{ts,tsx}', // Include all JavaScript/JSX files in the src directory
'src/**/*.{ts,tsx}', // Include all JavaScript/JSX files in the src directory
],
coveragePathIgnorePatterns: [
'/node_modules/', // Exclude the node_modules directory
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"mailgen": "^2.0.28",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"node-nlp": "^4.27.0",
"node-nlp": "^3.10.2",
"nodemailer": "^6.9.13",
"nodemon": "^3.1.0",
"passport": "^0.7.0",
Expand Down
12 changes: 10 additions & 2 deletions src/__test__/cart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ describe('Cart| Order management for guest/buyer', () => {
.get(`/product/client/orders/${orderId}`)
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);

expect(response.status).toBe(404);
expect(response.status).toBe(200);
});

it('should not return data for single order, if order doesn\'t exist', async () => {
Expand All @@ -493,7 +493,7 @@ describe('Cart| Order management for guest/buyer', () => {
.get(`/product/client/orders/incorrectId`)
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);

expect(response.status).toBe(404);
expect(response.status).toBe(400);
});

it('should return 404 if the buyer has no orders', async () => {
Expand Down Expand Up @@ -527,6 +527,14 @@ describe('Cart| Order management for guest/buyer', () => {
.send({ orderStatus: 'completed' })
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
expect(response.status).toBe(200);
expect(response.body.message).toBe("Order updated successfully");
});
it('should update order status successfully', async () => {
const response = await request(app)
.put(`/product/client/orders/${orderId}`)
.send({ orderStatus: 'completed' })
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
expect(response.status).toBe(401);
});
});
describe('Add feedback to the product with order', () => {
Expand Down
18 changes: 18 additions & 0 deletions src/__test__/coupon.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,24 @@ describe('Coupon Management System', () => {

expect(response.status).toBe(200);
}, 10000);

it('should return 200 for updating a product of coupon', async () => {
const response = await request(app)
.put(`/coupons/vendor/${vendor1Id}/update-coupon/${couponCode}`)
.send({ product: uuid() })
.set('Authorization', `Bearer ${getAccessToken(vendor1Id, sampleVendor1.email)}`);

expect(response.status).toBe(200);
}, 10000);

it('should return 404 for coupon not found', async () => {
const response = await request(app)
.put(`/coupons/vendor/${vendor1Id}/update-coupon/===__8899jjhh`)
.send({ product: uuid() })
.set('Authorization', `Bearer ${getAccessToken(vendor1Id, sampleVendor1.email)}`);

expect(response.status).toBe(404);
}, 10000);
});

describe('Delete Coupon', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/__test__/getProduct.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe('Creating new product', () => {

expect(response.status).toBe(201);
expect(response.body.data.product).toBeDefined;
}, 20000);
}, 60000);
});
describe('Get single product', () => {
it('should get a single product', async () => {
Expand Down
1 change: 0 additions & 1 deletion src/__test__/index.utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { server } from '..';
import { formatMoney, formatDate } from '../utils/index';

describe('Utility Functions', () => {
Expand Down
44 changes: 44 additions & 0 deletions src/__test__/isValid.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { isTokenValide } from '../middlewares/isValid';
import { Request, Response, NextFunction } from 'express';
import { getRepository } from 'typeorm';
import { User } from '../entities/User';

jest.mock('typeorm', () => ({
...jest.requireActual('typeorm'),
getRepository: jest.fn().mockImplementation((entity: any) => {
if (entity === User) {
return {
findOne: jest.fn(),
};
}
return jest.requireActual('typeorm').getRepository(entity);
}),
}));

const mockRequest = (userPayload: any): Request => {
return {
cookies: { token: 'mockToken' },
user: userPayload,
} as unknown as Request;
};

const mockResponse = () => {
const res: any = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};

const mockNext = jest.fn();

describe('isTokenValide middleware', () => {
it('should return 401 if no user payload', async () => {
const req = mockRequest(null);
const res = mockResponse();

await isTokenValide(req as Request, res as Response, mockNext as NextFunction);

expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ Message: 'Sorry, You are not authorized' });
});
});
83 changes: 83 additions & 0 deletions src/__test__/login.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import request from 'supertest';
import { app, server } from '../index';
import { createConnection, getRepository } from 'typeorm';
import { User, UserInterface } from '../entities/User';
import { cleanDatabase } from './test-assets/DatabaseCleanup';
import jwt from 'jsonwebtoken';
import { v4 as uuid } from 'uuid';
import { dbConnection } from '../startups/dbConnection';


const adminId = uuid();
const adminId1 = uuid();

const jwtSecretKey = process.env.JWT_SECRET || '';

const getAccessToken = (id: string, email: string) => {
return jwt.sign(
{
id: id,
email: email,
},
jwtSecretKey
);
};


if (!process.env.TEST_USER_EMAIL || !process.env.TEST_BUYER_EMAIL || !process.env.TEST_VENDOR1_EMAIL || !process.env.TEST_VENDOR_EMAIL || !process.env.TEST_USER_PASS) throw new Error('TEST_USER_PASS or TEST_USER_EMAIL not set in .env');

const sampleAdmin: UserInterface = {
id: adminId,
firstName: 'admin',
lastName: 'user',
email: process.env.TEST_USER_EMAIL,
password: process.env.TEST_USER_PASS,
userType: 'Admin',
gender: 'Male',
phoneNumber: '126380997',
photoUrl: 'https://example.com/photo.jpg',
verified: true,
role: 'ADMIN',
};

const sampleAdmin1: UserInterface = {
id: adminId1,
firstName: 'admin',
lastName: 'user',
email: '[email protected]',
password: process.env.TEST_USER_PASS,
userType: 'Admin',
gender: 'Male',
phoneNumber: '126380997',
photoUrl: 'https://example.com/photo.jpg',
verified: false,
role: 'ADMIN',
};

beforeAll(async () => {
const connection = await dbConnection();

const userRepository = connection?.getRepository(User);
await userRepository?.save([sampleAdmin, sampleAdmin1]);
});

afterAll(async () => {
await cleanDatabase();

server.close();
});

describe('POST /user/login', () => {
it('should not login a user with unverified email', async () => {

const loginUser = {
email: '[email protected]',
password: process.env.TEST_USER_LOGIN_PASS,
};

const loginResponse = await request(app).post('/user/login').send(loginUser);

expect(loginResponse.status).toBe(400);
expect(loginResponse.body).toBeDefined();
});
});
2 changes: 2 additions & 0 deletions src/__test__/roleCheck.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { dbConnection } from '../startups/dbConnection';
import { v4 as uuid } from 'uuid';
import { getConnection } from 'typeorm';
import { cleanDatabase } from './test-assets/DatabaseCleanup';
import { server } from '..';


let reqMock: Partial<Request>;
Expand Down Expand Up @@ -37,6 +38,7 @@ beforeAll(async () => {

afterAll(async () => {
await cleanDatabase();
server.close();
});

describe('hasRole MiddleWare Test', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/__test__/test-assets/DatabaseCleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ export const cleanDatabase = async () => {
// console.log('Database cleaned');
// }).catch(error => {
// console.error('Error cleaning database:', error);
// });
// });
33 changes: 33 additions & 0 deletions src/__test__/user.Route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// index.test.ts

import request from 'supertest';
import { app, server } from '../index';
import { dbConnection } from '../startups/dbConnection';
import { cleanDatabase } from './test-assets/DatabaseCleanup';

beforeAll(async () => {
await dbConnection();
});

afterAll(async () => {
await cleanDatabase();
server.close();
});

describe('USER ROUTE', () => {
it('should respond with 404, user not found', async () => {
const response = await request(app)
.get('/login/success')
.set('Content-Type', 'application/json');

expect(response.status).toBe(404);
});

it('Should respond 401, Login failed', async () => {
const response = await request(app)
.post('/login/failed')
.set('Content-Type', 'application/json');

expect(response.status).toBe(404);
});
});
102 changes: 102 additions & 0 deletions src/__test__/user.profile.update.service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { getConnection, getRepository, Repository } from 'typeorm';
import { User, UserInterface } from '../entities/User';
import { cleanDatabase } from './test-assets/DatabaseCleanup';
import {app, server } from '../index';
import { v4 as uuid } from 'uuid';
import { dbConnection } from '../startups/dbConnection';
import request from 'supertest';
import jwt from 'jsonwebtoken';

const adminId = uuid();

const jwtSecretKey = process.env.JWT_SECRET || '';

const getAccessToken = (id: string, email: string) => {
return jwt.sign(
{
id: id,
email: email,
},
jwtSecretKey
);
};

if (!process.env.TEST_USER_EMAIL || !process.env.TEST_BUYER_EMAIL || !process.env.TEST_VENDOR1_EMAIL || !process.env.TEST_VENDOR_EMAIL || !process.env.TEST_USER_PASS) throw new Error('TEST_USER_PASS or TEST_USER_EMAIL not set in .env');

const sampleAdmin: UserInterface = {
id: adminId,
firstName: 'admin',
lastName: 'user',
email:process.env.TEST_USER_EMAIL,
password: process.env.TEST_USER_PASS,
userType: 'Admin',
gender: 'Male',
phoneNumber: '126380997',
photoUrl: 'https://example.com/photo.jpg',
verified: true,
role: 'ADMIN',
};



beforeAll(async () => {
const connection = await dbConnection();
if (!connection) {
console.error('Failed to connect to the database');
return;
}

const userRepository = connection.getRepository(User);
await userRepository.save(sampleAdmin);
});

afterAll(async () => {
await cleanDatabase();
server.close();
});

describe('User profile update service', () => {
it('should validate a invalid user and return 400', async () => {
const res = await request(app)
.put('/user/update')
.set('Authorization', `Bearer ${getAccessToken(adminId, sampleAdmin.email)}`)
.send();

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

it('should validate a valid user', async () => {
const res = await request(app)
.put('/user/update')
.set('Authorization', `Bearer ${getAccessToken(adminId, sampleAdmin.email)}`)
.send({
firstName: 'admin',
lastName: 'user',
email: process.env.TEST_USER_EMAIL,
gender: 'Male',
phoneNumber: '126380997',
photoUrl: 'https://example.com/photo.jpg',
id: sampleAdmin.id,
});

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

it('should return 403 if user not authorized', async () => {
const fakeID = uuid();

const res = await request(app)
.put('/user/update')
.send({
firstName: 'admin',
lastName: 'user',
email: process.env.TEST_USER_EMAIL,
gender: 'Male',
phoneNumber: '126380997',
photoUrl: 'https://example.com/photo.jpg',
id: fakeID,
});

expect(res.statusCode).toBe(403);
});
});
4 changes: 2 additions & 2 deletions src/__test__/vendorProduct.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ describe('Vendor product management tests', () => {

expect(response.status).toBe(201);
expect(response.body.data.product).toBeDefined;
}, 60000);
}, 120000);

it('return an error if the number of product images exceeds 6', async () => {
const response = await request(app)
Expand Down Expand Up @@ -470,4 +470,4 @@ describe('Vendor product management tests', () => {
expect(response.status).toBe(400);
});
});
});
});
Loading
Loading