freshyo/apps/admin-ui/tests/pages/order-details.test.tsx
2026-10-20 00:31:05 +05:30

361 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 13.1 — Order details
* (`tests/pages/order-details.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import OrderDetails from '@/app/(drawer)/dashboard/manage-orders/order-details/[id]'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
procedureMutationCalls,
procedureQueryCalls,
setProcedure,
} from '../mocks/trpc-client'
import { router, __setParams } from '../mocks/expo-router-mock'
import { ORDER_DETAILS } from '../fixtures'
function order(overrides: Record<string, any> = {}) {
return {
...ORDER_DETAILS,
items: ORDER_DETAILS.items.map((item) => ({ ...item })),
...overrides,
}
}
function pressAlertButton(alertSpy: jest.SpyInstance, label: string) {
const call = alertSpy.mock.calls[alertSpy.mock.calls.length - 1]
const buttons = (call?.[2] ?? []) as Array<{ text?: string; onPress?: () => void }>
const button = buttons.find((candidate) => candidate.text === label)
if (!button?.onPress) throw new Error(`Alert button "${label}" not found`)
return button.onPress()
}
describe('Order details (AOD-01..25)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
__setParams({ id: '11' })
setProcedure('admin.order.getOrderDetails', { data: order() })
// The component renders `Added by {incident.addedBy}`; the default fixture's
// addedBy is an object, so keep this section empty for these cases.
setProcedure('admin.user.getUserIncidents', { data: { incidents: [] } })
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => alertSpy?.mockRestore())
function renderDetails() {
return renderWithProviders(<OrderDetails />, { auth: 'in' })
}
it('AOD-01: shows the loading copy', () => {
setProcedure('admin.order.getOrderDetails', { mode: 'pending' })
const view = renderDetails()
expect(view.getByText('Loading order details...')).toBeTruthy()
})
it('AOD-02: a failed load shows the error message and Go Back', () => {
setProcedure('admin.order.getOrderDetails', {
mode: 'error',
error: new Error('Order not found'),
})
const view = renderDetails()
expect(view.getByText('Oops!')).toBeTruthy()
expect(view.getByText('Order not found')).toBeTruthy()
fireEvent.press(view.getByText('Go Back'))
expect(router.back).toHaveBeenCalledTimes(1)
})
it('AOD-03: a missing id disables the query', () => {
__setParams({})
const view = renderDetails()
expect(procedureQueryCalls('admin.order.getOrderDetails')).toHaveLength(0)
expect(view.getByText('Failed to load order details')).toBeTruthy()
})
it('AOD-04: renders the header with id, date and status', () => {
const view = renderDetails()
expect(view.getByText('Order ID')).toBeTruthy()
expect(view.getByText('#101')).toBeTruthy()
expect(view.getByText('pending')).toBeTruthy()
expect(view.getByText(/Placed on/)).toBeTruthy()
expect(view.getByText(/Delivery at:/)).toBeTruthy()
})
it('AOD-05: a cancelled order shows the cancellation reason block', () => {
setProcedure('admin.order.getOrderDetails', {
data: {
...order({ status: 'cancelled', cancelReason: 'Customer changed their mind' }),
},
})
const view = renderDetails()
expect(view.getByText('Cancellation Reason')).toBeTruthy()
expect(view.getByText('Customer changed their mind')).toBeTruthy()
})
it('AOD-06: renders the customer card and links to the user', () => {
const view = renderDetails()
expect(view.getByText('Customer Details')).toBeTruthy()
expect(view.getByText('Test User')).toBeTruthy()
expect(view.getByText('9876543210')).toBeTruthy()
expect(view.getByText(/12 Main Road/)).toBeTruthy()
fireEvent.press(view.getByTestId('customer-details-card'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
})
it('AOD-07: renders each item with quantity, price and packaging controls', () => {
const view = renderDetails()
expect(view.getByText('Chicken Breast')).toBeTruthy()
expect(view.getByText('2 x 500g × ₹215')).toBeTruthy()
expect(view.getByText('₹430')).toBeTruthy()
expect(view.getByText('Cucumber')).toBeTruthy()
expect(view.getByText('1 x 500g × ₹15')).toBeTruthy()
expect(view.getAllByText('₹15').length).toBeGreaterThanOrEqual(1)
expect(view.getByTestId('order-item-packaged-1')).toBeTruthy()
expect(view.getByTestId('order-item-verified-1')).toBeTruthy()
})
it('AOD-08: the Packaged control calls updateOrderItemPackaging', async () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('order-item-packaged-1'))
await flush(2)
expect(lastMutationInput('admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 1,
isPackaged: true,
})
})
it('AOD-09: the Pkg Verified control calls updateOrderItemPackaging', async () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('order-item-verified-1'))
await flush(2)
expect(lastMutationInput('admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 1,
isPackageVerified: true,
})
})
it('AOD-10: a pending item update disables the item control', async () => {
setProcedure('admin.order.updateOrderItemPackaging', { mode: 'pending' })
const view = renderDetails()
fireEvent.press(view.getByTestId('order-item-packaged-1'))
await flush(2)
expect(
view.getByTestId('order-item-packaged-1').props.accessibilityState?.disabled,
).toBe(true)
})
it('AOD-11: a failed item update shows an alert', async () => {
setProcedure('admin.order.updateOrderItemPackaging', {
mode: 'error',
error: new Error('boom'),
})
const view = renderDetails()
fireEvent.press(view.getByTestId('order-item-verified-1'))
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
})
it('AOD-12: renders the bill summary', () => {
const view = renderDetails()
expect(view.getByText('Subtotal (2 items)')).toBeTruthy()
expect(view.getAllByText('₹445').length).toBe(2)
expect(view.getByText('Delivery Charge')).toBeTruthy()
expect(view.getAllByText('₹15').length).toBeGreaterThanOrEqual(1)
expect(view.getByText('Total Amount')).toBeTruthy()
})
it('AOD-13: removing the delivery charge confirms and calls the mutation', async () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('remove-delivery-charge'))
expect(alertSpy).toHaveBeenCalledWith(
'Remove Delivery Cost',
'Are you sure you want to remove the delivery cost from this order?',
expect.any(Array),
)
await act(async () => {
pressAlertButton(alertSpy, 'Remove')
})
await flush(2)
expect(lastMutationInput('admin.order.removeDeliveryCharge')).toEqual({ orderId: 11 })
expect(alertSpy).toHaveBeenCalledWith('Success', 'Delivery charge has been removed')
})
it('AOD-14: a failed remove shows an alert', async () => {
setProcedure('admin.order.removeDeliveryCharge', {
mode: 'error',
error: new Error('boom'),
})
const view = renderDetails()
fireEvent.press(view.getByTestId('remove-delivery-charge'))
await act(async () => {
pressAlertButton(alertSpy, 'Remove')
})
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
})
it('AOD-15: a zero delivery charge hides the remove action', () => {
setProcedure('admin.order.getOrderDetails', { data: order({ deliveryCharge: 0 }) })
const view = renderDetails()
expect(view.queryByTestId('remove-delivery-charge')).toBeNull()
expect(view.queryByText('Delivery Charge')).toBeNull()
})
it('AOD-16: an applied coupon renders the coupon block', () => {
setProcedure('admin.order.getOrderDetails', {
data: order({
couponCode: 'SAVE10',
couponDescription: '10% off',
discountAmount: 20,
}),
})
const view = renderDetails()
expect(view.getByText('Coupon Applied')).toBeTruthy()
expect(view.getByText('SAVE10')).toBeTruthy()
expect(view.getByText('10% off')).toBeTruthy()
expect(view.getByText('Discount Applied:')).toBeTruthy()
expect(view.getAllByText('-₹20').length).toBeGreaterThanOrEqual(1)
})
it('AOD-17: a flash order renders the amber flash notice', () => {
setProcedure('admin.order.getOrderDetails', {
data: order({ isFlashDelivery: true }),
})
const view = renderDetails()
expect(view.getByText('1 Hr Delivery Order')).toBeTruthy()
expect(view.getByText('⚡ 1 Hr Delivery • High Priority')).toBeTruthy()
expect(view.getByText(/Expected Delivery:/)).toBeTruthy()
})
it('AOD-18: admin notes render, user notes are not displayed (current)', () => {
setProcedure('admin.order.getOrderDetails', {
data: order({ adminNotes: 'Call before delivery' }),
})
const view = renderDetails()
expect(view.getByText('Admin Notes')).toBeTruthy()
expect(view.getByText('Call before delivery')).toBeTruthy()
// The details screen has no user-notes block.
expect(view.queryByText('Leave at door')).toBeNull()
})
it('AOD-19: Cancel Order opens the cancellation dialog', () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button'))
expect(view.getByText('Cancellation Reason *')).toBeTruthy()
expect(
view.getByText('This will cancel the order and mark it as cancelled by admin.'),
).toBeTruthy()
})
it('AOD-20: an empty cancellation reason is blocked', () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button'))
const buttons = view.getAllByText('Cancel Order')
fireEvent.press(buttons[buttons.length - 1])
expect(procedureMutationCalls('admin.order.cancelOrder')).toHaveLength(0)
expect(alertSpy).not.toHaveBeenCalled()
})
it('AOD-21: confirming cancellation calls cancelOrder with the reason', async () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button'))
fireEvent.changeText(view.getByTestId('cancel-order-reason'), 'Customer requested')
fireEvent.press(view.getByTestId('cancel-order-confirm'))
expect(alertSpy).toHaveBeenCalledWith(
'Cancel Order',
'Are you sure you want to cancel this order? This action cannot be undone.',
expect.any(Array),
)
await act(async () => {
pressAlertButton(alertSpy, 'Yes, Cancel')
})
await flush(2)
expect(lastMutationInput('admin.order.cancelOrder')).toEqual({
orderId: 11,
reason: 'Customer requested',
})
})
it('AOD-22: a failed cancellation shows an alert', async () => {
setProcedure('admin.order.cancelOrder', { mode: 'error', error: new Error('boom') })
const view = renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button'))
fireEvent.changeText(view.getByTestId('cancel-order-reason'), 'Customer requested')
fireEvent.press(view.getByTestId('cancel-order-confirm'))
await act(async () => {
pressAlertButton(alertSpy, 'Yes, Cancel')
})
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
})
it('AOD-23: Manage Orders returns to the orders hub', () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('order-details-back-button'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
})
it('AOD-24: the customer card opens the user detail route', () => {
const view = renderDetails()
fireEvent.press(view.getByTestId('customer-details-card'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
})
it('AOD-25: the details screen renders no OrderOptionsMenu', () => {
const view = renderDetails()
expect(view.queryByText('Select an action to perform')).toBeNull()
expect(view.queryByText('View Details')).toBeNull()
expect(view.getByTestId('order-details-cancel-button')).toBeTruthy()
expect(view.getByTestId('order-details-back-button')).toBeTruthy()
})
})