/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 12 — Offers / order again (`tests/pages/offers.test.tsx`, * OFFER-01..22). * * The page splits the merged catalogue into an "Offers" section (`isOffer`) and * a "Combos" section (`productType === 'combo'`); each section shows six cards * until its own "Show More" is pressed. * * OFFER-20 (`useMarkDataFetchers`) needs a *second* focus, which the shared * navigation mock cannot produce, so it is narrowed with a focus emitter. */ import * as React from 'react' import { DeviceEventEmitter } from 'react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native' import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs' import Offers from '@/app/(drawer)/(tabs)/order-again/index' import { useCartStore } from '@/src/store/cartStore' import { flush, renderWithProviders, seedBoot } 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 { AVAILABILITY, P_CHICKEN, P_NO_IMAGE, P_OUT, PRODUCTS, TAGS, availabilityCacheUrl, productsCacheUrl, } from '../fixtures' /** Focus listeners registered through the (narrowed) navigation mock. */ const mockFocusCallbacks = new Set<() => void>() jest.mock('@react-navigation/native', () => { const React = require('react') const actual = jest.requireActual(__dirname + '/../mocks/react-navigation-mock') return { ...actual, useFocusEffect: (callback: () => void | (() => void)) => { React.useEffect(() => { mockFocusCallbacks.add(callback) const cleanup = callback() return () => { mockFocusCallbacks.delete(callback) if (typeof cleanup === 'function') cleanup() } // eslint-disable-next-line react-hooks/exhaustive-deps }, [callback]) }, } }) /** Simulate the screen being focused again (what `useMarkDataFetchers` reacts to). */ async function emitFocus() { await act(async () => { Array.from(mockFocusCallbacks).forEach((callback) => callback()) }) } const OFFER_PRODUCT_ID = 7 // P_OFFER const COMBO_PRODUCT_ID = 150 // P_COMBO function makeProducts(prefix: string, count: number, idBase: number, productType = 'item') { return Array.from({ length: count }, (_, index) => ({ ...P_CHICKEN, id: idBase + index, name: `${prefix} ${index + 1}`, images: ['item.jpg'], productType, })) } function availabilityEntries(products: any[], overrides: Record = {}) { return products.map((product) => ({ id: product.id, price: 100, marketPrice: 120, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: false, ...overrides, })) } /** Register a bespoke products + availability pair. */ function seedCatalogue(products: any[], availability: any[]) { setJsonResponse(productsCacheUrl(1), { products, count: products.length, tags: TAGS }) setJsonResponse(availabilityCacheUrl(1), { availability, count: availability.length, }) } /** Override individual flags of the default availability document. */ function seedFlaggedAvailability(overrides: Record>) { setJsonResponse(availabilityCacheUrl(1), { availability: AVAILABILITY.map((entry) => overrides[entry.id] ? { ...entry, ...overrides[entry.id] } : entry ), count: AVAILABILITY.length, }) } /** Override fields of individual default products. */ function seedFlaggedProducts(overrides: Record>) { setJsonResponse(productsCacheUrl(1), { products: PRODUCTS.map((product) => overrides[product.id] ? { ...product, ...overrides[product.id] } : product ), count: PRODUCTS.length, tags: TAGS, }) } async function load() { await flush(3) } function renderPage() { return renderWithProviders(, { auth: false, withProductStore: true }) } describe('Offers / order again (OFFER)', () => { beforeEach(() => { resetAllMocks() mockFocusCallbacks.clear() seedBoot() }) it('OFFER-01: pending products show the offers loading state', async () => { setJsonPending(productsCacheUrl()) const { getByText } = renderPage() await waitFor(() => expect(getByText('Loading offers...')).toBeTruthy()) }) it('OFFER-02: a failed products request shows the offers failure state', async () => { setJsonError(productsCacheUrl(), new Error('offline')) const { getByText } = renderPage() await waitFor(() => expect(getByText('Oops!')).toBeTruthy()) expect(getByText('Failed to load offers')).toBeTruthy() }) it('OFFER-03: the loaded page shows both sections with their subtitles', async () => { const { getByText } = renderPage() await load() expect(getByText('Offers')).toBeTruthy() expect(getByText('Great prices on select items')).toBeTruthy() expect(getByText('Combos')).toBeTruthy() expect(getByText('Bundle your favorites and save')).toBeTruthy() }) it('OFFER-04: with no offer products the Offers section shows its empty copy', async () => { seedFlaggedAvailability({ [OFFER_PRODUCT_ID]: { isOffer: false } }) const { getByText } = renderPage() await load() expect(getByText('No offers available right now')).toBeTruthy() expect(getByText('Family Combo')).toBeTruthy() }) it('OFFER-05: with no combos the Combos section shows its empty copy', async () => { seedFlaggedProducts({ [COMBO_PRODUCT_ID]: { productType: 'item' } }) const { getByText } = renderPage() await load() expect(getByText('No combos available right now')).toBeTruthy() expect(getByText('Offer Chicken')).toBeTruthy() }) it('OFFER-06: the Offers section keeps only isOffer products', async () => { seedFlaggedAvailability({ 2: { isOffer: true }, [OFFER_PRODUCT_ID]: { isOffer: true }, }) const { getByText, queryByText } = renderPage() await load() expect(getByText('Chicken Breast')).toBeTruthy() expect(getByText('Offer Chicken')).toBeTruthy() expect(queryByText('Cucumber')).toBeNull() expect(queryByText('Paneer')).toBeNull() }) it('OFFER-07: the Combos section keeps only combo products', async () => { seedFlaggedProducts({ 5: { productType: 'combo' } }) const { getByText, queryByText } = renderPage() await load() expect(getByText('Cucumber')).toBeTruthy() expect(getByText('Family Combo')).toBeTruthy() // Neither an offer nor a combo, so it stays out of both sections. expect(queryByText('Chicken Breast')).toBeNull() expect(queryByText('Paneer')).toBeNull() }) it('OFFER-08: a product that is both an offer and a combo appears twice', async () => { seedFlaggedAvailability({ [COMBO_PRODUCT_ID]: { isOffer: true } }) const { getAllByText } = renderPage() await load() expect(getAllByText('Family Combo')).toHaveLength(2) }) it('OFFER-09: a section with exactly six products has no Show More', async () => { const offers = makeProducts('Offer', 6, 300) seedCatalogue([...offers], availabilityEntries(offers, { isOffer: true })) const { getAllByTestId, queryByText } = renderPage() await load() expect(getAllByTestId('product-card')).toHaveLength(6) expect(queryByText('Show More')).toBeNull() }) it('OFFER-10: a section with seven products gets a Show More that expands it', async () => { const offers = makeProducts('Offer', 7, 300) seedCatalogue([...offers], availabilityEntries(offers, { isOffer: true })) const { getAllByTestId, getAllByText, getByText, queryByText } = renderPage() await load() expect(getAllByTestId('product-card')).toHaveLength(6) expect(queryByText('Offer 7')).toBeNull() fireEvent.press(getAllByText('Show More')[0]) expect(getByText('Offer 7')).toBeTruthy() expect(getAllByTestId('product-card')).toHaveLength(7) expect(queryByText('Show More')).toBeNull() }) it('OFFER-11: expanding Offers leaves Combos collapsed', async () => { const offers = makeProducts('Offer', 7, 300) const combos = makeProducts('Combo', 7, 400, 'combo') seedCatalogue( [...offers, ...combos], [...availabilityEntries(offers, { isOffer: true }), ...availabilityEntries(combos)] ) const { getAllByText, getByText, queryByText } = renderPage() await load() expect(getAllByText('Show More')).toHaveLength(2) fireEvent.press(getAllByText('Show More')[0]) expect(getByText('Offer 7')).toBeTruthy() expect(queryByText('Combo 7')).toBeNull() expect(getAllByText('Show More')).toHaveLength(1) }) it('OFFER-12: expanding Combos leaves Offers collapsed', async () => { const offers = makeProducts('Offer', 7, 300) const combos = makeProducts('Combo', 7, 400, 'combo') seedCatalogue( [...offers, ...combos], [...availabilityEntries(offers, { isOffer: true }), ...availabilityEntries(combos)] ) const { getAllByText, getByText, queryByText } = renderPage() await load() fireEvent.press(getAllByText('Show More')[1]) expect(getByText('Combo 7')).toBeTruthy() expect(queryByText('Offer 7')).toBeNull() }) it('OFFER-13: an empty catalogue shows both section empty copies', async () => { seedCatalogue([], []) const { getByText } = renderPage() await load() expect(getByText('No offers available right now')).toBeTruthy() expect(getByText('No combos available right now')).toBeTruthy() }) it('OFFER-14: tapping an offer card pushes the order-again detail route', async () => { const { getAllByTestId } = renderPage() await load() fireEvent.press(getAllByTestId('product-card')[0]) expect(router.push).toHaveBeenCalledWith( `/(drawer)/(tabs)/order-again/product-detail/${OFFER_PRODUCT_ID}` ) }) it('OFFER-15: tapping a combo card pushes the same route shape', async () => { seedFlaggedAvailability({ [OFFER_PRODUCT_ID]: { isOffer: false } }) const { getAllByTestId } = renderPage() await load() fireEvent.press(getAllByTestId('product-card')[0]) expect(router.push).toHaveBeenCalledWith( `/(drawer)/(tabs)/order-again/product-detail/${COMBO_PRODUCT_ID}` ) }) it('OFFER-16: the card add icon queues the add-to-cart dialog product', async () => { const { getAllByTestId } = renderPage() await load() fireEvent.press(getAllByTestId('add-to-cart-icon')[0]) expect(useCartStore.getState().addedToCartProduct?.productId).toBe(OFFER_PRODUCT_ID) }) it('OFFER-17: an out-of-stock offer card carries the unavailable badge', async () => { seedCatalogue([P_OUT], [ { id: P_OUT.id, price: 400, marketPrice: 450, flashPrice: null, isFlashAvailable: false, isOutOfStock: true, isSuspended: false, isOffer: true }, ]) const { getAllByTestId, getByText } = renderPage() await load() expect(getByText('Mutton')).toBeTruthy() expect(getAllByTestId('out-of-stock-badge')).toHaveLength(1) }) it('OFFER-18: a product without images falls back to the image error copy', async () => { seedCatalogue([P_NO_IMAGE], [ { id: P_NO_IMAGE.id, price: 10, marketPrice: null, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: true }, ]) const { getByText } = renderPage() await load() expect(getByText('No Image Item')).toBeTruthy() expect(getByText('No image available')).toBeTruthy() }) it('OFFER-19: a refresh event refetches the products document', async () => { // The page scrolls through a plain ScrollView (no RefreshControl of its own), // so its pull-to-refresh path is `useManualRefresh` listening for the same // global refresh event the tab shells emit. renderPage() await load() const before = jsonCallsFor(productsCacheUrl()).length await act(async () => { DeviceEventEmitter.emit(REFRESH_EVENT) }) await flush(3) expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before) }) it('OFFER-20: a re-focus through useMarkDataFetchers refetches products', async () => { renderPage() await load() const before = jsonCallsFor(productsCacheUrl()).length await emitFocus() await flush(3) expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before) }) it('OFFER-21: the location bar is rendered at the top of the page', async () => { const { getByTestId } = renderPage() await load() expect(getByTestId('location-bar')).toBeTruthy() }) it('OFFER-22: the floating cart bar is rendered', async () => { const { getByTestId, getByText } = renderPage() await load() expect(getByTestId('go-to-cart')).toBeTruthy() expect(getByText('No Items In Cart')).toBeTruthy() }) })