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

1452 lines
60 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 — Scheduled Delivery Cart
* (`tests/pages/cart.test.tsx`, CART-01..CART-110).
*
* The real `CartPage` runs (both the regular route
* `app/(drawer)/(tabs)/home/cart.tsx` and the flash route
* `app/(drawer)/(tabs)/flash-delivery/(cart)/cart.tsx`). Only the tRPC
* procedure registry, the CDN JSON docs and the native modules are mocked.
*
* Cart lines live in the secure-store mock (`cart_items` / `flash_cart_items`);
* central product/slot stores and the region are seeded by `seedBoot()`.
* `computeCouponStack` / `computeCouponLineBreakdowns` / `evaluateCouponEligibility`
* stay REAL (imported by the page from `@packages/shared`).
*
* Rows marked "(current)" pin behaviour that differs from the catalogue's wording
* or is unreachable from the rendered UI; they say so in a comment.
*/
import * as React from 'react'
import { Alert, DeviceEventEmitter } from 'react-native'
import { QueryClient } from '@tanstack/react-query'
import { act, fireEvent, within } from '@testing-library/react-native'
import { StorageServiceCasual } from 'common-ui'
import Cart from '@/app/(drawer)/(tabs)/home/cart'
import FlashCart from '@/app/(drawer)/(tabs)/flash-delivery/(cart)/cart'
import AddressForm from '@/src/components/AddressForm'
import constants from '@/src/constants'
import { useAddressStore } from '@/src/store/addressStore'
import { useCheckoutStore } from '@/src/store/checkoutStore'
import { useRegionStore } from '@/src/store/regionStore'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import {
renderWithProviders,
seedBoot,
seedCentralStores,
seedJsonCache,
seedSelectedAddress,
flush,
} from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
procedureMutationCalls,
procedureQueryCalls,
setProcedure,
} from '../mocks/trpc-client'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import { router } from '../mocks/expo-router-mock'
import {
A1,
A2,
C1,
C2,
C3,
C4,
C5,
C6,
C8,
CART_SLOTS_RESPONSE,
MERGED_PRODUCTS,
REGION_1,
SLOTS,
} from '../fixtures'
const CART_KEY = 'cart_items'
const FLASH_KEY = 'flash_cart_items'
const REFRESH_EVENT = 'refresh_event'
/** The Unicode minus sign the bill's coupon breakdown uses. */
const MINUS = '\u2212'
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))
}
function storedLines(key = CART_KEY): any[] {
const raw = __snapshot()[key]
return raw ? JSON.parse(raw) : []
}
/** 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 ''
}
interface MountOptions {
lines?: any[] | null
key?: string
flash?: boolean
auth?: 'in' | 'out'
flushTimes?: number
setup?: () => void
}
/** Mutation GC off so a finished cart mutation never keeps the jest process alive. */
function createClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: Infinity,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false, gcTime: 0 },
},
})
}
/** Seed the standard boot state + cart lines and render the page (or flash cart). */
async function mount(opts: MountOptions = {}) {
seedBoot()
opts.setup?.()
if (opts.lines) {
seedCart(opts.lines, opts.key ?? (opts.flash ? FLASH_KEY : CART_KEY))
}
const ui = opts.flash ? <FlashCart /> : <Cart />
const result = renderWithProviders(ui, { auth: opts.auth ?? 'in', queryClient: createClient() })
await flush(opts.flushTimes ?? 4)
return result
}
function spyAlert() {
return jest.spyOn(Alert, 'alert').mockImplementation(() => {})
}
/** Invoke one button of the last Alert.alert(...) call, then settle. */
async function tapAlert(alertSpy: jest.SpyInstance, text: string) {
const call = alertSpy.mock.calls[alertSpy.mock.calls.length - 1]
const buttons = (call?.[2] ?? []) as any[]
const button = buttons.find((entry) => entry.text === text)
expect(button).toBeTruthy()
await act(async () => {
button?.onPress?.()
})
await flush(4)
}
/** Open the coupon multi-select and toggle one coupon option. */
async function pickCoupon(getByTestId: any, id: number) {
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
fireEvent.press(getByTestId(`coupon-dropdown-option-${id}`))
await flush(2)
}
/** Open one item's delivery-slot dropdown and choose a slot. */
async function pickSlot(getByTestId: any, itemId: number, slotId: number) {
fireEvent.press(getByTestId(`cart-item-slot-${itemId}`))
await flush(1)
fireEvent.press(getByTestId(`slot-dropdown-${itemId}-option-${slotId}`))
await flush(2)
}
/**
* Replace the cart-slots response and refetch, like a background data refresh.
* (The real slots query only re-reads the registry on a refetch.)
*/
async function refreshWithSlots(data: any) {
await act(async () => {
setProcedure('user.cart.getCartSlots', { data })
DeviceEventEmitter.emit(REFRESH_EVENT)
})
await flush(4)
}
/**
* Mount with no region (the slots query disabled), let auth/addresses settle,
* then enable the region so the slots query starts its *first* fetch — which is
* what `isLoading` (and therefore the "Loading cart..." gate) observes.
*/
async function enableRegionAfterMount(ui: React.ReactElement, auth: 'in' | 'out' = 'in') {
const result = renderWithProviders(ui, { auth, queryClient: createClient() })
await flush(4)
await act(async () => {
useRegionStore.getState().setRegion(REGION_1 as any, 7)
})
await flush(4)
return result
}
describe('Cart (scheduled) — CART-01..110', () => {
beforeEach(() => resetAllMocks())
/* ------------------------------------------------------------------------ */
/* 13.1 Gates, states and header */
/* ------------------------------------------------------------------------ */
it('CART-01: auth loading shows "Loading..."', () => {
seedBoot()
const { getByText } = renderWithProviders(<Cart />, { auth: 'in' })
expect(getByText('Loading...')).toBeTruthy()
})
it('CART-02: signed out shows the login wall and hides cart lines', async () => {
seedBoot()
seedCart([line(1, 2, 2, 1849)])
const { getByTestId, getByText, queryByText } = renderWithProviders(<Cart />, {
auth: 'out',
})
await flush(3)
expect(getByTestId('login-wall')).toBeTruthy()
expect(getByText('Log in to view your cart and continue to checkout.')).toBeTruthy()
expect(queryByText('Chicken Breast')).toBeNull()
})
it('CART-03: the login wall Log In stores the redirect and pushes login', async () => {
seedBoot()
const { getByTestId } = renderWithProviders(<Cart />, { auth: 'out' })
await flush(3)
fireEvent.press(getByTestId('login-wall-login'))
await flush(2)
expect(router.push).toHaveBeenCalledWith('/(auth)/login')
const stored = __snapshot()[constants.AUTH_REDIRECT_KEY]
expect(stored).toBeTruthy()
expect(JSON.parse(stored).targetUrl).toBeTruthy()
})
it('CART-04: the login wall Go Back calls router.back', async () => {
seedBoot()
const { getByTestId } = renderWithProviders(<Cart />, { auth: 'out' })
await flush(3)
fireEvent.press(getByTestId('login-wall-back'))
expect(router.back).toHaveBeenCalled()
})
it('CART-05: a pending cart query shows "Loading cart..."', async () => {
const original = StorageServiceCasual.getItem
const spy = jest
.spyOn(StorageServiceCasual, 'getItem')
.mockImplementation((key: string) =>
key === CART_KEY ? new Promise<string>(() => {}) : original(key)
)
seedBoot()
const { getByText } = renderWithProviders(<Cart />, { auth: 'in' })
await flush(3)
expect(getByText('Loading cart...')).toBeTruthy()
spy.mockRestore()
})
it('CART-06: pending slots in a regular cart still show "Loading cart..."', async () => {
// Keep the region unset on mount so the slots query is disabled while auth
// and the addresses settle; the harness hangs a whole batch when one
// procedure is pending, which would otherwise block those queries too.
configureLocation({ permission: 'denied', position: null })
seedJsonCache()
seedCentralStores()
seedSelectedAddress(A1.id)
seedCart([line(1, 2, 2, 1849)])
setProcedure('user.cart.getCartSlots', { mode: 'pending' })
const { getByText } = await enableRegionAfterMount(<Cart />)
expect(getByText('Loading cart...')).toBeTruthy()
})
it('CART-08: a failing cart query shows "Failed to load your cart" with no retry', async () => {
seedBoot()
__set(CART_KEY, '{not json')
const { getByText, queryByText } = renderWithProviders(<Cart />, { auth: 'in' })
await flush(3)
expect(getByText('Failed to load your cart')).toBeTruthy()
expect(queryByText('Retry')).toBeNull()
})
it('CART-10: no addresses show the CartAddressGate even when the cart is empty', async () => {
seedBoot()
setProcedure('user.address.getUserAddresses', { data: { data: [] } })
const { getByTestId, getByText, queryByText } = renderWithProviders(<Cart />, {
auth: 'in',
})
await flush(4)
expect(getByTestId('cart-address-gate-back')).toBeTruthy()
expect(getByText('Where should we deliver?')).toBeTruthy()
expect(queryByText('Your cart is empty')).toBeNull()
})
it('CART-11: finishing the gate refetches addresses and closes the gate', async () => {
seedBoot()
setProcedure('user.address.getUserAddresses', { data: { data: [] } })
const { getByTestId, UNSAFE_getByType, UNSAFE_queryByType } = renderWithProviders(<Cart />, {
auth: 'in',
})
await flush(4)
fireEvent.press(getByTestId('cart-address-other'))
await flush(2)
expect(UNSAFE_getByType(AddressForm)).toBeTruthy()
// The gate wires onSuccess -> onDone -> addressesQuery.refetch(); the refetch
// is a mock jest.fn with no other observable effect, so we pin that the gate
// closes cleanly after the first address is saved.
await act(async () => {
UNSAFE_getByType(AddressForm).props.onSuccess()
})
await flush(2)
expect(UNSAFE_queryByType(AddressForm)).toBeNull()
})
it('CART-12: the gate back button calls router.back', async () => {
seedBoot()
setProcedure('user.address.getUserAddresses', { data: { data: [] } })
const { getByTestId } = renderWithProviders(<Cart />, { auth: 'in' })
await flush(4)
fireEvent.press(getByTestId('cart-address-gate-back'))
expect(router.back).toHaveBeenCalled()
})
it('CART-13: with no region the slots query stays disabled but the address gate still applies', async () => {
// Keep the region null: no location fix and no default address.
configureLocation({ permission: 'denied', position: null })
seedJsonCache()
seedCentralStores()
seedSelectedAddress(null)
setProcedure('user.address.getDefaultAddress', { data: { data: null } })
setProcedure('user.address.getUserAddresses', { data: { data: [] } })
const { getByText } = renderWithProviders(<Cart />, { auth: 'in' })
await flush(4)
expect(getByText('Where should we deliver?')).toBeTruthy()
expect(procedureQueryCalls('user.cart.getCartSlots')).toHaveLength(0)
})
it('CART-14: header shows "Scheduled Delivery Cart" and a back button', async () => {
const { getByText, getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
expect(getByText('Scheduled Delivery Cart')).toBeTruthy()
fireEvent.press(getByTestId('cart-header-back'))
expect(router.back).toHaveBeenCalled()
})
it('CART-15: an empty cart shows "Your cart is empty" and Start Shopping → home', async () => {
const { getByText, getByTestId } = await mount({ lines: [] })
expect(getByText('Your cart is empty')).toBeTruthy()
fireEvent.press(getByTestId('cart-start-shopping'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
})
it('CART-16: all lines out of stock still lists them but hides coupons/bill/checkout', async () => {
const { getByText, queryByText, queryByTestId } = await mount({ lines: [line(1, 6, 1, 1849)] })
expect(getByText('Mutton')).toBeTruthy()
expect(getByText('Out of Stock')).toBeTruthy()
expect(queryByText('Offers & Coupons')).toBeNull()
expect(queryByText('Bill Details')).toBeNull()
expect(queryByTestId('checkout-button')).toBeNull()
})
it('CART-17: the flash cart shows "1 Hr Delivery Cart" and flash prices', async () => {
const { getByText, getAllByText } = await mount({
flash: true,
lines: [line(1, 8, 1, 0)],
})
expect(getByText('1 Hr Delivery Cart')).toBeTruthy()
// Paneer flashPrice 75 (not the regular 90).
expect(getAllByText('₹75').length).toBeGreaterThan(0)
})
/* ------------------------------------------------------------------------ */
/* 13.2 Cart lines, quantities and removal */
/* ------------------------------------------------------------------------ */
it('CART-18: a seeded line shows name, unit, quantity and price', async () => {
const { getByText, getByTestId, getAllByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
expect(getByText('Chicken Breast')).toBeTruthy()
expect(getByText('500g')).toBeTruthy()
expect(getByTestId('cart-item-1-value')).toHaveTextContent('2')
expect(getAllByText('₹430').length).toBeGreaterThan(0)
})
it('CART-19: tapping the image or name opens the product-detail route', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('cart-item-name-1'))
fireEvent.press(getByTestId('cart-item-image-1'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/product-detail/2')
expect(router.push).toHaveBeenCalledTimes(2)
})
it('CART-20: incrementing updates storage and the local quantity/price', async () => {
const { getByTestId, getAllByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('cart-item-1-increment'))
await flush(3)
expect(getByTestId('cart-item-1-value')).toHaveTextContent('3')
expect(storedLines()[0].quantity).toBe(3)
expect(getAllByText('₹645').length).toBeGreaterThan(0)
})
it('CART-21: decrementing to 0 opens the Remove Item alert; Cancel restores 1', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('cart-item-1-decrement'))
await flush(1)
fireEvent.press(getByTestId('cart-item-1-decrement'))
await flush(1)
expect(alertSpy.mock.calls[0][0]).toBe('Remove Item')
await tapAlert(alertSpy, 'Cancel')
expect(getByTestId('cart-item-1-value')).toHaveTextContent('1')
alertSpy.mockRestore()
})
it('CART-22: confirming Remove removes the line from storage and the cart', async () => {
const alertSpy = spyAlert()
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('cart-item-1-decrement'))
await flush(1)
fireEvent.press(getByTestId('cart-item-1-decrement'))
await flush(1)
await tapAlert(alertSpy, 'Remove')
expect(storedLines()).toEqual([])
expect(getByText('Your cart is empty')).toBeTruthy()
alertSpy.mockRestore()
})
it('CART-23: a rejected remove alerts an error and restores quantity 1', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('cart-item-1-decrement'))
await flush(1)
fireEvent.press(getByTestId('cart-item-1-decrement'))
await flush(1)
const setItemSpy = jest
.spyOn(StorageServiceCasual, 'setItem')
.mockRejectedValueOnce(new Error('boom'))
await tapAlert(alertSpy, 'Remove')
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
expect(getByTestId('cart-item-1-value')).toHaveTextContent('1')
expect(storedLines()).toHaveLength(1)
setItemSpy.mockRestore()
alertSpy.mockRestore()
})
it('CART-24: the delete icon asks for confirmation then removes the line', async () => {
const alertSpy = spyAlert()
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('cart-item-delete-1'))
expect(alertSpy.mock.calls[0][0]).toBe('Remove Item')
expect(alertSpy.mock.calls[0][1]).toBe('Remove Chicken Breast from cart?')
await tapAlert(alertSpy, 'Remove')
expect(storedLines()).toEqual([])
expect(getByText('Your cart is empty')).toBeTruthy()
alertSpy.mockRestore()
})
it('CART-25: a rejected delete-icon remove alerts an error', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
const setItemSpy = jest
.spyOn(StorageServiceCasual, 'setItem')
.mockRejectedValueOnce(new Error('remove failed'))
fireEvent.press(getByTestId('cart-item-delete-1'))
await tapAlert(alertSpy, 'Remove')
expect(alertSpy).toHaveBeenCalledWith('Error', 'remove failed')
setItemSpy.mockRestore()
alertSpy.mockRestore()
})
it('CART-26: an out-of-stock line gets a badge and no price contribution', async () => {
const { getByText, queryByText, getAllByText } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 6, 1, 1850)],
})
expect(getByText('Out of Stock')).toBeTruthy()
// Item Total is only the in-stock chicken (2 x 215); the mutton is ignored.
expect(getAllByText('₹430').length).toBeGreaterThan(0)
expect(queryByText('₹830')).toBeNull()
})
it('CART-27: a flash-ineligible line in a flash cart shows the flash message', async () => {
const { getByText } = await mount({ flash: true, lines: [line(1, 2, 1, 0)] })
expect(getByText('Not available for flash delivery. Please remove')).toBeTruthy()
})
it('CART-28: a line with no slots shows the copy and a disabled dropdown', async () => {
const { getAllByText, getByTestId } = await mount({ lines: [line(1, 9, 1, 0)] })
expect(getAllByText('No delivery slots available').length).toBeGreaterThan(0)
expect(getByTestId('cart-item-slot-1')).toBeDisabled()
})
it('CART-29: a stale selected slot blocks checkout with the unavailable message', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
// Refresh the slots doc so the selected slot is gone and no future one exists.
await refreshWithSlots({ 2: [SLOTS[2]] })
expect(getByTestId('checkout-button')).toBeDisabled()
expect(
getByText(
'Some items in your cart are no longer available for delivery. Please remove them to continue.'
)
).toBeTruthy()
})
it('CART-30: a selected slot whose freeze time passed blocks with the closed message', async () => {
const frozen = {
id: 9001,
deliveryTime: new Date(Date.now() + 2 * 3600_000).toISOString(),
freezeTime: new Date(Date.now() - 3600_000).toISOString(),
products: [{ id: 2, images: ['chicken.jpg'] }],
}
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 9001)],
setup: () => setProcedure('user.cart.getCartSlots', { data: { 2: [frozen] } }),
})
expect(getByTestId('checkout-button')).toBeDisabled()
expect(
getByText(
'The delivery slot for some items has closed. Please pick a new slot to continue.'
)
).toBeTruthy()
})
it('CART-31: a selected slot no longer offered shows the same unavailable message', async () => {
// Current behaviour: the "unavailable" branch shares one message with the
// "no slots" branch, so CART-29/31/32 are indistinguishable in the UI.
const { getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
await refreshWithSlots({ 2: [SLOTS[2]] })
expect(
getByText(
'Some items in your cart are no longer available for delivery. Please remove them to continue.'
)
).toBeTruthy()
})
it('CART-32: a SKU with no slots published shows the no-slots/unavailable message', async () => {
const { getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () => setProcedure('user.cart.getCartSlots', { data: {} }),
})
expect(
getByText(
'Some items in your cart are no longer available for delivery. Please remove them to continue.'
)
).toBeTruthy()
})
it('CART-33: a combo line hides the unit suffix', async () => {
const { getByText, queryByText } = await mount({ lines: [line(1, 150, 1, 0)] })
expect(getByText('Family Combo')).toBeTruthy()
expect(queryByText('1 combo')).toBeNull()
})
it('CART-34: a line whose product is missing from the central store is hidden (no crash)', async () => {
const { getByText } = await mount({ lines: [line(1, 999, 1, 1849)] })
expect(getByText('Your cart is empty')).toBeTruthy()
})
it('CART-35: a zero-quantity persisted line renders with quantity and price 0 (current)', async () => {
// Current behaviour: useGetCart keeps a zero-quantity line; the page shows 0.
const { getByTestId, getAllByText } = await mount({ lines: [line(1, 2, 0, 1849)] })
expect(getByTestId('cart-item-1-value')).toHaveTextContent('0')
expect(getAllByText('₹0').length).toBeGreaterThan(0)
})
/* ------------------------------------------------------------------------ */
/* 13.3 Slot selection and summary */
/* ------------------------------------------------------------------------ */
it('CART-36: the earliest future slot is auto-selected on load', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
expect(getByTestId('delivery-slot-items-1849')).toBeTruthy()
expect(getByText('1 item')).toBeTruthy()
})
it('CART-37: a stored slot that is still valid is kept', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1850)] })
expect(getByTestId('delivery-slot-items-1850')).toBeTruthy()
})
it('CART-38: an invalid stored slot is replaced with the earliest future slot', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 9999)] })
expect(getByTestId('delivery-slot-items-1849')).toBeTruthy()
})
it('CART-39: a past stored slot is replaced with the earliest future slot', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1851)] })
expect(getByTestId('delivery-slot-items-1849')).toBeTruthy()
})
it('CART-40: a product with no future slots gets no selection and a disabled dropdown', async () => {
const { getAllByText, getByTestId, queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () => setProcedure('user.cart.getCartSlots', { data: { 2: [SLOTS[2]] } }),
})
expect(getAllByText('No delivery slots available').length).toBeGreaterThan(0)
expect(getByTestId('cart-item-slot-1')).toBeDisabled()
expect(queryByTestId('delivery-slot-summary')).toBeNull()
})
it('CART-41: the dropdown lists only future slots, labels include the close time', async () => {
const at = (hour: number, id: number, offsetDays: number) => {
const date = new Date()
date.setDate(date.getDate() + offsetDays)
date.setHours(hour, 0, 0, 0)
return {
id,
deliveryTime: date.toISOString(),
freezeTime: new Date(date.getTime() - 3600_000).toISOString(),
products: [{ id: 2, images: ['chicken.jpg'] }],
}
}
// Times are chosen so the delivery range stays within one AM/PM period,
// otherwise the dropdown's `split(' - ')` label truncates the close time.
const morning = at(10, 7001, 1)
const afternoon = at(14, 7002, 1)
const past = at(0, 7003, -1)
const { getByTestId, queryByTestId } = await mount({
lines: [line(1, 2, 2, 7001)],
setup: () =>
setProcedure('user.cart.getCartSlots', { data: { 2: [morning, afternoon, past] } }),
})
fireEvent.press(getByTestId('cart-item-slot-1'))
await flush(1)
expect(getByTestId('slot-dropdown-1-option-7001')).toBeTruthy()
expect(getByTestId('slot-dropdown-1-option-7002')).toBeTruthy()
expect(queryByTestId('slot-dropdown-1-option-7003')).toBeNull()
expect(textOf(getByTestId('slot-dropdown-1-option-7001'))).toContain('Close time:')
})
it('CART-42: changing a slot updates the selection and the summary', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickSlot(getByTestId, 1, 1852)
expect(getByTestId('delivery-slot-items-1852')).toBeTruthy()
})
it('CART-43: summary shows one row per slot with correct item counts', async () => {
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 5, 1, 1849), line(3, 8, 1, 1852)],
})
expect(getByTestId('delivery-slot-items-1849')).toBeTruthy()
expect(getByTestId('delivery-slot-items-1852')).toBeTruthy()
expect(getByText('2 items')).toBeTruthy()
expect(getByText('1 item')).toBeTruthy()
})
it('CART-44: the group details dialog lists items and quantities, then closes', async () => {
const { getByTestId, getByText, queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 5, 1, 1849)],
})
fireEvent.press(getByTestId('delivery-slot-items-1849'))
await flush(1)
const dialog = getByTestId('delivery-slot-group-dialog')
expect(within(dialog).getByText('Chicken Breast')).toBeTruthy()
expect(within(dialog).getByText('Cucumber')).toBeTruthy()
expect(within(dialog).getByText('x2')).toBeTruthy()
expect(within(dialog).getByText('x1')).toBeTruthy()
fireEvent.press(getByTestId('delivery-slot-group-close'))
await flush(1)
expect(queryByTestId('delivery-slot-group-dialog')).toBeNull()
})
it('CART-45: merge is suggested only when every in-stock item supports the majority slot', async () => {
// Majority is 1849 (2 items) but Paneer (sku 8) cannot deliver at 1849.
const { queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 5, 1, 1849), line(3, 8, 1, 1852)],
})
expect(queryByTestId('delivery-slot-merge')).toBeNull()
})
it('CART-46: a tie for majority keeps the lowest slot id', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 1, 1849), line(2, 5, 1, 1849), line(3, 2, 1, 1852), line(4, 5, 1, 1852)],
})
fireEvent.press(getByTestId('delivery-slot-merge'))
await flush(2)
expect(getByTestId('delivery-slot-items-1849')).toBeTruthy()
expect(textOf(getByTestId('delivery-slot-items-1849'))).toContain('4 items')
})
it('CART-47: with a single group there is no merge suggestion', async () => {
const { queryByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
expect(queryByTestId('delivery-slot-merge')).toBeNull()
})
it('CART-48: the flash cart shows no slot summary', async () => {
const { queryByTestId } = await mount({ flash: true, lines: [line(1, 8, 1, 0)] })
expect(queryByTestId('delivery-slot-summary')).toBeNull()
})
it('CART-49: applying the merge moves all in-stock lines to the majority slot', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 1, 1852), line(2, 5, 1, 1852), line(3, 8, 1, 1850)],
})
expect(getByTestId('delivery-slot-merge')).toBeTruthy()
fireEvent.press(getByTestId('delivery-slot-merge'))
await flush(2)
expect(getByTestId('delivery-slot-items-1852')).toBeTruthy()
expect(textOf(getByTestId('delivery-slot-items-1852'))).toContain('3 items')
})
it('CART-50: an out-of-stock line keeps its slot during a merge', async () => {
const customSlots = { ...CART_SLOTS_RESPONSE, 6: [SLOTS[0]] }
const { getByTestId } = await mount({
lines: [
line(1, 2, 1, 1852),
line(2, 5, 1, 1852),
line(3, 8, 1, 1850),
line(4, 6, 1, 1849),
],
setup: () => setProcedure('user.cart.getCartSlots', { data: customSlots }),
})
fireEvent.press(getByTestId('delivery-slot-merge'))
await flush(2)
expect(textOf(getByTestId('delivery-slot-items-1852'))).toContain('3 items')
// The out-of-stock mutton keeps its old 1849 slot and is not merged.
expect(getByTestId('delivery-slot-items-1849')).toBeTruthy()
expect(textOf(getByTestId('delivery-slot-items-1849'))).toContain('1 item')
})
it('CART-51: a slot that closes after a data refresh blocks checkout', async () => {
const frozen = {
id: 1849,
deliveryTime: new Date(Date.now() + 2 * 3600_000).toISOString(),
freezeTime: new Date(Date.now() - 3600_000).toISOString(),
products: [{ id: 2, images: ['chicken.jpg'] }],
}
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
await refreshWithSlots({ 2: [frozen] })
expect(getByTestId('checkout-button')).toBeDisabled()
})
/* ------------------------------------------------------------------------ */
/* 13.4 Bill, coupons and savings */
/* ------------------------------------------------------------------------ */
it('CART-52: no coupon, total over the threshold shows Free delivery and savings', async () => {
const { getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
expect(getByText('Item Total')).toBeTruthy()
expect(getByText('Free')).toBeTruthy()
expect(getByText('To Pay')).toBeTruthy()
expect(getByText('You saved ₹25 on this order')).toBeTruthy()
})
it('CART-53: below the threshold adds delivery and an exact-remaining nudge', async () => {
const { getByText, getAllByText } = await mount({ lines: [line(1, 5, 1, 1849)] })
expect(getAllByText('₹15').length).toBeGreaterThan(0)
expect(getByText('Add products worth ₹234 for free delivery')).toBeTruthy()
})
it('CART-54: the Products discount row only appears when savings exceed ₹1 (current)', async () => {
// A saving of exactly ₹1 is hidden (the guard is `> 1`).
const oneSaving = MERGED_PRODUCTS.map((product) =>
product.id === 9 ? { ...product, price: 10, marketPrice: 11 } : product
)
const first = await mount({
lines: [line(1, 9, 1, 0)],
setup: () => seedCentralStores({ products: oneSaving }),
})
expect(first.queryByText('Products discount')).toBeNull()
first.unmount()
const twoSaving = MERGED_PRODUCTS.map((product) =>
product.id === 9 ? { ...product, price: 10, marketPrice: 12 } : product
)
const second = await mount({
lines: [line(1, 9, 1, 0)],
setup: () => seedCentralStores({ products: twoSaving }),
})
expect(second.getByText('Products discount')).toBeTruthy()
})
it('CART-55: a market price below the price yields no negative savings', async () => {
const cheaperMarket = MERGED_PRODUCTS.map((product) =>
product.id === 9 ? { ...product, price: 50, marketPrice: 40 } : product
)
const { queryByText } = await mount({
lines: [line(1, 9, 1, 0)],
setup: () => seedCentralStores({ products: cheaperMarket }),
})
expect(queryByText('Products discount')).toBeNull()
})
it('CART-56: changing the quantity updates the line and the bill', async () => {
const { getByTestId, getAllByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('cart-item-1-increment'))
await flush(3)
expect(getByTestId('cart-item-1-value')).toHaveTextContent('3')
expect(getAllByText('₹645').length).toBeGreaterThan(0)
})
it('CART-57: an out-of-stock line is excluded from the bill totals', async () => {
const { getByText, queryByText, getAllByText } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 6, 1, 1850)],
})
expect(getAllByText('₹430').length).toBeGreaterThan(0)
expect(queryByText('₹830')).toBeNull()
expect(getByText('To Pay')).toBeTruthy()
})
it('CART-58: the coupon query runs only when authenticated and shows Offers & Coupons', async () => {
const { getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
expect(getByText('Offers & Coupons')).toBeTruthy()
expect(procedureQueryCalls('user.coupon.getEligible').length).toBeGreaterThan(0)
})
it('CART-59: with no coupons the dropdown and helper copy say so', async () => {
const { getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () => setProcedure('user.coupon.getEligible', { data: { data: [], isFirstOrder: true } }),
})
expect(getByText('No coupons available')).toBeTruthy()
expect(getByText('No coupons available for this order')).toBeTruthy()
})
it('CART-60: a percent coupon shows Save ₹43, a discount row and To Pay', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
expect(getByText('-₹43')).toBeTruthy()
expect(getByText('₹387')).toBeTruthy()
})
it('CART-61: a percent coupon is capped at maxValue', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 10, 1849)] })
await pickCoupon(getByTestId, 21)
expect(getByText('-₹50')).toBeTruthy()
})
it('CART-62: a flat coupon shows a discount row', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 22)
expect(getByText('-₹100')).toBeTruthy()
})
it('CART-63: a flat coupon is capped at the item total and never goes negative', async () => {
const { getByTestId, getByText, getAllByText } = await mount({ lines: [line(1, 5, 1, 1849)] })
await pickCoupon(getByTestId, 22)
expect(getByText('-₹15')).toBeTruthy()
expect(getAllByText('₹15').length).toBeGreaterThan(0)
})
it('CART-64: a discount that drops the total below the threshold re-adds delivery', async () => {
const bigFlat = { ...C2, id: 99, couponCode: 'FLAT200', flatDiscount: 200 }
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', {
data: { data: [bigFlat], isFirstOrder: true },
}),
})
await pickCoupon(getByTestId, 99)
expect(getByText('₹15')).toBeTruthy()
})
it('CART-65: a coupon below minOrder is disabled with the reason and cannot be selected', async () => {
const { getByTestId, getByText, queryByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(getByTestId('coupon-dropdown-option-23')).toBeDisabled()
expect(getByText('Add ₹570 more to use this coupon')).toBeTruthy()
fireEvent.press(getByTestId('coupon-dropdown-option-23'))
await flush(1)
expect(queryByTestId('coupon-chip-MIN1000')).toBeNull()
})
it('CART-65B: a targeted coupon allows minOrder on the whole cart but discounts only its SKU', async () => {
const targeted = {
...C3,
id: 65,
couponCode: 'TGT65',
minOrder: 500,
flatDiscount: 50,
skuIds: [2],
}
const { getByTestId, getByText } = await mount({
// Chicken (targeted) is ₹215, cucumber (other) is ₹300 -> cart ₹515.
lines: [line(1, 2, 1, 1849), line(2, 5, 20, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', {
data: { data: [targeted], isFirstOrder: true },
}),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
// ₹215 of eligible product is below ₹500, but the cart is ₹515.
expect(getByTestId('coupon-dropdown-option-65')).not.toBeDisabled()
fireEvent.press(getByTestId('coupon-dropdown-option-65'))
await flush(2)
expect(getByTestId('coupon-bill-65')).toBeTruthy()
expect(getByText('-₹50')).toBeTruthy()
})
it('CART-66: a coupon at its usage limit is disabled', async () => {
const used = { ...C6, usages: [{ id: 1 }], maxLimitForUser: 1 }
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [used], isFirstOrder: true } }),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(getByTestId('coupon-dropdown-option-26')).toBeDisabled()
expect(getByText('Usage limit exceeded')).toBeTruthy()
})
it('CART-67: a coupon from another region is disabled with the reason', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(getByTestId('coupon-dropdown-option-27')).toBeDisabled()
expect(getByText('Not valid in your region')).toBeTruthy()
})
it('CART-68: a first-order-only coupon on a non-first order is disabled', async () => {
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', {
data: { data: [{ ...C8, isFirstOrderOnly: true }], isFirstOrder: false },
}),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(getByTestId('coupon-dropdown-option-28')).toBeDisabled()
expect(getByText('Valid on your first order only')).toBeTruthy()
})
it('CART-69: targeted coupon rows are unique by product name and match the count', async () => {
const targeted = { ...C4, id: 69, couponCode: 'TGT', skuIds: [2, 5, 2] }
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 5, 1, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [targeted], isFirstOrder: true } }),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(getByText('Applies to 2 products')).toBeTruthy()
fireEvent.press(getByTestId('coupon-dropdown-option-69-detail'))
await flush(1)
const list = getByTestId('coupon-dropdown-option-69-detail-list')
expect(within(list).getAllByText(/Chicken Breast|Cucumber/)).toHaveLength(2)
})
it('CART-70: a target SKU missing from the catalogue shows the unavailable row', async () => {
const targeted = { ...C4, id: 70, couponCode: 'MISS', skuIds: [999] }
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [targeted], isFirstOrder: true } }),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(getByText('Applies to 1 product')).toBeTruthy()
fireEvent.press(getByTestId('coupon-dropdown-option-70-detail'))
await flush(1)
expect(getByText('Product unavailable · #999')).toBeTruthy()
})
it('CART-71: a coupon with both percent and flat shows the percent (current)', async () => {
// Current behaviour: the description and discount type prefer discountPercent.
const both = { ...C4, id: 71, couponCode: 'BOTH', discountPercent: '10', maxValue: null, flatDiscount: 100, skuIds: [] }
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [both], isFirstOrder: true } }),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
const option = textOf(getByTestId('coupon-dropdown-option-71'))
expect(option).toContain('10% off')
expect(option).not.toContain('₹100 off')
fireEvent.press(getByTestId('coupon-dropdown-option-71'))
await flush(1)
fireEvent.press(getByTestId('coupon-bill-71'))
await flush(1)
expect(getByText('10% OFF')).toBeTruthy()
})
it('CART-72: the description combines percent/flat with min and max copy', async () => {
const described = { ...C1, id: 72, couponCode: 'DESC', minOrder: 100, maxValue: 50 }
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [described], isFirstOrder: true } }),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(textOf(getByTestId('coupon-dropdown-option-72'))).toContain(
'10% off on orders above ₹100 (max discount ₹50)'
)
})
it('CART-73: the Save preview is the marginal saving on the current selection', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(textOf(getByTestId('coupon-dropdown-option-24'))).toContain('Save ₹40')
fireEvent.press(getByTestId('coupon-dropdown-option-21'))
await flush(2)
expect(textOf(getByTestId('coupon-dropdown-option-24'))).toContain('Save ₹39')
})
it('CART-74: an already-selected coupon shows its current contribution', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
expect(textOf(getByTestId('coupon-dropdown-option-21'))).toContain('Save ₹43')
})
it('CART-75: multiple coupons stack in selection order', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
await pickCoupon(getByTestId, 22)
expect(getByText('-₹43')).toBeTruthy()
expect(getByText('-₹100')).toBeTruthy()
expect(getByText('₹287')).toBeTruthy()
})
it('CART-76: removing one coupon keeps the others and recomputes the discount', async () => {
const { getByTestId, getByText, queryByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
await pickCoupon(getByTestId, 22)
fireEvent.press(getByTestId('coupon-chip-remove-SAVE10'))
await flush(2)
expect(queryByText('-₹43')).toBeNull()
expect(getByText('-₹100')).toBeTruthy()
expect(getByTestId('coupon-chip-FLAT100')).toBeTruthy()
})
it('CART-77: removing all coupons clears the discount rows', async () => {
const { getByTestId, queryByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
await pickCoupon(getByTestId, 22)
fireEvent.press(getByTestId('remove-coupons'))
await flush(2)
expect(queryByText('-₹43')).toBeNull()
expect(queryByText('-₹100')).toBeNull()
expect(queryByText('Remove coupons')).toBeNull()
})
it('CART-78: selecting an exclusive coupon replaces every previous selection', async () => {
const exclusive = { ...C5, exclusiveApply: true }
const { getByTestId, queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', {
data: { data: [C1, exclusive], isFirstOrder: true },
}),
})
await pickCoupon(getByTestId, 21)
await pickCoupon(getByTestId, 25)
expect(queryByTestId('coupon-chip-SAVE10')).toBeNull()
expect(getByTestId('coupon-chip-EXCLUSIVE')).toBeTruthy()
})
it('CART-79: adding a normal coupon after an exclusive replaces the exclusive', async () => {
const exclusive = { ...C5, exclusiveApply: true }
const { getByTestId, queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', {
data: { data: [C1, exclusive], isFirstOrder: true },
}),
})
await pickCoupon(getByTestId, 25)
expect(getByTestId('coupon-chip-EXCLUSIVE')).toBeTruthy()
await pickCoupon(getByTestId, 21)
expect(queryByTestId('coupon-chip-EXCLUSIVE')).toBeNull()
expect(getByTestId('coupon-chip-SAVE10')).toBeTruthy()
})
it('CART-80: deselecting a coupon does not trigger exclusive replacement', async () => {
const { getByTestId, queryByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
await pickCoupon(getByTestId, 22)
fireEvent.press(getByTestId('coupon-chip-remove-FLAT100'))
await flush(2)
expect(queryByTestId('coupon-chip-FLAT100')).toBeNull()
expect(getByTestId('coupon-chip-SAVE10')).toBeTruthy()
})
it('CART-81: a quantity drop that makes a coupon ineligible keeps the chip but drops the discount (current)', async () => {
const min400 = { ...C3, id: 81, couponCode: 'MIN400', minOrder: 400, flatDiscount: 50 }
const { getByTestId, queryByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', {
data: { data: [min400], isFirstOrder: true },
}),
})
await pickCoupon(getByTestId, 81)
expect(getByTestId('coupon-bill-81')).toBeTruthy()
fireEvent.press(getByTestId('cart-item-1-decrement'))
await flush(3)
// Current behaviour: the chip stays (it is keyed off the selection) but the
// now-ineligible coupon contributes nothing.
expect(getByTestId('coupon-chip-MIN400')).toBeTruthy()
expect(queryByTestId('coupon-bill-81')).toBeNull()
})
it('CART-82: the coupons dialog lists selected coupons, the max-value line and closes', async () => {
const { getByTestId, getByText, queryByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
fireEvent.press(getByTestId('coupon-bill-21'))
await flush(1)
const dialog = getByTestId('coupon-details-dialog')
expect(within(dialog).getByText('Applied Coupons')).toBeTruthy()
expect(within(dialog).getByText('SAVE10')).toBeTruthy()
expect(within(dialog).getByText('10% off (max discount ₹50)')).toBeTruthy()
expect(within(dialog).getByText('Maximum discount up to ₹50')).toBeTruthy()
fireEvent.press(getByTestId('coupon-details-close'))
await flush(1)
expect(queryByTestId('coupon-details-dialog')).toBeNull()
})
it('CART-83: the targeted-coupon info icon opens a desc-sorted, positive-only breakdown', async () => {
const targeted = { ...C4, id: 83, couponCode: 'TGT83', skuIds: [2, 5], maxValue: 40 }
const { getByTestId, getAllByTestId } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 5, 4, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [targeted], isFirstOrder: true } }),
})
await pickCoupon(getByTestId, 83)
fireEvent.press(getByTestId('coupon-breakdown-83'))
await flush(1)
const ids = getAllByTestId(/^coupon-breakdown-row-/).map((node) => node.props.testID)
expect(ids).toEqual(['coupon-breakdown-row-2', 'coupon-breakdown-row-5'])
})
it('CART-84: a coupon with no positive split shows the empty message', async () => {
const zero = { ...C4, id: 84, couponCode: 'ZEROTGT', discountPercent: '0', maxValue: null, skuIds: [2] }
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [zero], isFirstOrder: true } }),
})
await pickCoupon(getByTestId, 84)
fireEvent.press(getByTestId('coupon-breakdown-84'))
await flush(1)
expect(getByText('No per-product split to show for this order.')).toBeTruthy()
})
it('CART-85: the breakdown total equals the coupon row', async () => {
const targeted = { ...C4, id: 85, couponCode: 'TGT85', skuIds: [2, 5], maxValue: 40 }
const { getByTestId, getByText } = await mount({
lines: [line(1, 2, 2, 1849), line(2, 5, 4, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [targeted], isFirstOrder: true } }),
})
await pickCoupon(getByTestId, 85)
expect(getByText('-₹40')).toBeTruthy()
fireEvent.press(getByTestId('coupon-breakdown-85'))
await flush(1)
expect(getByText(`${MINUS}₹40`)).toBeTruthy()
})
it('CART-86: a breakdown line shows quantity × unit price and the product name', async () => {
const targeted = { ...C4, id: 86, couponCode: 'TGT86', skuIds: [2], maxValue: 40 }
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', { data: { data: [targeted], isFirstOrder: true } }),
})
await pickCoupon(getByTestId, 86)
fireEvent.press(getByTestId('coupon-breakdown-86'))
await flush(1)
const row = getByTestId('coupon-breakdown-row-2')
expect(within(row).getByText('Chicken Breast')).toBeTruthy()
expect(within(row).getByText('2 × ₹215')).toBeTruthy()
})
it('CART-87: "Add Coupons to account" navigates to coupons with from=cart', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('add-coupons-to-account'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/me/coupons?from=cart')
})
it('CART-88: delivery instructions edit the global checkout notes', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.changeText(getByTestId('delivery-instructions'), 'Leave at the door')
expect(useCheckoutStore.getState().userNotes).toBe('Leave at the door')
})
/* ------------------------------------------------------------------------ */
/* 13.5 Address and checkout action */
/* ------------------------------------------------------------------------ */
it('CART-89: addresses sort selected/default/id and the default auto-selects', async () => {
const { getByTestId } = await mount({ lines: [] })
expect(getByTestId('address-option-0')).toBeTruthy()
expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy()
expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy()
expect(within(getByTestId('address-option-2')).getByText('NoRegion')).toBeTruthy()
expect(useAddressStore.getState().selectedAddressId).toBe(A1.id)
})
it('CART-91: tapping a cross-region address asks to confirm; Cancel changes nothing', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({
lines: [],
setup: () =>
setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } }),
})
fireEvent.press(getByTestId('address-option-1'))
expect(alertSpy.mock.calls[0][0]).toBe('Switch region?')
const buttons = alertSpy.mock.calls[0][2] as any[]
const cancel = buttons.find((button) => button.text === 'Cancel')
expect(cancel.onPress).toBeUndefined()
expect(useRegionStore.getState().selectedRegionId).toBe(1)
alertSpy.mockRestore()
})
it('CART-92: confirming a cross-region switch switches region, clears the cart and goes home', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({
lines: [line(1, 2, 2, 1849)],
setup: () =>
setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } }),
})
fireEvent.press(getByTestId('address-option-1'))
await tapAlert(alertSpy, 'Switch & clear cart')
expect(useNeoRegionStore.getState().regionId).toBe(2)
expect(storedLines()).toEqual([])
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore()
})
it('CART-93: an address in an unknown region shows "Unavailable region"', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({
lines: [],
setup: () =>
setProcedure('user.address.getUserAddresses', {
data: { data: [A1, { ...A2, id: 31, regionId: 99 }] },
}),
})
fireEvent.press(getByTestId('address-option-1'))
expect(alertSpy).toHaveBeenCalledWith(
'Unavailable region',
'This address belongs to a region that is not currently available.'
)
alertSpy.mockRestore()
})
it('CART-95: attaching the current location updates the address with the coords', async () => {
const { getByTestId } = await mount({
lines: [],
setup: () =>
setProcedure('user.address.getUserAddresses', {
data: { data: [{ ...A1, latitude: null, longitude: null }] },
}),
})
fireEvent.press(getByTestId('attach-location'))
await flush(3)
expect(lastMutationInput('user.address.updateAddress')).toMatchObject({
id: 11,
latitude: 17.00012,
longitude: 78.00034,
})
})
it('CART-96: a denied location permission alerts and does not mutate', async () => {
const alertSpy = spyAlert()
configureLocation({ permission: 'denied' })
const { getByTestId } = await mount({
lines: [],
setup: () =>
setProcedure('user.address.getUserAddresses', {
data: { data: [{ ...A1, latitude: null, longitude: null }] },
}),
})
fireEvent.press(getByTestId('attach-location'))
await flush(3)
expect(alertSpy).toHaveBeenCalledWith(
'Permission Denied',
'Location permission is required to attach your current location'
)
expect(procedureMutationCalls('user.address.updateAddress')).toHaveLength(0)
alertSpy.mockRestore()
})
it('CART-97: a failing location read alerts and clears the loading state', async () => {
const alertSpy = spyAlert()
configureLocation({ permission: 'granted', throwOnPosition: true })
const { getByTestId, getByText } = await mount({
lines: [],
setup: () =>
setProcedure('user.address.getUserAddresses', {
data: { data: [{ ...A1, latitude: null, longitude: null }] },
}),
})
fireEvent.press(getByTestId('attach-location'))
await flush(3)
expect(alertSpy).toHaveBeenCalledWith(
'Error',
'Unable to fetch location. Please check your GPS settings.'
)
expect(getByText('+ Attach Current Location')).toBeTruthy()
alertSpy.mockRestore()
})
it('CART-98: a selected address without coords shows the no-location copy', async () => {
const { getByText } = await mount({
lines: [],
setup: () =>
setProcedure('user.address.getUserAddresses', {
data: { data: [{ ...A1, latitude: null, longitude: null }] },
}),
})
expect(getByText('No Location is attached to address')).toBeTruthy()
})
it('CART-99: Checkout builds the regular route with slots and deliveryPrice', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('checkout-button'))
expect(router.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/home/checkout?slots=1849%3A1&deliveryPrice=0'
)
})
it('CART-100: selected coupon ids are included in the route, comma-separated', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
await pickCoupon(getByTestId, 21)
await pickCoupon(getByTestId, 22)
fireEvent.press(getByTestId('checkout-button'))
expect(router.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/home/checkout?slots=1849%3A1&coupons=21,22&deliveryPrice=0'
)
})
it('CART-101: with no coupon the route has no coupons param', async () => {
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(getByTestId('checkout-button'))
const route = (router.push as jest.Mock).mock.calls[0][0] as string
expect(route).not.toContain('coupons=')
})
it('CART-102: items across slots group as slotId:itemIds pairs', async () => {
const { getByTestId } = await mount({
lines: [line(1, 2, 1, 1849), line(2, 5, 1, 1852)],
})
fireEvent.press(getByTestId('checkout-button'))
expect(router.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/home/checkout?slots=1849%3A1%3B1852%3A2&deliveryPrice=15'
)
})
it('CART-103: all lines out of stock disables checkout and hides the bill', async () => {
const { getByText, queryByTestId, queryByText } = await mount({ lines: [line(1, 6, 1, 1849)] })
expect(getByText('Mutton')).toBeTruthy()
expect(queryByTestId('checkout-button')).toBeNull()
expect(queryByText('Bill Details')).toBeNull()
})
it('CART-104: an out-of-stock line is silently dropped from the groups (no alert)', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({
lines: [line(1, 2, 1, 1849), line(2, 6, 1, 1850)],
})
fireEvent.press(getByTestId('checkout-button'))
expect(alertSpy).not.toHaveBeenCalled()
expect(router.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/home/checkout?slots=1849%3A1&deliveryPrice=15'
)
alertSpy.mockRestore()
})
it('CART-105: a flash cart with no eligible items alerts "None of the items ..."', async () => {
const alertSpy = spyAlert()
const { getByTestId } = await mount({ flash: true, lines: [line(1, 2, 1, 0)] })
fireEvent.press(getByTestId('checkout-button'))
expect(alertSpy.mock.calls[0][0]).toBe('1 Hr Delivery Unavailable')
expect(alertSpy.mock.calls[0][1]).toBe(
'None of the items in your cart are available for flash delivery. Please remove ineligible items or switch to regular delivery.'
)
alertSpy.mockRestore()
})
it('CART-106: a flash cart with some eligible items proceeds with them (current)', async () => {
// Current behaviour: the "Some Items Not Available" alert is unreachable —
// a non-empty available list is built whenever an in-stock flash-eligible
// item exists, so checkout proceeds with the eligible items and no alert.
const alertSpy = spyAlert()
const { getByTestId } = await mount({
flash: true,
lines: [line(1, 8, 1, 0), line(2, 2, 1, 0)],
})
fireEvent.press(getByTestId('checkout-button'))
expect(alertSpy).not.toHaveBeenCalled()
expect(router.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/flash-delivery/checkout?slots=0%3A1&deliveryPrice=0'
)
alertSpy.mockRestore()
})
it('CART-107: a regular line with no slot keeps checkout disabled (no alert reached) (current)', async () => {
// Current behaviour: an in-stock line without a slot trips the slot check,
// so the checkout button is disabled and the "Delivery Slot Required" alert
// is never reached.
const alertSpy = spyAlert()
const { getByTestId, getByText } = await mount({ lines: [line(1, 9, 1, 0)] })
expect(getByTestId('checkout-button')).toBeDisabled()
fireEvent.press(getByTestId('checkout-button'))
await flush(2)
expect(alertSpy).not.toHaveBeenCalled()
expect(
getByText(
'Some items in your cart are no longer available for delivery. Please remove them to continue.'
)
).toBeTruthy()
alertSpy.mockRestore()
})
it('CART-108: Shop More goes to home (regular) or flash-delivery (flash)', async () => {
const regular = await mount({ lines: [line(1, 2, 2, 1849)] })
fireEvent.press(regular.getByTestId('shop-more-button'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
regular.unmount()
;(router.push as jest.Mock).mockClear()
const flash = await mount({ flash: true, lines: [line(1, 8, 1, 0)] })
fireEvent.press(flash.getByTestId('shop-more-button'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/flash-delivery')
})
it('CART-109: a manual refresh refetches the cart (and calls the slots refetch)', async () => {
const original = StorageServiceCasual.getItem
const spy = jest
.spyOn(StorageServiceCasual, 'getItem')
.mockImplementation((key: string) => original(key))
await mount({ lines: [line(1, 2, 2, 1849)] })
const readsBefore = spy.mock.calls.filter((call) => call[0] === CART_KEY).length
await act(async () => {
DeviceEventEmitter.emit(REFRESH_EVENT)
})
await flush(3)
const readsAfter = spy.mock.calls.filter((call) => call[0] === CART_KEY).length
expect(readsAfter).toBeGreaterThan(readsBefore)
// The same handler calls refetchSlots(); the trpc mock's refetch has no
// observable side effect beyond being invoked.
spy.mockRestore()
})
it('CART-110: the mark-data-fetchers focus refetch is skipped on the first focus (current)', async () => {
// Current behaviour: useMarkDataFetchers skips the initial focus, and the
// harness focus mock only fires on mount, so no second refetch happens.
const original = StorageServiceCasual.getItem
const spy = jest
.spyOn(StorageServiceCasual, 'getItem')
.mockImplementation((key: string) => original(key))
await mount({ lines: [line(1, 2, 2, 1849)] })
expect(spy.mock.calls.filter((call) => call[0] === CART_KEY)).toHaveLength(1)
spy.mockRestore()
})
})