freshyo/apps/backend/tests/api/order-lifecycle.test.ts
2026-10-17 12:07:20 +05:30

93 lines
3.1 KiB
TypeScript

/**
* Order lifecycle: notes, cancellation, pagination and the requested-id contract.
*/
import { apiClient, captureError } from '../helpers/api'
import { createFutureSlot, createStoreWithSku, ensureUserAddress } from '../helpers/fixtures'
import { userSession } from '../helpers/sessions'
describe('order lifecycle', () => {
let token = ''
let skuId = 0
let addressId = 0
let slotId = 0
let orderId = 0
beforeAll(async () => {
const store = await createStoreWithSku()
const slot = await createFutureSlot([store.skuId])
const address = await ensureUserAddress()
const user = await userSession()
token = user.token
skuId = store.skuId
addressId = address.addressId
slotId = slot.slotId
const res = await apiClient(token).user.order.placeOrder.mutate({
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId,
})
orderId = res.data[0].id
})
it('persists special instructions', async () => {
const notes = `Leave at reception ${Date.now()}`
await apiClient(token).user.order.updateUserNotes.mutate({ id: orderId, userNotes: notes })
const detail = await apiClient(token).user.order.getOrderById.query({
orderId: String(orderId),
})
expect(detail.userNotes).toBe(notes)
})
it('cancels the order with a reason and reflects it in the list', async () => {
const reason = `Changed my mind ${Date.now()}`
await apiClient(token).user.order.cancelOrder.mutate({ id: orderId, reason })
const detail = await apiClient(token).user.order.getOrderById.query({
orderId: String(orderId),
})
expect(detail.cancelReason).toBe(reason)
expect(String(detail.orderStatus).toLowerCase()).toMatch(/cancel/)
const list = await apiClient(token).user.order.getOrders.query({ page: 1, pageSize: 10 })
const row = list.data.find((o) => o.id === orderId)
expect(row).toBeDefined()
expect(String(row!.deliveryStatus).toLowerCase()).toMatch(/cancel/)
})
it('rejects a cancellation without a reason', async () => {
const error = await captureError(() =>
apiClient(token).user.order.cancelOrder.mutate({ id: orderId, reason: '' })
)
expect(error).toBeInstanceOf(Error)
})
it('rejects a readable order id ("ORD<id>") — the API wants the numeric string', async () => {
const error = await captureError(() =>
apiClient(token).user.order.getOrderById.query({ orderId: `ORD${orderId}` })
)
expect(error).toBeInstanceOf(Error)
})
it('paginates orders and rejects an oversized page size', async () => {
const page1 = await apiClient(token).user.order.getOrders.query({ page: 1, pageSize: 1 })
const page2 = await apiClient(token).user.order.getOrders.query({ page: 2, pageSize: 1 })
expect(page1.data).toHaveLength(1)
expect(page1.pagination.totalCount).toBeGreaterThan(1)
if (page2.data.length > 0) {
expect(page2.data[0].id).not.toBe(page1.data[0].id)
}
const error = await captureError(() =>
apiClient(token).user.order.getOrders.query({ page: 1, pageSize: 51 })
)
expect(error).toBeInstanceOf(Error)
})
})