freshyo/apps/user-ui/tests/pages/checkout.test.tsx
2026-11-08 13:49:17 +05:30

548 lines
20 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 14 — Checkout (`tests/pages/checkout.test.tsx`,
* CHECK-01..CHECK-35).
*
* The real routes run:
* - `app/(drawer)/(tabs)/home/checkout.tsx` (scheduled)
* - `app/(drawer)/(tabs)/flash-delivery/checkout.tsx` (flash)
*
* Only the tRPC procedure registry, the CDN JSON docs and native modules are
* mocked. `packages/shared/cart-pricing.ts` stays REAL, so the bill figures are
* the same ones the backend uses.
*
* URL params (`slots`, `coupons`) come from the expo-router mock; cart lines
* come from the secure-store mock.
*/
import * as React from 'react'
import { QueryClient } from '@tanstack/react-query'
import { act, fireEvent, within } from '@testing-library/react-native'
import dayjs from 'dayjs'
import Checkout from '@/app/(drawer)/(tabs)/home/checkout'
import FlashCheckout from '@/app/(drawer)/(tabs)/flash-delivery/checkout'
import constants from '@/src/constants'
import {
flush,
renderWithProviders,
seedBoot,
seedCentralStores,
} from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { lastProcedureInput, procedureMutationCalls, setProcedure } from '../mocks/trpc-client'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { __setParams, router } from '../mocks/expo-router-mock'
import {
A1,
CART_SLOTS_RESPONSE,
CONSTS,
MERGED_PRODUCTS,
SLOTS,
} from '../fixtures'
const CART_KEY = 'cart_items'
const FLASH_KEY = 'flash_cart_items'
const line = (id: number, skuId: number, quantity: number, slotId: number) => ({
id,
skuId,
quantity,
slotId,
addedAt: '2024-01-01T00:00:00.000Z',
})
function seedCart(lines: any[], key = CART_KEY) {
__set(key, JSON.stringify(lines))
}
/** Flatten a rendered node's text (handles nested Text and arrays). */
function textOf(node: any): string {
if (node == null || typeof node === 'boolean') return ''
if (typeof node === 'string' || typeof node === 'number') return String(node)
if (Array.isArray(node)) return node.map(textOf).join('')
if (node.props && node.props.children !== undefined) return textOf(node.props.children)
return ''
}
/** Mutation GC off so a finished placeOrder never keeps jest alive. */
function createClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: Infinity,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false, gcTime: 0 },
},
})
}
interface MountOptions {
lines?: any[] | null
key?: string
flash?: boolean
auth?: 'in' | 'out'
addressId?: number | null
params?: Record<string, any>
flushTimes?: number
noFlush?: boolean
setup?: () => void
}
async function mount(opts: MountOptions = {}) {
seedBoot({ addressId: opts.addressId === undefined ? A1.id : opts.addressId })
setProcedure('user.cart.getCartSlots', { data: CART_SLOTS_RESPONSE })
opts.setup?.()
if (opts.lines) {
seedCart(opts.lines, opts.key ?? (opts.flash ? FLASH_KEY : CART_KEY))
}
__setParams(opts.params ?? {})
const ui = opts.flash ? <FlashCheckout /> : <Checkout />
const result = renderWithProviders(ui, {
auth: opts.auth ?? 'in',
queryClient: createClient(),
})
if (!opts.noFlush) await flush(opts.flushTimes ?? 5)
return result
}
describe('Checkout — CHECK-01..35', () => {
beforeEach(() => resetAllMocks())
/* ------------------------------------------------------------------------ */
/* 14.1 Gates and empty states */
/* ------------------------------------------------------------------------ */
it('CHECK-01: unauthenticated stores target/query and pushes login', async () => {
const { getByTestId } = await mount({
auth: 'out',
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(getByTestId('checkout-header')).toBeTruthy()
expect(router.push).toHaveBeenCalledWith('/(auth)/login')
const stored = JSON.parse(__snapshot()[constants.AUTH_REDIRECT_KEY])
expect(stored.targetUrl).toBe('/(drawer)/(tabs)/home/checkout')
expect(stored.queryParams).toMatchObject({ slots: '1849:1' })
})
it('CHECK-02: auth loading does not redirect', async () => {
await mount({ auth: 'in', noFlush: true, lines: [line(1, 2, 2, 1849)] })
expect(router.push).not.toHaveBeenCalled()
})
it('CHECK-03: an empty cart shows "Your cart is empty" and Back to Shopping', async () => {
const { getByTestId } = await mount({ lines: null, params: {} })
expect(getByTestId('checkout-empty-title')).toHaveTextContent('Your cart is empty')
expect(getByTestId('checkout-empty-back')).toHaveTextContent('Back to Shopping')
})
it('CHECK-04: cart lines without selected slots show "No items to checkout"', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: {},
})
expect(getByTestId('checkout-empty-title')).toHaveTextContent('No items to checkout')
expect(getByTestId('checkout-empty-copy')).toHaveTextContent(
'Please select delivery slots for your items'
)
})
it('CHECK-05: flash cart lines that are not flash eligible show the flash message', async () => {
const { getByTestId } = await mount({
flash: true,
lines: [line(1, 2, 1, 0)],
params: {},
})
expect(getByTestId('checkout-empty-title')).toHaveTextContent('No items to checkout')
expect(getByTestId('checkout-empty-copy')).toHaveTextContent(
'None of your cart items are available for flash delivery'
)
})
it('CHECK-06: Back to Shopping calls router.back', async () => {
const { getByTestId } = await mount({ lines: null, params: {} })
fireEvent.press(getByTestId('checkout-empty-back'))
expect(router.back).toHaveBeenCalled()
})
/* ------------------------------------------------------------------------ */
/* 14.2 Items, slots and pricing */
/* ------------------------------------------------------------------------ */
it('CHECK-07: selected slots render the header and the Items section', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(getByTestId('checkout-header-title')).toHaveTextContent('Scheduled Delivery Checkout')
expect(getByTestId('checkout-items-section')).toBeTruthy()
expect(getByTestId('checkout-item-1')).toBeTruthy()
})
it('CHECK-08: items are grouped by slot, sorted by delivery time, with a Slot #id fallback', async () => {
const { getAllByTestId } = await mount({
lines: [line(1, 2, 1, 1850), line(2, 5, 1, 1849), line(3, 8, 1, 9999)],
params: { slots: '1850:1;1849:2;9999:3' },
})
const labels = getAllByTestId(/^checkout-slot-label-/).map((node) => textOf(node))
expect(labels).toEqual([
dayjs(SLOTS[0].deliveryTime).format('ddd, DD MMM h:mm A'),
dayjs(SLOTS[1].deliveryTime).format('ddd, DD MMM h:mm A'),
'Slot #9999',
])
})
it('CHECK-09: the flash checkout renders one unlabeled group', async () => {
const { getByTestId, queryAllByTestId, getByText } = await mount({
flash: true,
lines: [line(1, 8, 1, 0)],
params: {},
})
expect(getByTestId('checkout-header-title')).toHaveTextContent('1 Hr Delivery Checkout')
expect(getByTestId('checkout-slot-group-flash')).toBeTruthy()
expect(queryAllByTestId(/^checkout-slot-label-/)).toHaveLength(0)
expect(getByText('Paneer')).toBeTruthy()
})
it('CHECK-10: an item line shows name, unit, x quantity and line total', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
const row = getByTestId('checkout-item-1')
expect(within(row).getByText('Chicken Breast')).toBeTruthy()
expect(within(row).getByText('500g')).toBeTruthy()
expect(within(row).getByText('x2')).toBeTruthy()
expect(within(row).getByText('₹430')).toBeTruthy()
})
it('CHECK-11: a cart item not selected by the URL is excluded from items and totals', async () => {
const { queryByTestId, getByTestId } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 5, 1, 1849)],
params: { slots: '1849:1' },
})
expect(queryByTestId('checkout-item-2')).toBeNull()
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹430')
})
it('CHECK-12: missing product data renders a blank name and ₹0 (current)', async () => {
const { getByTestId, queryByText } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
setup: () =>
seedCentralStores({
products: MERGED_PRODUCTS.map((product) =>
product.id === 2 ? { ...product, name: '', price: 0 } : product
),
}),
})
const row = getByTestId('checkout-item-1')
expect(within(row).getByText('₹0')).toBeTruthy()
expect(queryByText('Chicken Breast')).toBeNull()
})
it('CHECK-13: the address shows selected, then default, then no address', async () => {
const first = await mount({
addressId: A1.id,
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(first.getByTestId('checkout-address-name')).toHaveTextContent('Home')
first.unmount()
// The neo model has no read-time default fallback: no selection means no
// address card, even when the user has a saved default.
const second = await mount({
addressId: null,
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(second.getByTestId('checkout-address-empty')).toBeTruthy()
second.unmount()
const third = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
setup: () => setProcedure('user.address.getUserAddresses', { data: { data: [] } }),
})
expect(third.getByTestId('checkout-address-empty')).toBeTruthy()
})
it('CHECK-28: the flash checkout uses the flash price in items and totals', async () => {
const { getByTestId } = await mount({
flash: true,
lines: [line(1, 8, 1, 0)],
params: {},
})
expect(within(getByTestId('checkout-item-1')).getByText('₹75')).toBeTruthy()
expect(getByTestId('bill-delivery-amount')).toHaveTextContent('₹25')
expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹100')
})
it('CHECK-29: cart updates while checkout is open recompute selectedItems', async () => {
const { getByTestId, queryClient } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹430')
__set(CART_KEY, JSON.stringify([line(1, 2, 1, 1849)]))
await act(async () => {
await queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] })
})
await flush(3)
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹215')
expect(within(getByTestId('checkout-item-1')).getByText('x1')).toBeTruthy()
})
it('CHECK-30: an item out of stock after the cart is excluded from totals and the order', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 1, 1849), line(2, 6, 1, 1849)],
params: { slots: '1849:1;1849:2' },
})
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹215')
expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹230')
fireEvent.press(getByTestId('place-order-button'))
await flush(4)
expect(lastProcedureInput('user.order.placeOrder').selectedItems).toEqual([
{ skuId: 2, quantity: 1, slotId: 1849 },
])
})
it('CHECK-31: a selected slot of 0 is falsy and excludes the item (current)', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '0:1' },
})
expect(getByTestId('checkout-empty-title')).toHaveTextContent('No items to checkout')
})
/* ------------------------------------------------------------------------ */
/* 14.3 Coupons */
/* ------------------------------------------------------------------------ */
it('CHECK-15: coupon ids in the URL are parsed into state', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21,22' },
})
expect(getByTestId('checkout-coupon-21')).toBeTruthy()
expect(getByTestId('checkout-coupon-22')).toBeTruthy()
})
it('CHECK-16: invalid coupon ids are ignored', async () => {
const { queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: 'abc,999' },
})
expect(queryByTestId('checkout-coupon-section')).toBeNull()
})
it('CHECK-17: duplicate coupon ids are preserved and stacked twice (current)', async () => {
const { getAllByTestId, getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21,21' },
})
expect(getAllByTestId('checkout-coupon-21')).toHaveLength(2)
expect(getByTestId('bill-product-discount-amount')).toHaveTextContent('-₹82')
})
it('CHECK-18: changing the coupon param updates state to the new list', async () => {
const { getByTestId, queryByTestId, rerender } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21' },
})
expect(getByTestId('checkout-coupon-21')).toBeTruthy()
__setParams({ slots: '1849:1', coupons: '22' })
rerender(<Checkout />)
await flush(2)
expect(queryByTestId('checkout-coupon-21')).toBeNull()
expect(getByTestId('checkout-coupon-22')).toBeTruthy()
})
it('CHECK-19: a still-eligible coupon shows its percent/flat label', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21,22' },
})
expect(getByTestId('checkout-coupon-value-21')).toHaveTextContent('10% off')
expect(getByTestId('checkout-coupon-value-22')).toHaveTextContent('₹100 off')
})
it('CHECK-20: a now-ineligible coupon is struck through with its reason', async () => {
const { getByTestId, queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '23' },
})
expect(queryByTestId('checkout-coupon-23')).toBeNull()
const dropped = getByTestId('checkout-coupon-dropped-23')
expect(within(dropped).getByText('MIN1000')).toBeTruthy()
expect(within(dropped).getByText('Not applied')).toBeTruthy()
expect(getByTestId('checkout-coupon-reason-23')).toHaveTextContent(
'Add ₹570 more to use this coupon'
)
})
it('CHECK-21: a targeted coupon shows the info icon and opens a matching breakdown', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '24' },
})
expect(getByTestId('checkout-coupon-value-24')).toHaveTextContent('10% off')
expect(getByTestId('bill-product-discount-amount')).toHaveTextContent('-₹40')
fireEvent.press(getByTestId('coupon-breakdown-24'))
await flush(1)
const dialog = getByTestId('coupon-breakdown-dialog')
expect(dialog).toBeTruthy()
const row = getByTestId('coupon-breakdown-row-2')
expect(within(row).getByText('−₹40')).toBeTruthy()
// The row and the "Total from this coupon" line both show the same ₹40.
expect(within(dialog).getAllByText('−₹40')).toHaveLength(2)
})
it('CHECK-22: the displayed bill matches the shared sequential coupon stack', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21,22' },
})
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹430')
// SAVE10: round(10% of 430) = 43; FLAT100 then takes 100 => 143.
expect(getByTestId('bill-product-discount-amount')).toHaveTextContent('-₹143')
expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹287')
})
it('CHECK-23: a discount that drops the total below the threshold re-adds delivery', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 1, 1849), line(2, 5, 3, 1849)],
params: { slots: '1849:1;1849:2', coupons: '22' },
})
// 215 + 45 = 260, FLAT100 -> 160 < 249, so ₹15 delivery.
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹260')
expect(getByTestId('bill-delivery-amount')).toHaveTextContent('₹15')
expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹175')
})
it('CHECK-24: no coupons means no Coupon section', async () => {
const { queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(queryByTestId('checkout-coupon-section')).toBeNull()
})
it('CHECK-25: the savings banner includes coupon, market savings and free delivery', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21' },
})
// 43 coupon + 10 market savings (2 × ₹5) + ₹15 waived delivery.
expect(getByTestId('bill-savings-text')).toHaveTextContent('You saved ₹68 on this order')
})
it('CHECK-32: coupon stack order changes the total', async () => {
const first = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21,22' },
})
expect(first.getByTestId('bill-to-pay-amount')).toHaveTextContent('₹287')
first.unmount()
const second = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '22,21' },
})
// FLAT100 first (330), then round(10% of 330) = 33 => 133 discount.
expect(second.getByTestId('bill-to-pay-amount')).toHaveTextContent('₹297')
})
/* ------------------------------------------------------------------------ */
/* 14.4 Order hand-off, address gate, header */
/* ------------------------------------------------------------------------ */
it('CHECK-26: place order receives the selected items, coupons and totals', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1', coupons: '21' },
})
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹430')
expect(getByTestId('bill-product-discount-amount')).toHaveTextContent('-₹43')
expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹387')
fireEvent.press(getByTestId('place-order-button'))
await flush(4)
expect(procedureMutationCalls('user.order.placeOrder')).toHaveLength(1)
expect(lastProcedureInput('user.order.placeOrder')).toEqual({
selectedItems: [{ skuId: 2, quantity: 2, slotId: 1849 }],
addressId: A1.id,
regionId: 1,
boundId: CONSTS.boundId,
couponIds: [21],
userNotes: '',
isFlashDelivery: false,
})
})
it('CHECK-27: re-rendering from empty to slotted does not crash on hooks', async () => {
const { getByTestId, rerender } = await mount({
lines: [line(1, 2, 2, 1849)],
params: {},
})
expect(getByTestId('checkout-empty')).toBeTruthy()
__setParams({ slots: '1849:1' })
rerender(<Checkout />)
await flush(3)
expect(getByTestId('checkout-header-title')).toHaveTextContent('Scheduled Delivery Checkout')
expect(getByTestId('checkout-item-1')).toBeTruthy()
})
it('CHECK-33: with no selected address the error banner shows and Place Order is disabled', async () => {
const { getByTestId } = await mount({
addressId: null,
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(getByTestId('select-address-error')).toBeTruthy()
expect(getByTestId('place-order-button')).toBeDisabled()
})
it('CHECK-34: the header title reflects scheduled vs flash checkout', async () => {
const scheduled = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
expect(scheduled.getByTestId('checkout-header-title')).toHaveTextContent(
'Scheduled Delivery Checkout'
)
scheduled.unmount()
const flash = await mount({
flash: true,
lines: [line(1, 8, 1, 0)],
params: {},
})
expect(flash.getByTestId('checkout-header-title')).toHaveTextContent('1 Hr Delivery Checkout')
})
it('CHECK-35: the checkout back button calls router.back', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
params: { slots: '1849:1' },
})
fireEvent.press(getByTestId('checkout-header-back'))
expect(router.back).toHaveBeenCalled()
})
})