/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 25 — "Prominent API hooks" (`tests/lib/prominent-api-hooks.test.tsx`). * * API-01..19: the regional discovery layer (`src/hooks/prominent-api-hooks.ts`). * CDN URLs are asserted through the `fetch-json` mock (`jsonCallsFor`), and the * tRPC input through the procedure registry (`lastProcedureInput`). * * Location is forced `denied` so the `useRegion()` startup check never overrides * the seeded region/bound while a hook is under test. */ import * as React from 'react' import { act, waitFor } from '@testing-library/react-native' import { resetAllMocks } from '../helpers/reset' import { renderWithProviders, flush, seedRegion, seedSelectedAddress, } from '../helpers/test-utils' import { setJsonResponse, setJsonError, jsonCalls, jsonCallsFor, } from '../mocks/fetch-json' import { setProcedure, lastProcedureInput, procedureCallCount, } from '../mocks/trpc-client' import { __set as setSecureItem, __snapshot as secureSnapshot } from '../mocks/secure-store-mock' import { __setAuthState } from '../mocks/auth-context' import { __configure as configureLocation } from '../mocks/expo-location-mock' import { useGetEssentialConsts, useRegionalConsts, useAllProducts, useAvailability, useStores, useSlots, useStoreWithProducts, } from '@/src/hooks/prominent-api-hooks' import { useRegionStore } from '@/src/store/regionStore' import { A1, A2, AVAILABILITY, AVAILABILITY_RESPONSE, CONSTS, PRODUCTS, PRODUCTS_RESPONSE, REGION_1, REGION_2, SLOTS_RESPONSE, STORES_RESPONSE, STORE_DETAIL_1, availabilityCacheUrl, productsCacheUrl, slotsCacheUrl, storeDetailCacheUrl, storesCacheUrl, } from '../fixtures' jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) interface Probe { element: React.ReactElement result: { current: T } } function makeProbe(hook: () => T): Probe { const result: { current: T } = { current: null as any } const Probe = () => { result.current = hook() return null } return { element: React.createElement(Probe), result } } describe('prominent API hooks', () => { beforeEach(() => { resetAllMocks() configureLocation({ permission: 'denied' }) seedRegion(REGION_1 as any, 7) }) it('API-01: queries essential consts for the active bound and reads the threshold', async () => { const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data).toBeTruthy()) expect(lastProcedureInput('common.essentialConsts')).toEqual({ boundId: 7 }) expect(result.current.data!.freeDeliveryThreshold).toBe(249) }) it('API-02: a same-region selected address bound overrides the active bound', async () => { __setAuthState({ isAuthenticated: true, isLoading: false }) seedSelectedAddress(A1.id) setProcedure('user.address.getUserAddresses', { data: { data: [{ ...A1, boundId: 8 }] } }) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(lastProcedureInput('common.essentialConsts')).toEqual({ boundId: 8 })) expect(result.current.data).toBeTruthy() }) it('API-03: a selected address in another region is ignored', async () => { __setAuthState({ isAuthenticated: true, isLoading: false }) seedSelectedAddress(A2.id) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data).toBeTruthy()) // A2 belongs to region 2, so the region-1 active bound (7) wins. expect(lastProcedureInput('common.essentialConsts')).toEqual({ boundId: 7 }) }) it('API-04: with no region/bound the consts query stays disabled', async () => { useRegionStore.getState().clearRegion() const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) await flush(2) expect(procedureCallCount('common.essentialConsts')).toBe(0) expect(result.current.isLoading).toBe(false) }) it('API-05: a cached consts payload per bound is a placeholder; corrupt cache is ignored', async () => { // Keep the request in flight: a procedure that resolves `undefined` lands as // a successful (empty) query result, which would override placeholderData. setProcedure('common.essentialConsts', { mode: 'pending' }) // Corrupt cache must not throw and must surface no placeholder. setSecureItem('essential_consts_b7', 'not-json') const corrupt = makeProbe(() => useGetEssentialConsts()) const corruptView = renderWithProviders(corrupt.element, { auth: false }) await flush(2) expect(corrupt.result.current.data).toBeUndefined() corruptView.unmount() // A valid cached payload is served immediately as placeholder data. setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 999 })) const cached = makeProbe(() => useGetEssentialConsts()) renderWithProviders(cached.element, { auth: false }) await waitFor(() => expect(cached.result.current.data?.freeDeliveryThreshold).toBe(999)) }) it('API-06: the consts cache is keyed per bound (no cross-bound leak)', async () => { // Keep the request in flight so the bound-keyed cache stays the placeholder. setProcedure('common.essentialConsts', { mode: 'pending' }) setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 })) setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 8, freeDeliveryThreshold: 222 })) seedRegion(REGION_1 as any, 8) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.freeDeliveryThreshold).toBe(222)) expect(result.current.data!.freeDeliveryThreshold).not.toBe(111) }) it('API-20: switching bounds never persists the previous bound snapshot under the new key', async () => { // The request never settles, so the only data the hook can hold for bound 8 // is whatever was carried over from bound 7. setProcedure('common.essentialConsts', { mode: 'pending' }) setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 })) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.freeDeliveryThreshold).toBe(111)) await flush(2) act(() => { useRegionStore.getState().setRegion(REGION_1 as any, 8) }) await flush(2) // Before the fix the b7 placeholder was written to essential_consts_b8 on // the switch render, leaving bound 8 with bound 7's fees after a failure. expect(secureSnapshot().essential_consts_b8).toBeUndefined() }) it('API-21: a snapshot stored under the wrong bound is ignored', async () => { setProcedure('common.essentialConsts', { mode: 'pending' }) setSecureItem( 'essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 }) ) seedRegion(REGION_1 as any, 8) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) await flush(2) expect(result.current.data).toBeUndefined() }) it('API-07: builds the versioned products CDN URL', async () => { setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE) setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1)) expect(jsonCallsFor(productsCacheUrl())).toEqual([productsCacheUrl(1, 12)]) }) it('API-08: builds the availability-versioned CDN URL', async () => { setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE) const { element, result } = makeProbe(() => useAvailability()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.availability).toBeTruthy()) expect(jsonCallsFor(availabilityCacheUrl())).toEqual([availabilityCacheUrl(1, 34)]) }) it('API-09: builds the slots CDN URL with the ?v=123 suffix', async () => { const slotsUrl = `${slotsCacheUrl()}?v=123` setJsonResponse(slotsUrl, SLOTS_RESPONSE) const { element, result } = makeProbe(() => useSlots()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.slots).toBeTruthy()) expect(jsonCallsFor(slotsUrl)).toEqual([slotsUrl]) }) it('API-10: builds the versioned stores CDN URL', async () => { setJsonResponse(storesCacheUrl(), STORES_RESPONSE) const { element, result } = makeProbe(() => useStores()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.stores).toBeTruthy()) expect(jsonCallsFor(storesCacheUrl())).toEqual([storesCacheUrl(1, 12)]) }) it('API-11: builds the versioned per-store detail CDN URL', async () => { setJsonResponse(storeDetailCacheUrl(2), STORE_DETAIL_1) const { element, result } = makeProbe(() => useStoreWithProducts(2)) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.store).toBeTruthy()) expect(jsonCallsFor(storeDetailCacheUrl(2))).toEqual([storeDetailCacheUrl(2, 1, 12)]) }) it('API-12: missing URL parts disable the hook and issue no fetch', async () => { setProcedure('common.essentialConsts', { data: { ...CONSTS, assetsDomain: null } }) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await flush(3) expect(jsonCalls()).toHaveLength(0) expect(result.current.isLoading).toBe(false) }) it('API-13: merges the availability row into each product', async () => { const availability = AVAILABILITY.map((entry) => entry.id === 5 ? { ...entry, isSuspended: true } : entry ) setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE) setJsonResponse(availabilityCacheUrl(), { availability, count: availability.length }) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1)) const byId = (id: number): any => result.current.data!.products.find((p: any) => p.id === id) expect(byId(8)).toMatchObject({ price: 90, marketPrice: 100, flashPrice: 75, isFlashAvailable: true, }) expect(byId(6).isOutOfStock).toBe(true) expect(byId(7).isOffer).toBe(true) expect(byId(5).isSuspended).toBe(true) }) it('API-14: a product without an availability row gets zeroed defaults', async () => { const availability = AVAILABILITY.filter((entry) => entry.id !== 10) setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE) setJsonResponse(availabilityCacheUrl(), { availability, count: availability.length }) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1)) const product = result.current.data!.products.find((p: any) => p.id === 10) as any expect(product).toMatchObject({ price: 0, marketPrice: null, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: false, }) }) it('API-15: combo-only SKUs are filtered out of the merged list', async () => { setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE) setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1)) expect(result.current.data!.products.some((p: any) => p.id === 149)).toBe(false) }) it('API-16: a products fetch error is surfaced', async () => { setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE) setJsonError(productsCacheUrl(), new Error('offline')) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.isError).toBe(true)) expect(result.current.error?.message).toBe('offline') }) it('API-17: when availability fails the products still render with defaults (current)', async () => { setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE) setJsonError(availabilityCacheUrl(), new Error('avail-down')) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1)) // The products query itself succeeded; each row falls back to the zeroed // defaults because its availability entry was never fetched. expect(result.current.isError).toBe(false) const chicken = result.current.data!.products.find((p: any) => p.id === 2) as any expect(chicken.price).toBe(0) expect(chicken.marketPrice).toBeNull() expect(chicken.isFlashAvailable).toBe(false) }) it('API-18: a region change produces a new CDN URL / query key', async () => { setProcedure('common.essentialConsts', { impl: () => ({ ...CONSTS, regionId: useRegionStore.getState().selectedRegionId }), }) setJsonResponse(productsCacheUrl(1), PRODUCTS_RESPONSE) setJsonResponse(availabilityCacheUrl(1), AVAILABILITY_RESPONSE) setJsonResponse(productsCacheUrl(2), PRODUCTS_RESPONSE) setJsonResponse(availabilityCacheUrl(2), AVAILABILITY_RESPONSE) const { element, result } = makeProbe(() => useAllProducts()) renderWithProviders(element, { auth: false }) await waitFor(() => expect(jsonCallsFor(productsCacheUrl(1))).toHaveLength(1)) await act(async () => { useRegionStore.getState().setRegion(REGION_2 as any, 8) }) await waitFor(() => expect(jsonCallsFor(productsCacheUrl(2))).toHaveLength(1)) await waitFor(() => expect(result.current.data).toBeTruthy()) }) it('API-19: useRegionalConsts passes through the essential consts data', async () => { const { element, result } = makeProbe(() => { const essentialConsts = useGetEssentialConsts() const regionalConsts = useRegionalConsts() return { essentialConsts, regionalConsts } }) renderWithProviders(element, { auth: false }) await waitFor(() => expect(result.current.regionalConsts).toBeTruthy()) expect(result.current.regionalConsts).toEqual(result.current.essentialConsts.data) }) })