Skip to content

Commit

Permalink
conflict resolusion
Browse files Browse the repository at this point in the history
  • Loading branch information
Ndevu12 committed Jun 4, 2024
2 parents 795238d + 229fcb1 commit 0dab3bc
Show file tree
Hide file tree
Showing 33 changed files with 1,316 additions and 27 deletions.
9 changes: 5 additions & 4 deletions src/__test__/cart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,9 @@ describe('Cart| Order management for guest/buyer', () => {
let productId: any;
let feedbackId: any;
let feedback2Id: any;

describe('Create order', () => {
it('should return 400 when user ID is not provided', async () => {
it('should return 201 when user is found', async () => {
const response = await request(app)
.post('/product/orders')
.send({
Expand Down Expand Up @@ -433,11 +434,11 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.message).toBe('Transaction history retrieved successfully');
});

it('should return 400 when user ID is not provided', async () => {
it('should return 400 when user is not AUTHORIZED', async () => {
const response = await request(app)
.get('/product/orders/history')
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
expect(response.status).toBe(200);
.set('Authorization', `Bearer ''`);
expect(response.status).toBe(403);
});
});

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();
});
});
231 changes: 231 additions & 0 deletions src/__test__/notification.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
import request from 'supertest';
import jwt from 'jsonwebtoken';
import { app, server } from '../index';
import { dbConnection } from '../startups/dbConnection';
import { User, UserInterface } from '../entities/User';
import { v4 as uuid } from 'uuid';
import { cleanDatabase } from './test-assets/DatabaseCleanup';
import { Notification } from '../entities/Notification';
import { NotificationItem } from '../entities/NotificationItem';
import exp from 'constants';

const user1Id = uuid();
const user2Id = uuid();
const user3Id = uuid();

const notificationId = uuid();
const notification2Id = uuid();

const notificationItemId = uuid();
const notificationItem2Id = uuid();
const notificationItem3Id = uuid();

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

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

const sampleUser: UserInterface = {
id: user1Id,
firstName: 'vendor1',
lastName: 'user',
email: '[email protected]',
password: 'password',
userType: 'Vendor',
gender: 'Male',
phoneNumber: '126380996347',
photoUrl: 'https://example.com/photo.jpg',
role: 'VENDOR',
};
const sampleUser2: UserInterface = {
id: user2Id,
firstName: 'buyer1',
lastName: 'user',
email: '[email protected]',
password: 'password',
userType: 'Buyer',
gender: 'Male',
phoneNumber: '126380996347',
photoUrl: 'https://example.com/photo.jpg',
role: 'BUYER',
};

const sampleUser3: UserInterface = {
id: user3Id,
firstName: 'buyer2',
lastName: 'user',
email: '[email protected]',
password: 'password',
userType: 'Buyer',
gender: 'Male',
phoneNumber: '1347',
photoUrl: 'https://example.com/photo.jpg',
role: 'BUYER',
};

const sampleNotification = {
id: notificationId,
unRead: 2,
user: sampleUser
};

const sampleNotification2 = {
id: notification2Id,
unRead: 1,
user: sampleUser3
};

const sampleNotificationItem = {
id: notificationItemId,
content: "This is notification content for test",
type: 'order',
isRead: false,
link: '/link/to/more-detail',
notification: sampleNotification
};


const sampleNotificationItem2 = {
id: notificationItem2Id,
content: "This is notification content for test",
type: 'order',
isRead: false,
link: '/link/to/more-detail',
notification: sampleNotification
};

const sampleNotificationItem3 = new NotificationItem();
sampleNotificationItem3.id = notificationItem3Id;
sampleNotificationItem3.content = "This is notification content for test";
sampleNotificationItem3.type = 'order';
sampleNotificationItem3.isRead = false;
sampleNotificationItem3.link = '/link/to/more-details';


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

const userRepository = connection?.getRepository(User);
await userRepository?.save({ ...sampleUser });
await userRepository?.save({ ...sampleUser2 });
await userRepository?.save({ ...sampleUser3 });

const notificationRepository = connection?.getRepository(Notification);
await notificationRepository?.save({ ...sampleNotification });

const result = await notificationRepository?.save({ ...sampleNotification2 });

const notificationItemRepository = connection?.getRepository(NotificationItem);
if (result) sampleNotificationItem3.notification = result;
await notificationItemRepository?.save({ ...sampleNotificationItem });
await notificationItemRepository?.save({ ...sampleNotificationItem2 });
await notificationItemRepository?.save({ ...sampleNotificationItem3 });
});

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

server.close();
});

