freshyo/apps/user-ui/tests/home-page/home-floating-cart-bar.test.tsx
2026-09-26 00:46:08 +05:30

203 lines
6.9 KiB
TypeScript

/**
* FloatingCartBar — the home page's cart bar and its "Your Cart" dialog.
*
* Products are pinned (see PINNED_PRODUCTS) so every money and slot expectation
* is an exact number rather than a computed one:
* - they all live in the "Chicken" tag, so a single expanded grid holds them,
* - their prices come from mock-availability-response.json,
* - the free-delivery threshold is consts.freeDeliveryThreshold (249).
*
* The bar counts cart LINES (itemCount = cartItems.length), so one product at
* quantity 2 still reads "1 Item".
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import { fireEvent, screen, waitFor, within } from '@testing-library/react-native'
import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual'
import dayjs from 'dayjs'
import {
ESSENTIAL_CONSTS_DATA,
mockSlots,
outOfStockIds,
resetStorage,
setupApiMocks,
} from '../mocks/api'
import { useNavigationStore } from '@/src/store/navigationStore'
import { addToCartFromTagGrid, expandTag, renderLoadedHome } from './render'
const FREE_DELIVERY_THRESHOLD = ESSENTIAL_CONSTS_DATA.freeDeliveryThreshold
/**
* The products these tests add, with their exact fixture prices.
* 215 + 129 = 344 crosses the 249 threshold; 215 alone leaves a 34 gap.
*/
const PINNED_PRODUCTS = [
{ id: 2, name: 'Chicken Breast 500 g', price: 215, tagId: 1 },
{ id: 40, name: 'Chicken regular cut Large pieces', price: 129, tagId: 1 },
] as const
const [CHICKEN_BREAST, CHICKEN_LARGE_CUT] = PINNED_PRODUCTS
/** Mirrors formatTimeRange in components/floating-cart-bar.tsx (includes the date). */
const formatSlotLabel = (deliveryTime: string) => {
const time = dayjs(deliveryTime)
const endTime = time.add(1, 'hour')
const startPeriod = time.format('A')
const endPeriod = endTime.format('A')
const range =
startPeriod === endPeriod
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
return `${time.format('ddd, DD MMM ')}${range}`
}
/** The slot addToCartFromTagGrid will pick: first in fixture order, freeze ahead. */
const firstOpenSlotFor = (productId: number) => {
const slot = mockSlots.slots.find(
(s) =>
s.products.some((p) => p.id === productId) &&
dayjs(s.freezeTime).isAfter(dayjs())
)
if (!slot) throw new Error(`[tests] no open slot for product ${productId}`)
return slot
}
const expandCart = () => {
// The collapsed bar only expands while it has items.
fireEvent.press(screen.getByText(/• \d+ Items?/))
}
describe('Floating cart bar', () => {
beforeEach(async () => {
setupApiMocks()
await resetStorage()
useNavigationStore.setState({
isNavigatedFromHome: false,
selectedStoreId: null,
})
})
it('adds exactly the pinned products and tracks the total and delivery threshold', async () => {
await renderLoadedHome()
// Guards the pinned prices against a fixture change.
for (const product of PINNED_PRODUCTS) {
expect(outOfStockIds.has(product.id)).toBe(false)
}
expandTag(CHICKEN_BREAST.tagId)
addToCartFromTagGrid(CHICKEN_BREAST.id)
await waitFor(() =>
expect(screen.getByText(`₹${CHICKEN_BREAST.price} • 1 Item`)).toBeVisible()
)
expect(
screen.getByText(
new RegExp(`₹${FREE_DELIVERY_THRESHOLD - CHICKEN_BREAST.price} more for`)
)
).toBeVisible()
addToCartFromTagGrid(CHICKEN_LARGE_CUT.id)
const total = CHICKEN_BREAST.price + CHICKEN_LARGE_CUT.price
await waitFor(() => expect(screen.getByText(`₹${total} • 2 Items`)).toBeVisible())
expect(screen.getByText(/Free Delivery Unlocked/)).toBeVisible()
expect(screen.queryByText(/more for/)).toBeNull()
})
it('places each pinned product in the first open slot it belongs to', async () => {
await renderLoadedHome()
expandTag(CHICKEN_BREAST.tagId)
addToCartFromTagGrid(CHICKEN_BREAST.id)
// Wait for the first add to settle, otherwise its dialog cleanup can race
// the second product's dialog and drop it.
await waitFor(() => expect(screen.getByText(/• 1 Item/)).toBeVisible())
addToCartFromTagGrid(CHICKEN_LARGE_CUT.id)
await waitFor(() => expect(screen.getByText(/• 2 Items/)).toBeVisible())
const slot = firstOpenSlotFor(CHICKEN_BREAST.id)
// Both pinned products resolve to the first open slot in the fixture.
expect(firstOpenSlotFor(CHICKEN_LARGE_CUT.id).id).toBe(slot.id)
expandCart()
expect(screen.getByText('Your Cart')).toBeVisible()
// One delivery-slot label per cart line (each row shows its own slot).
expect(screen.getAllByText(formatSlotLabel(slot.deliveryTime))).toHaveLength(
PINNED_PRODUCTS.length
)
})
it('recomputes the total when the quantity changes', async () => {
await renderLoadedHome()
expandTag(CHICKEN_BREAST.tagId)
addToCartFromTagGrid(CHICKEN_BREAST.id)
await waitFor(() => expect(screen.getByText(/1 Item/)).toBeVisible())
// The card stepper reopens the dialog in update mode, preloaded with 1.
fireEvent.press(
within(screen.getByTestId(`tag-product-${CHICKEN_BREAST.id}`)).getByTestId(
'mini-quantifier-increment'
)
)
expect(screen.getByText('Update Item')).toBeVisible()
expect(screen.getByTestId('quantifier-value')).toHaveTextContent('1')
fireEvent.press(screen.getByTestId('quantifier-increment'))
expect(screen.getByTestId('quantifier-value')).toHaveTextContent('2')
fireEvent.press(screen.getByTestId('add-to-cart-confirm'))
// Still one line, but the value is price * 2.
const doubled = CHICKEN_BREAST.price * 2
await waitFor(() => expect(screen.getByText(`₹${doubled} • 1 Item`)).toBeVisible())
expect(screen.getByText(/Free Delivery Unlocked/)).toBeVisible()
})
it('expands into the cart dialog with the line and the subtotal', async () => {
await renderLoadedHome()
expandTag(CHICKEN_BREAST.tagId)
addToCartFromTagGrid(CHICKEN_BREAST.id)
await waitFor(() => expect(screen.getByText(/• 1 Item/)).toBeVisible())
expandCart()
expect(screen.getByText('Your Cart')).toBeVisible()
expect(screen.getByText('Subtotal')).toBeVisible()
expect(screen.getAllByText(`₹${CHICKEN_BREAST.price}`).length).toBeGreaterThan(0)
})
it('re-slots a stored cart item whose slot no longer exists', async () => {
await StorageServiceCasual.setItem(
'cart_items',
JSON.stringify([
{
id: 1,
skuId: CHICKEN_BREAST.id,
quantity: 1,
slotId: 999999,
addedAt: new Date().toISOString(),
},
])
)
await renderLoadedHome()
await waitFor(async () => {
const raw = await StorageServiceCasual.getItem('cart_items')
const items = raw ? JSON.parse(raw) : []
expect(items).toHaveLength(1)
expect(items[0].slotId).not.toBe(999999)
expect(mockSlots.slots.some((s) => s.id === items[0].slotId)).toBe(true)
})
})
})