/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 8.3 — Flash products (`tests/pages/flash-products.test.tsx`, * FLASH-01..18). * * The page is `flash-delivery/(products)/index.tsx` plus `FlashDeliveryProducts` * in `components/SlotSpecificView.tsx`. Product eligibility comes from the * central slot store (`isFlashAvailable` / `isOutOfStock`) and the catalogue from * the CDN products document, so both are seeded per case. */ import * as React from 'react' import { Alert, RefreshControl } from 'react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native' import { QueryClient } from '@tanstack/react-query' import { StorageServiceCasual } from 'common-ui' import FlashDeliveryView from '@/app/(drawer)/(tabs)/flash-delivery/(products)/index' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashCartStore } from '@/src/store/flashCartStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { flush, renderWithProviders, seedBoot, } 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 { AVAILABILITY, P_FLASH, PRODUCT_AVAILABILITY, PRODUCTS_RESPONSE, SLOTS, productsCacheUrl, } from '../fixtures' const FLASH_CART_ROUTE = '/(drawer)/(tabs)/flash-delivery/(cart)/cart' const SEARCH_INPUT = 'flash-product-search-input' type AvailabilityEntry = (typeof AVAILABILITY)[number] /** Availability document with per-id overrides (flash/stock flags). */ function availabilityWith(overrides: Record>) { return AVAILABILITY.map((entry) => overrides[entry.id] ? { ...entry, ...overrides[entry.id] } : entry ) } /** Drive the flash eligibility map straight into the central slot store. */ function seedFlashAvailability(entries: any[]) { useCentralSlotStore.getState().setSlotsData(SLOTS as any, PRODUCT_AVAILABILITY as any, entries as any) } /** Product catalogue with per-id store overrides (the store filter reads this doc). */ function seedProductsInStores(stores: Record) { setJsonResponse(productsCacheUrl(), { ...PRODUCTS_RESPONSE, products: PRODUCTS_RESPONSE.products.map((product) => stores[product.id] ? { ...product, storeId: stores[product.id] } : product ), }) } async function load() { await flush(3) } function renderFlash(params: Record = {}, queryClient?: QueryClient) { __setParams(params) return renderWithProviders(, { auth: false, queryClient }) } /** * Flash 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 }, }, }) } describe('Flash products (FLASH)', () => { beforeEach(() => { resetAllMocks() seedBoot() }) it('FLASH-01: with a storeId a pending request shows the flash loading state', async () => { setJsonPending(productsCacheUrl()) const { getByText } = renderFlash({ storeId: '1' }) await load() expect(getByText('Loading 1 Hr Delivery...')).toBeTruthy() }) it('FLASH-02: with a storeId a failed request shows the flash failure state', async () => { setJsonError(productsCacheUrl(), new Error('offline')) const { getByText } = renderFlash({ storeId: '1' }) await load() expect(getByText('Oops!')).toBeTruthy() expect(getByText('Failed to load 1 Hr Delivery')).toBeTruthy() }) it('FLASH-03: without a storeId there is no loading gate, just the empty copy', async () => { setJsonPending(productsCacheUrl()) const { getByText, queryByText } = renderFlash() await load() expect(queryByText('Loading 1 Hr Delivery...')).toBeNull() expect(getByText('No 1 Hr Delivery products available.')).toBeTruthy() }) it('FLASH-04: only flash-available, in-stock products are listed', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true, isOutOfStock: true }, 5: { isFlashAvailable: true }, }) ) const { getByText, queryByText } = renderFlash({ storeId: '1' }) await load() expect(getByText('Paneer')).toBeTruthy() expect(getByText('Cucumber')).toBeTruthy() // Flash available but out of stock. expect(queryByText('Chicken Breast')).toBeNull() expect(queryByText('Mutton')).toBeNull() }) it('FLASH-05: a storeId keeps only that store\'s flash products', async () => { seedProductsInStores({ 5: 2 }) seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) const { getByText, queryByText } = renderFlash({ storeId: '1' }) await load() expect(getByText('Paneer')).toBeTruthy() expect(queryByText('Cucumber')).toBeNull() }) it('FLASH-06: the search box filters case-insensitively on a substring', async () => { seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) const { getByTestId, getByText, queryByText } = renderFlash() await load() expect(getByText('Paneer')).toBeTruthy() fireEvent.changeText(getByTestId(SEARCH_INPUT), 'cuc') expect(getByText('Cucumber')).toBeTruthy() expect(queryByText('Paneer')).toBeNull() }) it('FLASH-07: a whitespace-only search keeps every flash product', async () => { seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) const { getByTestId, getByText } = renderFlash() await load() fireEvent.changeText(getByTestId(SEARCH_INPUT), ' ') expect(getByText('Cucumber')).toBeTruthy() expect(getByText('Paneer')).toBeTruthy() }) it('FLASH-08: no eligible products shows the flash empty copy', async () => { setJsonResponse(productsCacheUrl(), { products: [], count: 0, tags: [] }) const { getByText } = renderFlash({ storeId: '1' }) await load() expect(getByText('No 1 Hr Delivery products available.')).toBeTruthy() }) it('FLASH-09: tapping add writes to the flash cart and alerts for 1hr delivery', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const { getAllByTestId } = renderFlash({ storeId: '1' }, createMutationQueryClient()) await load() fireEvent.press(getAllByTestId('compact-card-add')[0]) await waitFor(() => expect(JSON.parse(__snapshot().flash_cart_items ?? '[]')).toHaveLength(1) ) const line = JSON.parse(__snapshot().flash_cart_items)[0] expect(line.skuId).toBe(8) expect(line.quantity).toBe(1) expect(line.slotId).toBe(0) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Added to Cart', 'Added Paneer for delivery in 1hr') ) alertSpy.mockRestore() }) it('FLASH-10: tapping a card pushes the flash product-detail route', async () => { const { getAllByTestId } = renderFlash({ storeId: '1' }) await load() fireEvent.press(getAllByTestId('compact-product-card')[0]) expect(router.push).toHaveBeenCalledWith( '/(drawer)/(tabs)/flash-delivery/product-detail/8' ) }) it('FLASH-11: the card uses the flash price when present and the regular one otherwise', async () => { seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) const { getByText } = renderFlash() await load() // P_FLASH (8): price 90, flashPrice 75. P_CUCUMBER (5): price 15, no flash price. expect(getByText('₹75')).toBeTruthy() expect(getByText('₹15')).toBeTruthy() }) it('FLASH-12: pull to refresh refetches the products document', async () => { const { UNSAFE_getAllByType } = renderFlash({ storeId: '1' }) await load() const before = jsonCallsFor(productsCacheUrl()).length await act(async () => { UNSAFE_getAllByType(RefreshControl)[0].props.onRefresh() }) await flush(3) expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before) }) it('FLASH-13: a storeId of 0 is falsy and falls back to the all-stores list', async () => { seedProductsInStores({ 5: 2 }) seedFlashAvailability(availabilityWith({ 5: { isFlashAvailable: true } })) const { getByText } = renderFlash({ storeId: '' }) await load() expect(getByText('Paneer')).toBeTruthy() expect(getByText('Cucumber')).toBeTruthy() }) it('FLASH-14: a queued flash product is auto-added once and alerts after 300ms', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) useFlashCartStore.getState().setAddedFlashProduct({ productId: 8, product: P_FLASH }) renderFlash({ storeId: '1' }, createMutationQueryClient()) await load() await waitFor(() => expect(useFlashCartStore.getState().addedFlashProduct).toBeNull()) expect(JSON.parse(__snapshot().flash_cart_items ?? '[]')).toHaveLength(1) expect(alertSpy).not.toHaveBeenCalled() await waitFor( () => expect(alertSpy).toHaveBeenCalledWith( 'Added to Cart', 'Added Paneer for delivery in 1hr' ), { timeout: 2000 } ) expect(alertSpy).toHaveBeenCalledTimes(1) alertSpy.mockRestore() }) it('FLASH-15: a failed auto-add keeps the dialog product and skips the alert', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) // Fail only the flash cart write: the essential-consts cache write is // fire-and-forget and would otherwise surface as an unhandled rejection. const originalSetItem = StorageServiceCasual.setItem const setItem = jest .spyOn(StorageServiceCasual, 'setItem') .mockImplementation(async (key: string, value: string) => { if (key === 'flash_cart_items') throw new Error('boom') return originalSetItem.call(StorageServiceCasual, key, value) }) useFlashCartStore.getState().setAddedFlashProduct({ productId: 8, product: P_FLASH }) renderFlash({ storeId: '1' }, createMutationQueryClient()) await load() expect(useFlashCartStore.getState().addedFlashProduct).not.toBeNull() expect(alertSpy).not.toHaveBeenCalled() setItem.mockRestore() alertSpy.mockRestore() }) it('FLASH-16: focusing with shouldNavigateToCart resets the flag and pushes the flash cart', async () => { useFlashNavigationStore.setState({ shouldNavigateToCart: true }) renderFlash({ storeId: '1' }) await load() expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false) expect(router.push).toHaveBeenCalledWith(FLASH_CART_ROUTE) }) it('FLASH-17: without shouldNavigateToCart the page does not push the cart', async () => { renderFlash({ storeId: '1' }) await load() expect(router.push).not.toHaveBeenCalledWith(FLASH_CART_ROUTE) }) it('FLASH-18: a changed storeId param updates the slot store', async () => { __setParams({ storeId: '1' }) const { rerender } = renderWithProviders(, { auth: false }) await load() expect(useSlotStore.getState().storeId).toBe(1) __setParams({ storeId: '2' }) rerender() expect(useSlotStore.getState().storeId).toBe(2) }) })