/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 8.3 — Flash products (`tests/pages/flash-products.test.tsx`, * FLASH-01..25). * * The page is `flash-delivery/(products)/index.tsx` plus `FlashDeliveryProducts` * in `components/SlotSpecificView.tsx`. The screen has two independently paged * sections: products by tag (tabs mirror the home page order) and products by * store ("Shop by Store", one tab per store). */ import * as React from 'react' import { Alert, RefreshControl } from 'react-native' import { act, fireEvent, waitFor, within } 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 { useFlashCartStore } from '@/src/store/flashCartStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { flush, renderWithProviders, seedBoot, seedEmptyCatalogue } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { router } 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, TAGS, productsCacheUrl, storesCacheUrl, } from '../fixtures' const FLASH_CART_ROUTE = '/(drawer)/(tabs)/flash-delivery/(cart)/cart' const SEARCH_INPUT = 'flash-product-search-input' const EMPTY_COPY = 'No 1 Hr Delivery products available.' 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) } /** Replace the cache's tag document (tabs and per-tag product ids). */ function seedTags(tags: any[]) { setJsonResponse(productsCacheUrl(), { ...PRODUCTS_RESPONSE, tags }) } async function load() { await flush(3) } function renderFlash(queryClient?: QueryClient) { return renderWithProviders(, { auth: false, queryClient, withProductStore: true }) } type FlashView = ReturnType /** Product assertions are scoped: both sections can show the same card. */ const tagSection = (view: FlashView) => within(view.getByTestId('flash-tag-section')) const storeSection = (view: FlashView) => within(view.getByTestId('flash-store-section')) /** * 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: a pending products request shows the flash loading state', async () => { setJsonPending(productsCacheUrl()) const { getByText } = renderFlash() await load() expect(getByText('Loading 1 Hr Delivery...')).toBeTruthy() }) it('FLASH-02: a failed request with no cache shows the flash failure state', async () => { seedEmptyCatalogue() setJsonError(productsCacheUrl(), new Error('offline')) const { getByText } = renderFlash() await load() expect(getByText('Oops!')).toBeTruthy() expect(getByText('Failed to load 1 Hr Delivery')).toBeTruthy() }) it('FLASH-03: the first tag is selected and the tabs keep the cache order', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 5: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() expect(view.getByTestId('flash-tag-strip')).toBeTruthy() expect(view.getByTestId('flash-tag-tab-1')).toBeTruthy() expect(view.getByTestId('flash-tag-tab-2')).toBeTruthy() // The "Empty" tag has no eligible product, so it gets no tab. expect(view.queryByTestId('flash-tag-tab-3')).toBeNull() // Chicken is tag 1, so its product shows and Vegetables stays out of it. expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy() expect(tagSection(view).queryByText('Cucumber')).toBeNull() }) it('FLASH-04: the active tag keeps only flash-available, in-stock products', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 6: { isFlashAvailable: true, isOutOfStock: true }, 9: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() const grid = tagSection(view) expect(grid.getByText('Chicken Breast')).toBeTruthy() expect(grid.getByText('No Image Item')).toBeTruthy() // Flash available but out of stock. expect(grid.queryByText('Mutton')).toBeNull() }) it('FLASH-05: selecting another tab swaps the feed to that tag', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 5: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy() fireEvent.press(view.getByTestId('flash-tag-tab-2')) expect(tagSection(view).getByText('Cucumber')).toBeTruthy() expect(tagSection(view).queryByText('Chicken Breast')).toBeNull() }) it('FLASH-06: the search box filters case-insensitively within the tag', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 5: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() fireEvent.press(view.getByTestId('flash-tag-tab-2')) fireEvent.changeText(view.getByTestId(SEARCH_INPUT), 'cuc') expect(tagSection(view).getByText('Cucumber')).toBeTruthy() fireEvent.changeText(view.getByTestId(SEARCH_INPUT), 'chick') expect(tagSection(view).getByText(EMPTY_COPY)).toBeTruthy() }) it('FLASH-07: a whitespace-only search keeps every product in the tag', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 9: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() fireEvent.changeText(view.getByTestId(SEARCH_INPUT), ' ') expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy() expect(tagSection(view).getByText('No Image Item')).toBeTruthy() }) it('FLASH-08: tags and stores with no flash products get no tab', async () => { // Only Chicken Breast (tag 1, store 1) is flash-eligible. seedFlashAvailability(availabilityWith({ 2: { isFlashAvailable: true } })) const view = renderFlash() await load() expect(view.getByTestId('flash-tag-tab-1')).toBeTruthy() // Vegetables only sells Cucumber, which is not flash-eligible. expect(view.queryByTestId('flash-tag-tab-2')).toBeNull() expect(view.queryByTestId('flash-tag-tab-3')).toBeNull() // Freshyo Greens has no flash products either. expect(view.getByTestId('flash-store-tab-1')).toBeTruthy() expect(view.queryByTestId('flash-store-tab-2')).toBeNull() }) it('FLASH-09: tapping add writes to the flash cart and alerts for 1hr delivery', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) seedTags([{ ...TAGS[0], productIds: [8] }]) seedFlashAvailability(availabilityWith({ 8: { isFlashAvailable: true } })) const view = renderFlash(createMutationQueryClient()) await load() fireEvent.press(tagSection(view).getAllByTestId('add-to-cart-icon')[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 () => { seedTags([{ ...TAGS[0], productIds: [8] }]) seedFlashAvailability(availabilityWith({ 8: { isFlashAvailable: true } })) const view = renderFlash() await load() fireEvent.press(tagSection(view).getAllByTestId('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 () => { seedTags([{ ...TAGS[0], productIds: [5, 8] }]) seedFlashAvailability( availabilityWith({ 5: { isFlashAvailable: true }, 8: { isFlashAvailable: true } }) ) const view = renderFlash() await load() // P_FLASH (8): price 90, flashPrice 75. P_CUCUMBER (5): price 15, no flash price. expect(tagSection(view).getByText('₹75')).toBeTruthy() expect(tagSection(view).getByText('₹15')).toBeTruthy() }) it('FLASH-12: pull to refresh refetches the products document', async () => { const view = renderFlash() await load() const before = jsonCallsFor(productsCacheUrl()).length await act(async () => { view.UNSAFE_getAllByType(RefreshControl)[0].props.onRefresh() }) await flush(3) expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before) }) it('FLASH-13: without tags the strip is hidden and every flash product shows', async () => { seedTags([]) seedFlashAvailability(availabilityWith({ 8: { isFlashAvailable: true } })) const view = renderFlash() await load() expect(view.queryByTestId('flash-tag-strip')).toBeNull() expect(tagSection(view).getByText('Paneer')).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(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(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() 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() await load() expect(router.push).not.toHaveBeenCalledWith(FLASH_CART_ROUTE) }) it('FLASH-18: switching tags stays client-side and never rewrites the route', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 5: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() fireEvent.press(view.getByTestId('flash-tag-tab-2')) expect(router.replace).not.toHaveBeenCalled() expect(router.push).not.toHaveBeenCalled() }) it('FLASH-19: nine products render first and Show More reveals the rest', async () => { const generated = Array.from({ length: 12 }, (_, index) => ({ ...P_FLASH, id: 800 + index, name: `Flash ${index + 1}`, })) setJsonResponse(productsCacheUrl(), { products: generated, count: generated.length, tags: [{ ...TAGS[0], productIds: generated.map((product) => product.id) }], }) // The generated ids need their own productAvailability rows so the central // slot store builds productSlotsMap entries for them. useCentralSlotStore.getState().setSlotsData( SLOTS as any, generated.map((product) => ({ id: product.id })) as any, generated.map((product) => ({ id: product.id, price: 90, marketPrice: 100, flashPrice: 75, isFlashAvailable: true, isOutOfStock: false, isSuspended: false, isOffer: false, })) as any ) const view = renderFlash() await load() expect(tagSection(view).getAllByTestId('product-card')).toHaveLength(9) fireEvent.press(view.getByTestId('flash-products-show-more')) expect(tagSection(view).getAllByTestId('product-card')).toHaveLength(12) expect(view.queryByTestId('flash-products-show-more')).toBeNull() }) it('FLASH-20: Shop by Store shows a tab only for stores with flash products', async () => { seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 5: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() expect(view.getByText('Shop by Store')).toBeTruthy() expect(view.getByTestId('flash-store-strip')).toBeTruthy() expect(view.getByTestId('flash-store-tab-1')).toBeTruthy() // Freshyo Greens only sells Cucumber, which is not flash-eligible. expect(view.queryByTestId('flash-store-tab-2')).toBeNull() // Both fixtures belong to store 1. expect(storeSection(view).getByText('Chicken Breast')).toBeTruthy() expect(storeSection(view).getByText('Cucumber')).toBeTruthy() }) it('FLASH-21: a store with flash products gets its own tab and grid', async () => { setJsonResponse(productsCacheUrl(), { ...PRODUCTS_RESPONSE, products: PRODUCTS_RESPONSE.products.map((product) => product.id === 5 ? { ...product, storeId: 2 } : product ), }) seedFlashAvailability( availabilityWith({ 2: { isFlashAvailable: true }, 5: { isFlashAvailable: true }, }) ) const view = renderFlash() await load() fireEvent.press(view.getByTestId('flash-store-tab-2')) expect(storeSection(view).getByText('Cucumber')).toBeTruthy() expect(storeSection(view).queryByText('Chicken Breast')).toBeNull() }) it('FLASH-22: with no stores the Shop by Store section is hidden', async () => { setJsonResponse(storesCacheUrl(), { stores: [] }) seedFlashAvailability(availabilityWith({ 2: { isFlashAvailable: true } })) const view = renderFlash() await load() expect(view.queryByText('Shop by Store')).toBeNull() expect(view.queryByTestId('flash-store-strip')).toBeNull() // The tag section still renders. expect(tagSection(view).getByText('Chicken Breast')).toBeTruthy() }) it('FLASH-24: a background refetch leaves the pull-to-refresh spinner idle', async () => { const view = renderFlash() await load() const control = () => view.UNSAFE_getAllByType(RefreshControl)[0] expect(control().props.refreshing).toBe(false) // Something else refetches the catalogue (remount after the stale window, // an invalidation, a version bump). It must not drive the user's control. setJsonPending(productsCacheUrl()) await act(async () => { void view.queryClient.refetchQueries({ queryKey: ['all-products'] }) }) await flush(2) expect(control().props.refreshing).toBe(false) }) it('FLASH-25: pulling down keeps the spinner up until the refresh settles', async () => { const view = renderFlash() await load() setJsonPending(productsCacheUrl()) await act(async () => { void view.UNSAFE_getAllByType(RefreshControl)[0].props.onRefresh() }) await flush(1) expect(view.UNSAFE_getAllByType(RefreshControl)[0].props.refreshing).toBe(true) }) })