freshyo/apps/user-ui/tests/pages/product-detail.test.tsx
2026-11-16 01:28:18 +05:30

697 lines
27 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Section 11 — ProductDetail shared component (PD-01..PD-47).
*
* The component runs for real; only network (tRPC procedure registry, CDN JSON)
* and native modules are mocked. Cart lines live in the storage mock under
* `cart_items` / `flash_cart_items`; slots/availability come from the central
* stores seeded by `seedBoot()` (plus `useSlots()` from the slots CDN doc).
*
* A few rows describe branches that are unreachable from the rendered UI
* (the `newQuantity === 1 && !cartItem` quantifier branch, the not-flash-eligible
* alert, the no-quickest-slot alert). Those cases assert the closest observable
* behaviour and say so in a comment.
*/
import * as React from 'react'
import { Alert, Image as RNImage, RefreshControl, StyleSheet } from 'react-native'
import { QueryClient } from '@tanstack/react-query'
import { fireEvent, waitFor } from '@testing-library/react-native'
import ProductDetail from '@/components/ProductDetail'
import { useCartStore } from '@/src/store/cartStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastProcedureInput,
procedureQueryCalls,
setProcedure,
} from '../mocks/trpc-client'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { router } from '../mocks/expo-router-mock'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import { setJsonResponse } from '../mocks/fetch-json'
import {
CART_REG,
P_COMBO,
P_FLASH,
P_NO_SLOT,
P_OUT,
PRODUCT_DETAILS,
REVIEWS_RESPONSE,
slotsCacheUrl,
slotsResponse,
} from '../fixtures'
/** 10% capped ₹40 on Chicken Breast (sku 2): ₹215 -> ₹194. */
const CHICKEN_OFFER = {
couponId: 24,
couponCode: 'TARGET10',
discountPercent: '10',
flatDiscount: null,
maxValue: 40,
}
/** 10% capped ₹20 on Paneer (sku 8): flash ₹75 -> ₹68. */
const PANEER_OFFER = {
couponId: 31,
couponCode: 'FLASH10',
discountPercent: '10',
flatDiscount: null,
maxValue: 20,
}
const fontSizeOf = (node: any) => StyleSheet.flatten(node.props.style)?.fontSize
const HOUR = 60 * 60 * 1000
const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString()
/** Mutation GC off so a finished 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 },
},
})
}
/** Standard boot: region + catalogue + central product/slot stores + CDN JSON. */
function seedDetail(detail: any = PRODUCT_DETAILS) {
seedBoot()
setProcedure('user.product.getProductDetails', { data: detail })
setProcedure('user.product.getProductReviews', { data: REVIEWS_RESPONSE })
}
/** Replace the slots CDN document (the `useSlots` URL is fetched with `?v=123`). */
function overrideSlots(slots: any[]) {
setJsonResponse(slotsCacheUrl(1), slotsResponse(slots))
setJsonResponse(`${slotsCacheUrl(1)}?v=123`, slotsResponse(slots))
}
async function renderDetail(productId = '2', props: Record<string, unknown> = {}) {
const utils = renderWithProviders(
<ProductDetail productId={productId} {...(props as any)} />,
{ auth: false, queryClient: createClient() }
)
await flush(2)
return utils
}
const cartLine = (id: number, skuId: number, quantity: number, slotId: number) =>
JSON.stringify([{ id, skuId, quantity, slotId, addedAt: '2024-01-01T00:00:00.000Z' }])
describe('ProductDetail', () => {
beforeEach(() => resetAllMocks())
it('PD-01: with no region the loading copy shows and the product query never runs', async () => {
configureLocation({ permission: 'denied', position: null })
const { getByText } = await renderDetail('2')
expect(getByText('Loading product details...')).toBeTruthy()
expect(procedureQueryCalls('user.product.getProductDetails')).toHaveLength(0)
})
it('PD-02: a pending product query keeps the loading copy', async () => {
seedBoot()
setProcedure('user.product.getProductDetails', { mode: 'pending' })
const { getByText } = await renderDetail('2')
expect(getByText('Loading product details...')).toBeTruthy()
})
it('PD-03: a rejected product query shows the error copy', async () => {
seedBoot()
setProcedure('user.product.getProductDetails', { mode: 'error', error: new Error('boom') })
const { getByText } = await renderDetail('2')
expect(getByText('Product not found or error loading')).toBeTruthy()
})
it('PD-04: a successful query with no product shows the error copy', async () => {
seedBoot()
setProcedure('user.product.getProductDetails', { data: undefined })
const { getByText } = await renderDetail('2')
expect(getByText('Product not found or error loading')).toBeTruthy()
})
it('PD-05: a loaded product renders name, descriptions, unit and price', async () => {
seedDetail()
const { getByText } = await renderDetail('2')
expect(getByText('Chicken Breast')).toBeTruthy()
expect(getByText('Tender boneless breast')).toBeTruthy()
expect(getByText('Tender boneless chicken breast.')).toBeTruthy()
expect(getByText('/ 500g')).toBeTruthy()
expect(getByText('₹215')).toBeTruthy()
})
it('PD-06: a market price renders the struck price and the rounded % OFF', async () => {
seedDetail({ ...PRODUCT_DETAILS, price: 215, marketPrice: 220 })
const { getByText, getByTestId } = await renderDetail('2')
expect(getByTestId('product-discount')).toBeTruthy()
expect(getByText('₹220')).toBeTruthy()
expect(getByText('2% OFF')).toBeTruthy()
})
it('PD-07: no market price means no discount block', async () => {
seedDetail({ ...PRODUCT_DETAILS, marketPrice: null })
const { queryByTestId } = await renderDetail('2')
expect(queryByTestId('product-discount')).toBeNull()
})
it('PD-08: a market price below the price renders a negative percentage', async () => {
seedDetail({ ...PRODUCT_DETAILS, price: 100, marketPrice: 80 })
const { getByText } = await renderDetail('2')
expect(getByText('-25% OFF')).toBeTruthy()
})
it('PD-09: a market price of 0 is falsy and renders no percentage', async () => {
seedDetail({ ...PRODUCT_DETAILS, marketPrice: 0 })
const { queryByTestId } = await renderDetail('2')
expect(queryByTestId('product-discount')).toBeNull()
})
it('PD-10: a combo product hides the / unit suffix and shows the items section', async () => {
seedDetail({
...P_COMBO,
productId: 150,
longDescription: 'combo pack',
comboItems: [
{ skuId: 2, productName: 'Chicken Breast', unitNotation: '500g', images: ['chicken.jpg'] },
{ skuId: 5, productName: 'Cucumber', unitNotation: '500g', images: ['cucumber.jpg'] },
],
})
const { getByText, queryByText } = await renderDetail('150')
expect(queryByText('/ 1 combo')).toBeNull()
expect(getByText('Included Items')).toBeTruthy()
})
it('PD-11: combo items render names, offer badge and the SKU fallback', async () => {
const detail = {
...P_COMBO,
productId: 150,
longDescription: 'combo pack',
comboItems: [
{ skuId: 2, productName: 'Chicken Breast', unitNotation: '500g', images: ['chicken.jpg'], isOffer: false },
{ skuId: 5, productName: 'Cucumber', skuName: 'Cucumber SKU', images: [], isOffer: true },
],
}
seedDetail(detail)
const { getByText, getByTestId } = await renderDetail('150')
expect(getByTestId('combo-item-2')).toBeTruthy()
expect(getByTestId('combo-item-5')).toBeTruthy()
expect(getByText('Chicken Breast')).toBeTruthy()
expect(getByText('500g')).toBeTruthy()
// No images + no unit notation → the skuName fallback line renders.
expect(getByText('Cucumber SKU')).toBeTruthy()
expect(getByText('OFFER')).toBeTruthy()
})
it('PD-12: special deals render one quantity/price row each', async () => {
seedDetail({
...PRODUCT_DETAILS,
specialDeals: [
{ quantity: '2', price: '300', validTill: '2026-01-01' },
{ quantity: '3', price: '420', validTill: '2026-01-01' },
],
})
const { getByText } = await renderDetail('2')
expect(getByText('Bulk Savings')).toBeTruthy()
expect(getByText('Buy 2 • 500g')).toBeTruthy()
expect(getByText('₹300')).toBeTruthy()
expect(getByText('₹420')).toBeTruthy()
})
it('PD-13: store information renders under Sourced From', async () => {
seedDetail()
const { getByText } = await renderDetail('2')
expect(getByText('Sourced From')).toBeTruthy()
expect(getByText('The Freshyo Meat House')).toBeTruthy()
})
it('PD-14: an absent long description shows the fallback copy', async () => {
seedDetail({ ...PRODUCT_DETAILS, longDescription: undefined })
const { getByText } = await renderDetail('2')
expect(getByText('No detailed description available.')).toBeTruthy()
})
it('PD-15: flash availability renders the badge and the flash price line', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const { getByText, getByTestId } = await renderDetail('8')
expect(getByTestId('product-flash-badge')).toBeTruthy()
expect(getByText('1 Hr Delivery')).toBeTruthy()
expect(getByTestId('product-flash-price')).toBeTruthy()
expect(getByText('1 Hr Delivery: ₹75 / 200g')).toBeTruthy()
})
it('PD-16: a flash price equal to the regular price hides the flash line', async () => {
seedDetail({ ...P_FLASH, productId: 8, flashPrice: 90 })
const { getByTestId, queryByTestId } = await renderDetail('8')
expect(getByTestId('product-flash-badge')).toBeTruthy()
expect(queryByTestId('product-flash-price')).toBeNull()
})
it('PD-17: an out-of-stock product shows the badge, disables Add and says Unavailable', async () => {
seedDetail({ ...P_OUT, productId: 6 })
const { getByText, getByTestId } = await renderDetail('6')
expect(getByText('Out of Stock')).toBeTruthy()
expect(getByText('Unavailable')).toBeTruthy()
expect(getByTestId('product-add-to-cart').props.accessibilityState.disabled).toBe(true)
})
it('PD-18: no product availability leaves the Add button enabled', async () => {
seedDetail({ ...PRODUCT_DETAILS, id: 999, productId: 999 })
const { getByText, getByTestId } = await renderDetail('999')
expect(getByText('Add to Cart')).toBeTruthy()
fireEvent.press(getByTestId('product-add-to-cart'))
expect(useCartStore.getState().addedToCartProduct?.productId).toBe(999)
})
it('PD-19: the regular Add button queues the product for the slot dialog', async () => {
seedDetail()
const { getByTestId } = await renderDetail('2')
fireEvent.press(getByTestId('product-add-to-cart'))
expect(useCartStore.getState().addedToCartProduct?.productId).toBe(2)
// Regular adds go through the dialog, not a direct storage write.
expect(__snapshot().cart_items).toBeUndefined()
})
it('PD-20: an existing cart line renders the Quantifier and mutates on press', async () => {
seedDetail()
__set('cart_items', CART_REG)
const { getByTestId } = await renderDetail('2')
expect(getByTestId('quantifier-value')).toHaveTextContent('2')
fireEvent.press(getByTestId('quantifier-increment'))
await waitFor(() => expect(JSON.parse(__snapshot().cart_items)[0].quantity).toBe(3))
fireEvent.press(getByTestId('quantifier-decrement'))
await waitFor(() => expect(JSON.parse(__snapshot().cart_items)[0].quantity).toBe(2))
})
it('PD-21: decrementing a single-item line to 0 removes it from the cart', async () => {
seedDetail()
__set('cart_items', cartLine(1, 2, 1, 1849))
const { getByTestId } = await renderDetail('2')
fireEvent.press(getByTestId('quantifier-decrement'))
await waitFor(() => expect(JSON.parse(__snapshot().cart_items)).toHaveLength(0))
})
it('PD-22: a line for another SKU leaves the product out of cart, so Add queues the dialog', async () => {
// The `newQuantity === 1 && !cartItem` quantifier branch cannot be reached
// from the UI: the Quantifier only renders when this product already has a
// cart line (quantity > 0). This asserts the observable "not in cart" path.
seedDetail()
__set('cart_items', cartLine(1, 5, 1, 1849))
const { getByText, getByTestId } = await renderDetail('2')
expect(getByText('Add to Cart')).toBeTruthy()
fireEvent.press(getByTestId('product-add-to-cart'))
expect(useCartStore.getState().addedToCartProduct?.productId).toBe(2)
})
it('PD-23: a product with no delivery slots still queues the dialog, never the slot alert', async () => {
// The "No available delivery slot for this product" alert only fires from
// handleAddToCart, which the regular Add button never calls (it queues the
// dialog). This documents the reachable behaviour instead.
const alertSpy = jest.spyOn(Alert, 'alert')
seedDetail({ ...P_NO_SLOT, productId: 10, longDescription: 'no slot item' })
const { getByTestId, queryByText } = await renderDetail('10')
fireEvent.press(getByTestId('product-add-to-cart'))
expect(useCartStore.getState().addedToCartProduct?.productId).toBe(10)
expect(queryByText('No available delivery slot for this product')).toBeNull()
expect(alertSpy).not.toHaveBeenCalled()
})
it('PD-24: pressing Add on an out-of-stock product mutates nothing', async () => {
seedDetail({ ...P_OUT, productId: 6 })
const { getByTestId } = await renderDetail('6')
fireEvent.press(getByTestId('product-add-to-cart'))
await flush()
expect(useCartStore.getState().addedToCartProduct).toBeNull()
expect(__snapshot().cart_items).toBeUndefined()
})
it('PD-25: tapping a slot row adds the product with that slot', async () => {
seedDetail()
const { findByTestId } = await renderDetail('2')
fireEvent.press(await findByTestId('product-slot-1849'))
await waitFor(() => {
const items = JSON.parse(__snapshot().cart_items)
expect(items).toHaveLength(1)
expect(items[0].skuId).toBe(2)
expect(items[0].quantity).toBe(1)
expect(items[0].slotId).toBe(1849)
})
})
it('PD-26: tapping a slot row for an existing line removes then re-adds quantity + 1', async () => {
seedDetail()
__set('cart_items', CART_REG)
const { findByTestId } = await renderDetail('2')
fireEvent.press(await findByTestId('product-slot-1849'))
await waitFor(() => {
const items = JSON.parse(__snapshot().cart_items)
expect(items).toHaveLength(1)
expect(items[0].skuId).toBe(2)
expect(items[0].quantity).toBe(3)
expect(items[0].slotId).toBe(1849)
})
})
it('PD-27: a failing remove in the re-add flow closes the loading dialog and adds nothing', async () => {
seedDetail()
__set('cart_items', CART_REG)
const { findByTestId, queryByText } = await renderDetail('2')
// The slot rows come from the async slots query, so wait for the row first.
const slotRow = await findByTestId('product-slot-1849')
// Corrupt the stored cart so the remove mutation's read throws → onError.
__set('cart_items', '{not-json')
fireEvent.press(slotRow)
await flush(2)
expect(queryByText('Processing...')).toBeNull()
expect(__snapshot().cart_items).toBe('{not-json')
})
it('PD-28: slot rows are sorted by delivery time with a freeze-time tie-break', async () => {
seedDetail()
overrideSlots([
{ id: 501, deliveryTime: iso(2 * HOUR), freezeTime: iso(1 * HOUR), products: [{ id: 2 }] },
{ id: 503, deliveryTime: iso(1 * HOUR), freezeTime: iso(0.5 * HOUR), products: [{ id: 2 }] },
{ id: 502, deliveryTime: iso(2 * HOUR), freezeTime: iso(0.25 * HOUR), products: [{ id: 2 }] },
])
const { findAllByTestId } = await renderDetail('2')
const ids = (await findAllByTestId(/^product-slot-/)).map((node) => node.props.testID)
expect(ids).toEqual(['product-slot-503', 'product-slot-502'])
})
it('PD-29: a slot whose delivery time has passed is still rendered', async () => {
seedDetail()
overrideSlots([
{ id: 601, deliveryTime: iso(-1 * HOUR), freezeTime: iso(1 * HOUR), products: [{ id: 2 }] },
])
const { findByTestId } = await renderDetail('2')
expect(await findByTestId('product-slot-601')).toBeTruthy()
})
it('PD-30: more than two slots shows the View All button which opens the dialog', async () => {
seedDetail()
const { getByText, getByTestId, findByTestId } = await renderDetail('2')
const viewAll = await findByTestId('product-view-all-slots')
expect(getByText('View All 4 Slots')).toBeTruthy()
fireEvent.press(viewAll)
expect(getByText('All Delivery Slots')).toBeTruthy()
})
it('PD-31: the all-slots dialog lists every slot and closes', async () => {
seedDetail()
const { getByText, getByTestId, queryByText, findByTestId } = await renderDetail('2')
fireEvent.press(await findByTestId('product-view-all-slots'))
;[1851, 1849, 1850, 1852].forEach((id) => {
expect(getByTestId(`product-all-slot-${id}`)).toBeTruthy()
})
fireEvent.press(getByTestId('product-slots-dialog-close'))
expect(queryByText('All Delivery Slots')).toBeNull()
})
it('PD-32: out-of-stock slot rows are disabled', async () => {
seedDetail()
const { productSlotsMap } = useCentralSlotStore.getState()
useCentralSlotStore.setState({
productSlotsMap: { ...productSlotsMap, 2: { ...productSlotsMap[2], isOutOfStock: true } },
})
const { findByTestId } = await renderDetail('2')
expect((await findByTestId('product-slot-1849')).props.accessibilityState.disabled).toBe(true)
})
it('PD-33: the flash Add button writes the flash cart with slot 0', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const { getByTestId, getByText } = await renderDetail('8', { isFlashDelivery: true })
fireEvent.press(getByTestId('product-add-to-cart'))
// The add shows the blocking "Processing..." dialog while it settles.
expect(getByText('Processing...')).toBeTruthy()
await waitFor(() => {
const items = JSON.parse(__snapshot().flash_cart_items)
expect(items[0].skuId).toBe(8)
expect(items[0].quantity).toBe(1)
expect(items[0].slotId).toBe(0)
})
})
it('PD-34: a not-eligible flash product cannot be added and is labelled Unavailable', async () => {
// The "This product is not available for flash delivery" alert sits behind a
// guard the disabled Add button already enforces, so it is unreachable.
const alertSpy = jest.spyOn(Alert, 'alert')
seedDetail()
const { getByText, getByTestId } = await renderDetail('2', { isFlashDelivery: true })
expect(getByText('Unavailable')).toBeTruthy()
expect(getByTestId('product-add-to-cart').props.accessibilityState.disabled).toBe(true)
fireEvent.press(getByTestId('product-add-to-cart'))
expect(alertSpy).not.toHaveBeenCalled()
expect(__snapshot().flash_cart_items).toBeUndefined()
})
it('PD-35: an out-of-stock flash product disables Add and labels the CTA Out of Stock', async () => {
seedDetail({ ...P_OUT, productId: 6 })
const { getByText, getByTestId, getAllByText } = await renderDetail('6', { isFlashDelivery: true })
expect(getByText('Unavailable')).toBeTruthy()
expect(getByTestId('product-add-to-cart').props.accessibilityState.disabled).toBe(true)
expect(getByTestId('product-buy-now').props.accessibilityState.disabled).toBe(true)
// The badge and the CTA both read "Out of Stock".
expect(getAllByText('Out of Stock')).toHaveLength(2)
})
it('PD-36: a flash product without eligibility labels the CTA Not Flash Eligible', async () => {
seedDetail()
const { getByText } = await renderDetail('2', { isFlashDelivery: true })
expect(getByText('Not Flash Eligible')).toBeTruthy()
})
it('PD-37: a regular product that is flash eligible with slots shows Get in 1 Hour', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const { getByTestId, findByText } = await renderDetail('8')
expect(await findByText('Get in 1 Hour')).toBeTruthy()
expect(getByTestId('product-buy-now').props.accessibilityState.disabled).toBe(false)
})
it('PD-38: a flash-eligible regular product with no slots shows a disabled No Slots CTA', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
overrideSlots([
{ id: 700, deliveryTime: iso(2 * HOUR), freezeTime: iso(1 * HOUR), products: [{ id: 2 }] },
])
const { getByText, getByTestId } = await renderDetail('8')
expect(getByText('No Slots')).toBeTruthy()
expect(getByTestId('product-buy-now').props.accessibilityState.disabled).toBe(true)
})
it('PD-39: the regular Get in 1 Hour CTA adds to the flash cart and routes to flash delivery', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const { getByTestId, findByText } = await renderDetail('8')
await findByText('Get in 1 Hour')
fireEvent.press(getByTestId('product-buy-now'))
await waitFor(() => {
const items = JSON.parse(__snapshot().flash_cart_items)
expect(items[0].skuId).toBe(8)
expect(items[0].slotId).toBe(0)
})
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(true)
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/flash-delivery')
})
it('PD-40: the flash Get in 1 Hour CTA adds to the flash cart and routes with select=<id>', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const { getByTestId } = await renderDetail('8', { isFlashDelivery: true })
fireEvent.press(getByTestId('product-buy-now'))
await waitFor(() => {
const items = JSON.parse(__snapshot().flash_cart_items)
expect(items[0].skuId).toBe(8)
})
expect(router.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/flash-delivery/(cart)/cart?select=8'
)
})
it('PD-41: the review form and list stay hidden even with review data', async () => {
seedDetail()
const { queryByText } = await renderDetail('2')
expect(queryByText('Rate this Product')).toBeNull()
expect(queryByText('Customer Reviews')).toBeNull()
expect(queryByText('No reviews yet.')).toBeNull()
})
it('PD-42: mounting still requests the first review page through the client proxy', async () => {
seedDetail()
await renderDetail('2')
expect(procedureQueryCalls('user.product.getProductReviews')).toHaveLength(1)
expect(lastProcedureInput('user.product.getProductReviews')).toEqual({
productId: 2,
limit: 10,
offset: 0,
})
})
it('PD-43: a rejected review request is swallowed and the product still renders', async () => {
seedDetail()
setProcedure('user.product.getProductReviews', { mode: 'error', error: new Error('nope') })
const { getByText } = await renderDetail('2')
expect(getByText('Chicken Breast')).toBeTruthy()
expect(procedureQueryCalls('user.product.getProductReviews')).toHaveLength(1)
})
it('PD-44: pull to refresh refetches the product and resets the reviews', async () => {
seedDetail()
const view = await renderDetail('2')
const [refreshControl] = view.UNSAFE_getAllByType(RefreshControl)
fireEvent(refreshControl, 'refresh')
await flush(2)
expect(procedureQueryCalls('user.product.getProductReviews')).toHaveLength(2)
expect(lastProcedureInput('user.product.getProductReviews')).toEqual({
productId: 2,
limit: 10,
offset: 0,
})
})
it('PD-45: the store header title is set to the product name', async () => {
seedDetail()
await renderDetail('2')
expect(useStoreHeaderStore.getState().title).toBe('Chicken Breast')
})
it('PD-46: the carousel receives the image URLs and empty images do not crash', async () => {
seedDetail()
const first = await renderDetail('2')
const images = first.UNSAFE_getAllByType(RNImage).filter(
(node) => node.props.source?.uri === 'chicken.jpg'
)
expect(images.length).toBeGreaterThan(0)
first.unmount()
seedDetail({ ...PRODUCT_DETAILS, images: [] })
const second = await renderDetail('2')
expect(second.getByText('Chicken Breast')).toBeTruthy()
})
it('PD-47: the floating cart bar switches between the regular and flash variants', async () => {
seedDetail()
const regular = await renderDetail('2')
expect(regular.getByText('No Items In Cart')).toBeTruthy()
regular.unmount()
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const flash = await renderDetail('8', { isFlashDelivery: true })
expect(flash.getByText('No Flash Items')).toBeTruthy()
})
/*
* Catalogue coupons: the detail screen reads the offer from the central product
* store, so the figure matches the card the customer tapped.
*/
it('PD-52: a product coupon adds the coupon price under the price block', async () => {
seedDetail()
useCentralProductStore.getState().setCouponOffers({ 2: [CHICKEN_OFFER] })
const { getByTestId, getByText } = await renderDetail('2')
await waitFor(() => expect(getByTestId('product-coupon-price')).toBeTruthy())
// ₹215 - min(21.5, 40) = ₹193.5 -> ₹194
expect(getByTestId('product-coupon-price')).toHaveTextContent('₹194')
expect(getByText('With Coupon')).toBeTruthy()
// The price block stays the hero number (text-3xl); the coupon line is
// text-base, i.e. the struck price's size, and never outshines it.
expect(fontSizeOf(getByText('₹215'))).toBe(30)
expect(fontSizeOf(getByText('₹220'))).toBe(16)
expect(fontSizeOf(getByText('₹194'))).toBe(16)
})
it('PD-53: without a coupon there is no coupon line', async () => {
seedDetail()
const { queryByTestId } = await renderDetail('2')
expect(queryByTestId('product-coupon-price')).toBeNull()
})
it('PD-54: the flash detail prices the coupon off the flash price', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
useCentralProductStore.getState().setCouponOffers({ 8: [PANEER_OFFER] })
const { getByTestId } = await renderDetail('8', { isFlashDelivery: true })
await waitFor(() => expect(getByTestId('product-coupon-price')).toBeTruthy())
// ₹75 flash - 10% (capped ₹20) = ₹67.5 -> ₹68
expect(getByTestId('product-coupon-price')).toHaveTextContent('₹68')
})
it('PD-55: an out-of-stock product shows no coupon line', async () => {
seedDetail(P_OUT)
useCentralProductStore.getState().setCouponOffers({ 6: [CHICKEN_OFFER] })
const { queryByTestId } = await renderDetail('6')
expect(queryByTestId('product-coupon-price')).toBeNull()
})
})