describe('Notifications Tests', () => {
it('Should return all notification for authenticated user', async () => {
const response = await request(app)
.get('/notification/')
.set('Authorization', `Bearer ${getAccessToken(sampleUser.id!, sampleUser.email)}`);

expect(response.status).toBe(200);
expect(response.body.data.message).toBe('Notifications retrieved successfully');
});

it('Should return empty object if user doesn\'t have any notification', async () => {
const response = await request(app)
.get('/notification/')
.set('Authorization', `Bearer ${getAccessToken(sampleUser2.id!, sampleUser2.email)}`);

expect(response.status).toBe(200);
expect(response.body.data.message).toBe('User doesn\'t have any notifications.');
});

it('should update selected notifications, if there valid Ids and exist in DB', async () => {
const response = await request(app)
.put(`/notification/`)
.send({
notificationIds: [notificationItemId, 'sdfsdfd']
})
.set('Authorization', `Bearer ${getAccessToken(sampleUser.id!, sampleUser.email)}`);

expect(response.status).toBe(200);
expect(response.body.data.message).toBe('1 of 2 Notification(s) was successfully updated.');
});

it('should return 400, if no notifications ids provided to update', async () => {
const response = await request(app)
.put(`/notification/`)
.set('Authorization', `Bearer ${getAccessToken(sampleUser.id!, sampleUser.email)}`);

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

it('should update all unread notifications for authenticated user', async () => {
const response = await request(app)
.put(`/notification/all`)
.set('Authorization', `Bearer ${getAccessToken(sampleUser.id!, sampleUser.email)}`);

expect(response.status).toBe(200);
expect(response.body.data.message).toBe('All your unread notifications was successfully updated as read.');
});

it('should not update any notification if user doesn\'t have unread notifications.', async () => {
const response = await request(app)
.put(`/notification/all`)
.set('Authorization', `Bearer ${getAccessToken(sampleUser2.id!, sampleUser2.email)}`);

expect(response.status).toBe(200);
expect(response.body.data.message).toBe('User doesn\'t have any unread notifications.');
});

it('should delete selected notifications, if there valid Ids and exist in DB', async () => {
const response = await request(app)
.delete(`/notification/`)
.send({
notificationIds: [notificationItem3Id, 'sdfsdfd']
})
.set('Authorization', `Bearer ${getAccessToken(sampleUser3.id!, sampleUser3.email)}`);

expect(response.status).toBe(200);
expect(response.body.data.message).toBe('1 of 2 Notification(s) was successfully deleted.');
});

it('should return 400, if no notifications ids provided to delete', async () => {
const response = await request(app)
.delete(`/notification/`)
.set('Authorization', `Bearer ${getAccessToken(sampleUser.id!, sampleUser.email)}`);

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

it('should delete all notification for authenticated user.', async () => {
const response = await request(app)
.delete(`/notification/all`)
.set('Authorization', `Bearer ${getAccessToken(sampleUser.id!, sampleUser.email)}`);

expect(response.status).toBe(200);
expect(response.body.data.message).toBe('All Notifications was successfully deleted.');
});
it('Should not delete any notification, if user doesn\'t have notifications', async () => {
const response = await request(app)
.delete('/notification/all')
.set('Authorization', `Bearer ${getAccessToken(sampleUser2.id!, sampleUser2.email)}`);

expect(response.status).toBe(404);
expect(response.body.message).toBe('User doesn\'t have notifications');
});
});
Loading

0 comments on commit 0dab3bc

Please sign in to comment.