From a950692fd9a90263ecb955f7af0a4576f207befa Mon Sep 17 00:00:00 2001 From: Fatima Ali Date: Wed, 9 Aug 2023 18:57:48 +0300 Subject: [PATCH] Fix: update cancele order function and test cases #10 --- src/controllers/__tests__/order.test.ts | 10 +++++++--- src/controllers/order.ts | 20 ++++++++++++++------ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/controllers/__tests__/order.test.ts b/src/controllers/__tests__/order.test.ts index 85cebbb..4e6d3c9 100644 --- a/src/controllers/__tests__/order.test.ts +++ b/src/controllers/__tests__/order.test.ts @@ -104,7 +104,7 @@ describe('Order Routes', () => { }, ], totalPrice: 10, - orderStatus: 'Canceled', + orderStatus: 'Pending', customer: { firstName: 'John', lastName: 'Doe', @@ -116,19 +116,23 @@ describe('Order Routes', () => { }, }, cookerId: '64b9781dbee12ba0fe169899', + save: jest.fn(), }; const userFindByIdMock = jest.spyOn(User, 'findById'); userFindByIdMock.mockResolvedValue({ _id: '64b9781dbee12ba0fe169821' }); - const orderFindAndUpdateMock = jest.spyOn(Order, 'findByIdAndUpdate'); + const orderFindAndUpdateMock = jest.spyOn(Order, 'findById'); orderFindAndUpdateMock.mockResolvedValue(mockUpdateOrder); + const res = await request(server) .put(`/api/orders/64b9781dbee12ba0fe169877/cancel`) .set('Cookie', [`authTokenCompleted=s%3A${signedToken}`]); expect(res.status).toBe(200); expect(res.body.message).toBe('Order canceled successfully'); - expect(res.body.data).toEqual(mockUpdateOrder); + expect(JSON.stringify(res.body.data)).toEqual( + JSON.stringify(mockUpdateOrder) + ); expect(userFindByIdMock).toHaveBeenCalledTimes(1); expect(orderFindAndUpdateMock).toHaveBeenCalledTimes(1); }); diff --git a/src/controllers/order.ts b/src/controllers/order.ts index 1b4782f..173f00f 100644 --- a/src/controllers/order.ts +++ b/src/controllers/order.ts @@ -109,15 +109,23 @@ const cancelOrder = async (req: Request, res: Response) => { if (!customer) { return res.status(404).json({ message: 'User not found' }); } - const order = await Order.findByIdAndUpdate( - orderId, - { orderStatus: OrderStatus.Canceled }, - { new: true } - ); - + const order = await Order.findById({ _id: orderId }); if (!order) { return res.status(404).json({ error: 'Order not found' }); } + + if ( + order.orderStatus === OrderStatus.Canceled || + order.orderStatus === OrderStatus.Delivered + ) { + return res.status(400).json({ + error: 'You can not cancele order when its Delivered or Canceled', + }); + } + + order.orderStatus = OrderStatus.Canceled; + await order.save(); + // Format the orders data to make the response more concise and readable const formattedOrder = { _id: order._id,