/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 8.1/8.2 — Slot view (`tests/pages/slot-view.test.tsx`, * SLOT-01..29). * * Covers the route wrapper (`slot-view/index.tsx`), `SlotLayout` * (`slot-view/_layout.tsx`) and `SlotProducts` from * `components/SlotSpecificView.tsx`. * * The shared `expo-router` mock renders layout primitives as pass-throughs and * ignores `drawerContent`, so this file narrows `expo-router/drawer` with a * Drawer that also renders `drawerContent(props)` — otherwise the drawer rows * (SLOT-05..08, SLOT-10) would be unreachable. */ import * as React from 'react' import { Alert, RefreshControl, StyleSheet } from 'react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native' import { QueryClient } from '@tanstack/react-query' import dayjs from 'dayjs' import SlotView from '@/app/(drawer)/(tabs)/home/slot-view/index' import SlotViewLayout from '@/app/(drawer)/(tabs)/home/slot-view/_layout' import FlashProductsLayout from '@/app/(drawer)/(tabs)/flash-delivery/(products)/_layout' import { useSlotStore } from '@/components/stores/slotStore' import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore' import { useAppStore } from '@/src/store/appStore' import { flush, renderWithProviders, seedBoot, seedCentralStores } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { router, __setParams } from '../mocks/expo-router-mock' import { jsonCallsFor, setJsonError, setJsonPending, setJsonResponse } from '../mocks/fetch-json' import { __snapshot } from '../mocks/secure-store-mock' import { MERGED_PRODUCTS, PRODUCT_AVAILABILITY, SLOTS, slotsCacheUrl, storesCacheUrl, } from '../fixtures' jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) jest.mock('expo-router/drawer', () => { const React = require('react') // `expo-router` and `expo-router/drawer` resolve to the same harness mock, so // override only the Drawer export on top of the real (mocked) module. const actual = jest.requireActual(__dirname + '/../mocks/native/expo-router') return { ...actual, Drawer: (props: any) => { ;(globalThis as any).__drawerProps = props const content = props.drawerContent ? props.drawerContent({}) : null return React.createElement(React.Fragment, null, props.children, content) }, } }) const BASE_URL = '/(drawer)/(tabs)/home/slot-view' /** A one-entry slots document for the given slot products. */ function slotsWith(products: any[], id = 1849) { return { slots: [{ ...slot1849(), id, products }], productAvailability: PRODUCT_AVAILABILITY, count: 1, } } /** * The 1849 slot. Looked up by id because `QuickDeliveryAddressSelector` sorts * `slotsData.slots` in place (oldest first), so `SLOTS[0]` is not stable. */ function slot1849() { return SLOTS.find((slot) => slot.id === 1849) ?? SLOTS[0] } function seedSlots(response: any) { setJsonResponse(slotsCacheUrl(1), response) setJsonResponse(`${slotsCacheUrl(1)}?v=123`, response) } /** * Give the mocked CDN a moment to hydrate consts, slots and products. * * The queries now run through the real React Query client, so this only drains * the first round of work. Rows that assert loaded content must still await the * element they need (`findBy*` / `waitFor`) — `load()` alone is not enough. */ async function load() { await flush(3) } function renderRoute(params: Record = {}, queryClient?: QueryClient) { __setParams(params) return renderWithProviders(, { auth: false, queryClient }) } /** * Cart mutations otherwise schedule React Query's 5-minute GC timer, which keeps * the jest process alive long after the run has finished. */ function createMutationQueryClient(): QueryClient { return new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: Infinity, refetchOnWindowFocus: false, }, mutations: { retry: false, gcTime: 0 }, }, }) } function renderLayout(params: Record = {}) { __setParams(params) return renderWithProviders(, { auth: false }) } const storeNameStyle = (element: any) => StyleSheet.flatten(element.props.style) as any describe('Slot view (SLOT)', () => { beforeEach(() => { resetAllMocks() ;(globalThis as any).__drawerProps = undefined seedBoot() }) it('SLOT-01: the route forwards slotId=1849 to SlotProducts', async () => { const { getByText, findByText } = renderRoute({ slotId: '1849' }) await load() expect(useSlotStore.getState().slotId).toBe(1849) expect(await findByText('Chicken Breast')).toBeTruthy() expect(getByText('Cucumber')).toBeTruthy() }) it('SLOT-02: without a slotId the page falls back to "No delivery slot available."', async () => { const { findByText } = renderRoute() await load() expect(useSlotStore.getState().slotId).toBeUndefined() expect(await findByText('No delivery slot available.')).toBeTruthy() }) it('SLOT-03: a missing storeId becomes NaN and applies no store filter', async () => { // Spread the two slot products across two stores so the filter is visible. seedCentralStores({ products: MERGED_PRODUCTS.map((product) => product.id === 5 ? { ...product, storeId: 2 } : product ), }) const { getByText, findByText } = renderRoute({ slotId: '1849' }) await load() expect(Number.isNaN(useSlotStore.getState().storeId as number)).toBe(true) expect(await findByText('Chicken Breast')).toBeTruthy() expect(getByText('Cucumber')).toBeTruthy() }) it('SLOT-04: the layout renders the address selector, the drawer and the floating cart', async () => { const { getByTestId, getByText, findByTestId } = renderLayout({ slotId: '1849' }) await load() expect(await findByTestId('quick-delivery-slot-button')).toBeTruthy() expect(getByText('ALL')).toBeTruthy() expect(getByTestId('go-to-cart')).toBeTruthy() }) it('SLOT-05: the drawer lists ALL plus every store and styles the active one', async () => { const { getByText, findByText } = renderLayout({ slotId: '1849', storeId: '1' }) await load() expect(getByText('ALL')).toBeTruthy() const active = storeNameStyle(await findByText('Freshyo Meat House')) const inactive = storeNameStyle(getByText('Freshyo Greens')) // `font-bold` maps to the RN keyword while `font-medium` maps to a numeric weight. const weight = (value: any) => (value === 'bold' ? 700 : Number(value)) expect(weight(active.fontWeight)).toBeGreaterThan(weight(inactive.fontWeight)) }) it('SLOT-06: a stores document without a list falls back to "Loading..."', async () => { setJsonResponse(storesCacheUrl(1), {}) const { getByText } = renderLayout({ slotId: '1849' }) await load() expect(getByText('Loading...')).toBeTruthy() }) it('SLOT-07: tapping ALL replaces the URL with the base route preserving slotId', async () => { const { getByText } = renderLayout({ slotId: '1849', storeId: '1' }) await load() fireEvent.press(getByText('ALL')) expect(router.replace).toHaveBeenCalledWith(`${BASE_URL}?slotId=1849`) }) it('SLOT-08: tapping a store sets the store and keeps slotId in the route', async () => { const { findByText } = renderLayout({ slotId: '1849' }) await load() fireEvent.press(await findByText('Freshyo Greens')) expect(useSlotStore.getState().storeId).toBe(2) expect(router.replace).toHaveBeenCalledWith(`${BASE_URL}?slotId=1849&storeId=2`) }) it('SLOT-09: changing the delivery slot updates both stores and the URL', async () => { const { getByTestId, findByTestId } = renderLayout({ slotId: '1849' }) await load() fireEvent.press(getByTestId('quick-delivery-slot-button')) fireEvent.press(await findByTestId('quick-delivery-slot-1850')) expect(useQuickDeliveryStore.getState().selectedSlotId).toBe(1850) expect(useSlotStore.getState().slotId).toBe(1850) expect(router.replace).toHaveBeenCalledWith(`${BASE_URL}?slotId=1850`) }) it('SLOT-10: a hidden drawer gets display none in the drawer style', async () => { useQuickDeliveryStore.setState({ isDrawerHidden: true }) renderLayout({ slotId: '1849' }) await load() expect((globalThis as any).__drawerProps.screenOptions.drawerStyle.display).toBe('none') }) it('SLOT-11: the flash layout shows the header, the location bar and no store drawer', async () => { const { getByTestId, getByText } = renderWithProviders(, { auth: false, }) await load() expect(getByText('Delivery in within 1 hour')).toBeTruthy() expect(getByTestId('location-bar')).toBeTruthy() // Store selection moved to tag tabs inside the products screen. expect((globalThis as any).__drawerProps).toBeUndefined() }) it('SLOT-12: pending slots show the slot loading state', async () => { setJsonPending(`${slotsCacheUrl(1)}?v=123`) const { getByText } = renderRoute({ slotId: '1849' }) await load() expect(getByText('Loading slot delivery...')).toBeTruthy() }) it('SLOT-13: a rejected slots request shows the failure state', async () => { setJsonError(`${slotsCacheUrl(1)}?v=123`, new Error('offline')) const { getByText, findByText } = renderRoute({ slotId: '1849' }) await load() expect(await findByText('Oops!')).toBeTruthy() expect(getByText('Failed to load slot delivery')).toBeTruthy() }) it('SLOT-14: an unknown slot id shows "No delivery slot available."', async () => { const { findByText } = renderRoute({ slotId: '9999' }) await load() expect(await findByText('No delivery slot available.')).toBeTruthy() }) it('SLOT-15: the slot renders a card per slot product', async () => { const { getAllByTestId, getByText, findByText } = renderRoute({ slotId: '1849' }) await load() expect(await findByText('Chicken Breast')).toBeTruthy() expect(getAllByTestId('compact-product-card')).toHaveLength(2) expect(getByText('Cucumber')).toBeTruthy() }) it('SLOT-16: a slot product missing from the central store is skipped', async () => { seedSlots( slotsWith([ { id: 2, images: ['chicken.jpg'] }, { id: 999, images: [] }, ]) ) const { getAllByTestId, getByText, queryByText, findByTestId } = renderRoute({ slotId: '1849', }) await load() expect(await findByTestId('slot-detail-page')).toBeTruthy() expect(getAllByTestId('compact-product-card')).toHaveLength(1) expect(getByText('Chicken Breast')).toBeTruthy() expect(queryByText('Cucumber')).toBeNull() }) it('SLOT-17: an out-of-stock slot product is filtered out', async () => { // P_OUT (id 6) is out of stock in the availability document. seedSlots( slotsWith([ { id: 2, images: ['chicken.jpg'] }, { id: 6, images: ['mutton.jpg'] }, ]) ) const { getAllByTestId, getByText, queryByText, findByTestId } = renderRoute({ slotId: '1849', }) await load() expect(await findByTestId('slot-detail-page')).toBeTruthy() expect(getAllByTestId('compact-product-card')).toHaveLength(1) expect(getByText('Chicken Breast')).toBeTruthy() expect(queryByText('Mutton')).toBeNull() }) it('SLOT-18: a store filter keeps only that store\'s slot products', async () => { seedCentralStores({ products: MERGED_PRODUCTS.map((product) => product.id === 5 ? { ...product, storeId: 2 } : product ), }) const { getAllByTestId, getByText, queryByText, findByTestId } = renderRoute({ slotId: '1849', storeId: '1', }) await load() expect(await findByTestId('slot-detail-page')).toBeTruthy() expect(getAllByTestId('compact-product-card')).toHaveLength(1) expect(getByText('Chicken Breast')).toBeTruthy() expect(queryByText('Cucumber')).toBeNull() }) it('SLOT-19: a store filter with no matches shows the store empty copy', async () => { const { getByText, findByTestId } = renderRoute({ slotId: '1849', storeId: '2' }) await load() expect(await findByTestId('slot-detail-page')).toBeTruthy() expect(getByText('No products from this store in this slot.')).toBeTruthy() }) it('SLOT-20: without a store filter an empty slot list renders no empty copy', async () => { seedSlots(slotsWith([{ id: 999, images: [] }])) const { queryByTestId, queryByText, findByTestId } = renderRoute({ slotId: '1849', }) await load() expect(await findByTestId('slot-detail-page')).toBeTruthy() expect(queryByTestId('compact-product-card')).toBeNull() expect(queryByText('No products from this store in this slot.')).toBeNull() }) it('SLOT-21: tapping add schedules the product for the slot and alerts', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const { getAllByTestId, findAllByTestId } = renderRoute( { slotId: '1849' }, createMutationQueryClient() ) await load() await findAllByTestId('compact-card-add') fireEvent.press(getAllByTestId('compact-card-add')[0]) await waitFor(() => expect(JSON.parse(__snapshot().cart_items ?? '[]')).toHaveLength(1) ) const line = JSON.parse(__snapshot().cart_items)[0] expect(line.skuId).toBe(2) expect(line.quantity).toBe(1) expect(line.slotId).toBe(1849) const expectedTime = dayjs(slot1849().deliveryTime).format('ddd, DD MMM • h:mm A') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith( 'Added to Cart', `Added Chicken Breast for delivery at ${expectedTime}` ) ) alertSpy.mockRestore() }) it('SLOT-22: a falsy slot id is sent as the 0 payload slot', async () => { seedSlots( slotsWith([ { id: 2, images: ['chicken.jpg'] }, { id: 5, images: ['cucumber.jpg'] }, ], 0) ) const { getAllByTestId, findAllByTestId } = renderRoute( { slotId: '0' }, createMutationQueryClient() ) await load() await findAllByTestId('compact-card-add') fireEvent.press(getAllByTestId('compact-card-add')[0]) await waitFor(() => expect(JSON.parse(__snapshot().cart_items ?? '[]')).toHaveLength(1) ) expect(JSON.parse(__snapshot().cart_items)[0].slotId).toBe(0) }) it('SLOT-23: tapping a card pushes the home product detail route', async () => { const { getAllByTestId, findAllByTestId } = renderRoute({ slotId: '1849' }) await load() await findAllByTestId('compact-product-card') fireEvent.press(getAllByTestId('compact-product-card')[0]) expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/product-detail/2') }) it('SLOT-24: the card shows the price with the market strikethrough', async () => { const { getByText, findByText } = renderRoute({ slotId: '1849' }) await load() // P_CHICKEN: price 215, marketPrice 220. expect(await findByText('₹215')).toBeTruthy() expect(getByText('₹220')).toBeTruthy() }) it('SLOT-25: a combo card hides the quantity line', async () => { seedSlots(slotsWith([{ id: 150, images: ['combo.jpg'] }])) const { getByText, queryByText, findByText } = renderRoute({ slotId: '1849' }) await load() expect(await findByText('Family Combo')).toBeTruthy() expect(getByText('₹599')).toBeTruthy() expect(queryByText(/Quantity:/)).toBeNull() }) it('SLOT-26: an out-of-stock card never renders, so no overlay is shown', async () => { // SlotProducts filters out-of-stock slot products before rendering, so the // card overlay in CompactProductCard is currently unreachable. seedSlots(slotsWith([{ id: 6, images: ['mutton.jpg'] }])) const { queryByText, queryByTestId, findByTestId } = renderRoute({ slotId: '1849' }) await load() expect(await findByTestId('slot-detail-page')).toBeTruthy() expect(queryByText('Mutton')).toBeNull() expect(queryByTestId('compact-product-card')).toBeNull() }) it('SLOT-27: a product without images renders without crashing', async () => { seedSlots(slotsWith([{ id: 9, images: [] }])) const { findByText } = renderRoute({ slotId: '1849' }) await load() expect(await findByText('No Image Item')).toBeTruthy() }) it('SLOT-28: the slot products hide the tab bar through useHideTabNav', async () => { renderRoute({ slotId: '1849' }) await load() expect(useAppStore.getState().hideTabsNav.quick_delivery).toBe(true) }) it('SLOT-29: pull to refresh is a no-op on the slot list', async () => { const { UNSAFE_getAllByType, findByTestId } = renderRoute({ slotId: '1849' }) await load() await findByTestId('slot-detail-page') const before = jsonCallsFor(`${slotsCacheUrl(1)}?v=123`).length await act(async () => { UNSAFE_getAllByType(RefreshControl)[0].props.onRefresh() }) await flush(3) expect(jsonCallsFor(`${slotsCacheUrl(1)}?v=123`).length).toBe(before) }) })