Skip to content

Commit

Permalink
Add more test cases for payment service (#127)
Browse files Browse the repository at this point in the history
* Fix data types in event listeners

* Rename show-products route in payment service

* Add more test case for payment service

* Remove requests.http
  • Loading branch information
thasup committed Apr 13, 2023
1 parent f66bce7 commit 0f04372
Show file tree
Hide file tree
Showing 9 changed files with 145 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import mongoose from 'mongoose';
import { type Message } from 'node-nats-streaming';
import { OrderStatus, type ExpirationCompletedEvent } from '@thasup-dev/common';

import { ExpirationCompletedListener } from '../ExpirationCompletedListener';
import { natsWrapper } from '../../../NatsWrapper';
import { Order } from '../../../models/order';
Expand All @@ -12,9 +13,7 @@ const setup = async (): Promise<{
listener: any
order: OrderDoc
product: ProductDoc
data: {
orderId: string
}
data: ExpirationCompletedEvent['data']
msg: Message
}> => {
const listener = new ExpirationCompletedListener(natsWrapper.client);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { type Message } from 'node-nats-streaming';
import mongoose from 'mongoose';
import { type ProductCreatedEvent } from '@thasup-dev/common';

import { ProductCreatedListener } from '../ProductCreatedListener';
import { Product } from '../../../models/product';
import type { ProductDoc } from '../../../types/product';
import { natsWrapper } from '../../../NatsWrapper';

const setup = async (): Promise<{
listener: any
data: Partial<ProductDoc>
data: ProductCreatedEvent['data']
msg: Message
}> => {
// create an instance of the listener
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { ProductDoc } from '../../../types/product';

const setup = async (): Promise<{
listener: any
data: Partial<ProductDoc>
data: ProductUpdatedEvent['data']
product: ProductDoc
msg: Message
}> => {
Expand Down
4 changes: 2 additions & 2 deletions payment/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { NotFoundError, errorHandler, currentUser } from '@thasup-dev/common';

import { createChargeRouter } from './routes/create-payment';
import { getPaymentRouter } from './routes/get-payment';
import { showProductRouter } from './routes/show-product';
import { showProductsRouter } from './routes/show-products';

const app = express();
app.set('trust proxy', true);
Expand All @@ -18,7 +18,7 @@ app.use(
);
app.use(currentUser);

app.use(showProductRouter);
app.use(showProductsRouter);
app.use(createChargeRouter);
app.use(getPaymentRouter);

Expand Down
99 changes: 99 additions & 0 deletions payment/src/routes/__test__/get-payment.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import mongoose from 'mongoose';
import request from 'supertest';
import { OrderStatus } from '@thasup-dev/common';

import { app } from '../../app';
import { Order } from '../../models/order';
import { Product } from '../../models/product';
import type { OrderDoc } from '../../types/order';

const setup = async (userId?: string): Promise<OrderDoc> => {
const price = Math.floor(Math.random() * 100000);

// Create and save a product
const product = Product.build({
id: new mongoose.Types.ObjectId().toHexString(),
title: 'Sample Dress',
price,
userId: new mongoose.Types.ObjectId().toHexString(),
image: './asset/sample.jpg',
colors: 'White,Black',
sizes: 'S,M,L',
countInStock: 1,
numReviews: 0,
rating: 0,
isReserved: false
});
await product.save();

const itemsPrice = Math.floor(parseFloat(product.price.toFixed(2)));
const taxPrice = Math.floor(parseFloat((product.price * 0.07).toFixed(2)));

// Create and save the order
const order = Order.build({
id: new mongoose.Types.ObjectId().toHexString(),
status: OrderStatus.Created,
userId: userId ?? new mongoose.Types.ObjectId().toHexString(),
version: 0,
paymentMethod: 'stripe',
itemsPrice,
shippingPrice: 0,
taxPrice,
totalPrice: itemsPrice + taxPrice
});
await order.save();

return order;
};

it('returns 404 if there is no order with that id', async () => {
const randomId = new mongoose.Types.ObjectId().toHexString();

await request(app)
.get(`/api/payments/${randomId}`)
.set('Cookie', global.signin())
.send({})
.expect(404);
});

it('returns 201 if user does not have authorization', async () => {
const userId = new mongoose.Types.ObjectId().toHexString();
const anotherUserId = new mongoose.Types.ObjectId().toHexString();

// Create and save a product
const order = await setup(userId);

// Get the payment with another user id
await request(app)
.get(`/api/payments/${order.id as string}`)
.set('Cookie', global.signin(anotherUserId))
.send({})
.expect(401);
});

it('returns 200 if the payment has found', async () => {
const userId = new mongoose.Types.ObjectId().toHexString();

// Create and save a product
const order = await setup(userId);

// Create the payment
await request(app)
.post('/api/payments')
.set('Cookie', global.signin(userId))
.send({
token: 'tok_visa',
orderId: order.id
})
.expect(201);

// Get the payment
const { body: fetchedPayment } = await request(app)
.get(`/api/payments/${order.id as string}`)
.set('Cookie', global.signin(userId))
.send({})
.expect(200);

expect(fetchedPayment[0]).toBeDefined();
expect(fetchedPayment[0].orderId).toEqual(order.id);
});
35 changes: 35 additions & 0 deletions payment/src/routes/__test__/show-products.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import mongoose from 'mongoose';
import request from 'supertest';

import { app } from '../../app';
import { Product } from '../../models/product';
import type { ProductDoc } from '../../types/product';

const buildProduct = async (): Promise<ProductDoc> => {
const product = Product.build({
id: new mongoose.Types.ObjectId().toHexString(),
title: 'Sample Dress',
price: 1990,
userId: new mongoose.Types.ObjectId().toHexString(),
image: './asset/sample.jpg',
colors: 'White,Black',
sizes: 'S,M,L',
countInStock: 1,
numReviews: 0,
rating: 0,
isReserved: false
});
await product.save();

return product;
};

it('can fetch a list of products', async () => {
await buildProduct();
await buildProduct();
await buildProduct();

const response = await request(app).get('/api/payments/products').send().expect(200);

expect(response.body.length).toEqual(3);
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import express, { type Request, type Response } from 'express';

import { Product } from '../models/product';

const router = express.Router();
Expand All @@ -9,4 +10,4 @@ router.get('/api/payments/products', async (req: Request, res: Response) => {
res.send(products);
});

export { router as showProductRouter };
export { router as showProductsRouter };
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ import { OrderCreatedListener } from '../OrderCreatedListener';
import { Product } from '../../../models/product';
import { natsWrapper } from '../../../NatsWrapper';
import type { ProductDoc } from '../../../types/product';
import type { OrderDoc } from '../../../types/order';

const setup = async (): Promise<{
listener: any
product: ProductDoc
data: Partial<OrderDoc>
data: OrderCreatedEvent['data']
msg: Message
}> => {
// Create an instance of the listener
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import { OrderUpdatedListener } from '../OrderUpdatedListener';
import { Product } from '../../../models/product';
import { natsWrapper } from '../../../NatsWrapper';
import type { ProductDoc } from '../../../types/product';
import type { OrderDoc } from '../../../types/order';

const setup = async (): Promise<{
listener: any
product: ProductDoc
data: Partial<OrderDoc>
data: OrderUpdatedEvent['data']
msg: Message
}> => {
// Create an instance of the listener
Expand Down

0 comments on commit 0f04372

Please sign in to comment.