Skip to content

Commit

Permalink
Merge pull request #124 from atlp-rwanda/fix-user-profile-management
Browse files Browse the repository at this point in the history
fix user profile managment
  • Loading branch information
faid-terence authored and maxCastro1 committed Jul 25, 2024
2 parents c67cbca + 0b6e258 commit 186bd7c
Show file tree
Hide file tree
Showing 15 changed files with 397 additions and 160 deletions.
49 changes: 17 additions & 32 deletions src/__test__/cart.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import request from 'supertest';
import jwt from 'jsonwebtoken';
import { app, server } from '../index';
Expand Down Expand Up @@ -38,7 +37,8 @@ let returnedCartItem2Id: string;

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

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

const sampleAdmin: UserInterface = {
id: sampleAdminId,
Expand All @@ -53,7 +53,6 @@ const sampleAdmin: UserInterface = {
role: 'ADMIN',
};


const getAccessToken = (id: string, email: string) => {
return jwt.sign(
{
Expand Down Expand Up @@ -232,7 +231,6 @@ afterAll(async () => {
});

describe('Cart| Order management for guest/buyer', () => {

describe('Adding product to cart on guest/buyer', () => {
it('should add product to cart as authenticated buyer', async () => {
const response = await request(app)
Expand Down Expand Up @@ -315,13 +313,10 @@ describe('Cart| Order management for guest/buyer', () => {
});

it('should return 400 for incorrect Id syntax (IDs not in uuid form), when add product to cart', async () => {
const response = await request(app)
.post(`/cart`)
.set('Cookie', [`cartId=dfgdsf`])
.send({
productId: product1Id,
quantity: 3,
});
const response = await request(app).post(`/cart`).set('Cookie', [`cartId=dfgdsf`]).send({
productId: product1Id,
quantity: 3,
});

expect(response.status).toBe(400);
});
Expand Down Expand Up @@ -412,11 +407,8 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.cart).toBeDefined;
});


it('should return 400 for incorrect Id syntax (IDs not in uuid form), when getting cart', async () => {
const response = await request(app)
.get(`/cart`)
.set('Cookie', [`cartId=dfgdsf`]);
const response = await request(app).get(`/cart`).set('Cookie', [`cartId=dfgdsf`]);

expect(response.status).toBe(400);
});
Expand Down Expand Up @@ -497,7 +489,6 @@ describe('Cart| Order management for guest/buyer', () => {
productId = response.body.data.orders[0]?.orderItems[0]?.product?.id;
});


it('should get single order', async () => {
const response = await request(app)
.get(`/product/client/orders/${orderId}`)
Expand All @@ -507,7 +498,7 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.order).toBeDefined();
});

it('should not return data for single order, if order doesn\'t exist', async () => {
it("should not return data for single order, if order doesn't exist", async () => {
const response = await request(app)
.get(`/product/client/orders/${uuid()}`)
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
Expand Down Expand Up @@ -541,9 +532,7 @@ describe('Cart| Order management for guest/buyer', () => {
});

it('should return 400 when user is not AUTHORIZED', async () => {
const response = await request(app)
.get('/product/orders/history')
.set('Authorization', `Bearer ''`);
const response = await request(app).get('/product/orders/history').set('Authorization', `Bearer ''`);
expect(response.status).toBe(403);
});
});
Expand All @@ -557,7 +546,7 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.status).toBe(200);
});

it('should return 404, if order doesn\'t exist', async () => {
it("should return 404, if order doesn't exist", async () => {
const response = await request(app)
.put(`/product/client/orders/${uuid()}`)
.send({ orderStatus: 'completed' })
Expand All @@ -583,18 +572,17 @@ describe('Cart| Order management for guest/buyer', () => {
feedbackId = response.body.data.id;
});


it('should create second feedback to the ordered product', async () => {
const response = await request(app)
.post(`/feedback/${productId}/new`)
.send({ orderId, comment: 'Murigalike this product looks so fantastic' })
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
expect(response.status).toBe(201);
feedback2Id = response.body.data.id
feedback2Id = response.body.data.id;
});
it('should updated existing feedback successfully', async () => {
const response = await request(app)
.put(`/feedback/update/${feedbackId}`,)
.put(`/feedback/update/${feedbackId}`)
.send({ orderId, comment: 'Well this product looks so lovely' })
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
expect(response.status).toBe(200);
Expand All @@ -609,7 +597,6 @@ describe('Cart| Order management for guest/buyer', () => {
});

describe('Feedback API', () => {

describe('Add feedback to the product with order', () => {
it('should create new feedback for the ordered product', async () => {
const response = await request(app)
Expand Down Expand Up @@ -725,15 +712,15 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.message).toBe('Feedback successfully removed');
});

it('should return 404, if feedback doesn\'t exist', async () => {
it("should return 404, if feedback doesn't exist", async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/${uuid()}`)
.set('Authorization', `Bearer ${getAccessToken(sampleAdminId, sampleAdmin.email)}`);

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

it('should return 500, for incorrect feedback id syntax (invalid uuid) doesn\'t exist', async () => {
it("should return 500, for incorrect feedback id syntax (invalid uuid) doesn't exist", async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/invalid-uuid`)
.set('Authorization', `Bearer ${getAccessToken(sampleAdminId, sampleAdmin.email)}`);
Expand All @@ -742,7 +729,6 @@ describe('Cart| Order management for guest/buyer', () => {
});
});
});

});

describe('Deleting product from cart', () => {
Expand Down Expand Up @@ -850,7 +836,7 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.cart).toBeDefined;
});

it('should return empty cart for guest user, if he/she doesn\'t have cart', async () => {
it("should return empty cart for guest user, if he/she doesn't have cart", async () => {
const response = await request(app)
.delete('/cart')
.set('Cookie', [`cartId=${sampleCartId}`]);
Expand All @@ -861,10 +847,9 @@ describe('Cart| Order management for guest/buyer', () => {
});

it('should return 400, for incorrect cart id syntax (invalid uuid) for guest user', async () => {
const response = await request(app).delete(`/cart`)
.set('Cookie', [`cartId=invalid-uuid`]);
const response = await request(app).delete(`/cart`).set('Cookie', [`cartId=invalid-uuid`]);

expect(response.status).toBe(400);
});
});
});
});
99 changes: 99 additions & 0 deletions src/__test__/transactions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import request from 'supertest';
import { app, server } from '../index'; // Adjust the path to your Express app
import Stripe from 'stripe';
import jwt from 'jsonwebtoken';
import { User, UserInterface } from '../entities/User';
import { dbConnection } from '../startups/dbConnection';
import { v4 as uuid } from 'uuid';
import { cleanDatabase } from './test-assets/DatabaseCleanup';

jest.mock('stripe', () => {
const stripeInstance = {
paymentIntents: {
list: jest.fn(),
},
};

return jest.fn(() => stripeInstance);
});
const jwtSecretKey = process.env.JWT_SECRET || '';

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

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

const Admin = uuid();
const sampleAdmin1: UserInterface = {
id: Admin,
firstName: 'vendor1o',
lastName: 'user',
email: '[email protected]',
password: 'password',
userType: 'Vendor',
gender: 'Male',
phoneNumber: '126380996348',
photoUrl: 'https://example.com/photo.jpg',
role: 'ADMIN',
};

const mockStripeInstance = new Stripe('fake-key', { apiVersion: '2024-04-10' }) as jest.Mocked<Stripe>;

describe('Transaction function', () => {
beforeEach(async () => {
const connection = await dbConnection();
(mockStripeInstance.paymentIntents.list as jest.Mock).mockClear();
const userRepository = connection?.getRepository(User);
await userRepository?.save({ ...sampleAdmin1 });
});

it('should return the correct payment statistics', async () => {
(mockStripeInstance.paymentIntents.list as jest.Mock).mockResolvedValue({
data: [
{ amount: 1000, amount_received: 1000, status: 'succeeded' },
{ amount: 2000, amount_received: 0, status: 'pending' },
],
} as any);

const response = await request(app)
.get('/product/transaction')
.set('Authorization', `Bearer ${getAccessToken(Admin, sampleAdmin1.email)}`);

expect(response.body).toEqual({
payments: [
{ amount: 1000, amount_received: 1000, status: 'succeeded' },
{ amount: 2000, amount_received: 0, status: 'pending' },
],
statistics: {
totalPayments: 2,
totalAmount: 3000,
totalCapturedAmount: 1000,
successfulPayments: 1,
pendingPayments: 1,
averagePaymentAmount: 1500,
},
});
});

it('should handle errors gracefully', async () => {
const error = new Error('Something went wrong');
(mockStripeInstance.paymentIntents.list as jest.Mock).mockRejectedValueOnce(error);

const response = await request(app)
.get('/product/transaction')
.set('Authorization', `Bearer ${getAccessToken(Admin, sampleAdmin1.email)}`);

expect(response.status).toBe(500);
expect(response.body).toEqual({ error: 'Something went wrong' });
});
});
Loading

0 comments on commit 186bd7c

Please sign in to comment.