/** * Network-layer mocks for the user-ui tests. * * Everything the home page fetches goes through one of two doors: * - tRPC -> global.fetch (common.essentialConsts, user.order.getOrders, ...) * - axios -> the assets CDN (products.json, stores.json, slots.json, availability.json) * * Both are stubbed here and both fail loudly on an unmocked URL, so a new * dependency introduced by app code surfaces as a test failure instead of a * silent empty render. * * The tRPC URL is matched on the procedure path rather than the host, because * BASE_API_URL (@packages/shared) is a local address during development. * `jest.mock('axios')` lives in tests/setup.ts so it is registered before any * app module imports axios. * * Fixtures are imported as JSON rather than read with `fs`: importing a Node * builtin pulls @types/node into the typecheck program, which flips * `setTimeout` from `number` to `NodeJS.Timeout` and breaks unrelated app types. * * NOTE: mock-slots-response.json is a snapshot of one real day, so its dates are * rebased relative to the frozen clock below rather than used as-is. */ import essentialConsts from '../__fixtures__/essentialConsts.json' import availability from './mock-availability-response.json' import products from './mock-products-response.json' import slotsRaw from './mock-slots-response.json' import storeProducts from './mock-store-products-response.json' import stores from './mock-stores-response.json' import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' import { parseTrpcUrl } from './procedures' /** The payload the common.essentialConsts procedure resolves to (unwrapped). */ export const ESSENTIAL_CONSTS_DATA = essentialConsts[0].result.data /** essentialConsts with flash delivery switched on (flash-option tests). */ export const FLASH_ENABLED_CONSTS = { ...ESSENTIAL_CONSTS_DATA, isFlashDeliveryEnabled: true, } /** products.json with no tags and no products (empty-state tests). */ export const EMPTY_PRODUCTS = { products: [], tags: [] } /** Region fixtures returned by common.listRegions (region 1 / Mahabubnagar). */ export const MOCK_REGIONS = [ { id: 1, name: 'Mahabubnagar', description: null, effectiveBoundId: 1 }, ] /** * Default address fixture. Coordinates are mandatory now and the region/bound * are derived from them; returned by user.address.getDefaultAddress and (as a * one-item list) user.address.getUserAddresses when a test doesn't override. */ export const MOCK_ADDRESS = { id: 1, regionId: 1, boundId: 1, name: 'Home', phone: '9876543210', addressLine1: '12 Main Road', addressLine2: null, city: 'Mahabubnagar', state: 'Telangana', isDefault: true, latitude: 16.7488, longitude: 77.9851, } /** A dashboard tag that points at no products (empty-tag-grid test). */ export const EMPTY_TAG = { id: 9999, tagName: 'Empty', tagDescription: null, imageUrl: null, isDashboardTag: true, productIds: [], } /** * The mocked StorageServiceCasual keeps its map at module scope, so the cart * survives from one test to the next. Call from beforeEach. * * `essential_consts` is deliberately NOT cleared here: when it is persisted, * useGetEssentialConsts gets placeholderData synchronously, which * tests/home-page/navigation.test.tsx (real router) relies on. A file that * overrides the constants must clear it itself via resetEssentialConsts(). */ export async function resetStorage() { await StorageServiceCasual.clearAll(['cart_items', 'flash_cart_items']) } /** Clears the persisted essentialConsts so the next render refetches them. */ export async function resetEssentialConsts() { await StorageServiceCasual.clearAll(['essential_consts']) } /** * The slot fixture is a snapshot of a real day. The home page drops slots whose * deliveryTime is not after `dayjs()`, so the fixture would silently expire. * Shift every slot by the same delta so the earliest lands FIRST_SLOT_LEAD_MS * ahead of now, keeping the relative spacing and the freeze-before-delivery * offset intact. Ids and per-slot product lists are untouched. */ const FIRST_SLOT_LEAD_MS = 2 * 60 * 60 * 1000 /** How far in the past the synthetic expired slots freeze. */ const EXPIRED_FREEZE_MS = 2 * 60 * 1000 export const EXPIRED_HOME_SLOT_ID = 9001 export const EXPIRED_DIALOG_SLOT_ID = 9002 const rebaseSlots = (raw: typeof slotsRaw) => { const offset = Date.now() + FIRST_SLOT_LEAD_MS - new Date(raw.slots[0].deliveryTime).getTime() return { ...raw, slots: raw.slots.map((slot) => ({ ...slot, deliveryTime: new Date( new Date(slot.deliveryTime).getTime() + offset ).toISOString(), freezeTime: new Date( new Date(slot.freezeTime).getTime() + offset ).toISOString(), })), } } /** Slots as the app will receive them (rebased), for building expectations. */ export const mockSlots = (() => { const rebased = rebaseSlots(slotsRaw) const now = Date.now() // Slots whose freezeTime has passed but whose delivery is still upcoming. // The backend filters these out (scaffoldSlotsWithProducts) and the cart // dialog filters them out too; these exist so the home strip can be shown to // do the same. Delivery times are picked deliberately: // 9001 earliest -> an unfiltered slot would sort first and fail loudly // instead of hiding beyond the 5-item slice // 9002 latest -> getQuickestSlot (which ignores freezeTime) still // resolves product 23 to its real, earlier slot const expiredSlot = (id: number, deliveryLeadMs: number, productIds: number[]) => ({ id, deliveryTime: new Date(now + deliveryLeadMs).toISOString(), freezeTime: new Date(now - EXPIRED_FREEZE_MS).toISOString(), products: productIds.map((productId) => ({ id: productId, images: [] as string[], })), }) return { ...rebased, slots: [ ...rebased.slots, expiredSlot(EXPIRED_HOME_SLOT_ID, 60 * 60 * 1000, []), expiredSlot(EXPIRED_DIALOG_SLOT_ID, 20 * 60 * 60 * 1000, [23]), ], } })() const productsInAnySlot = new Set() mockSlots.slots.forEach((slot) => slot.products.forEach((p) => productsInAnySlot.add(p.id)) ) const flaggedOutOfStock = new Set( availability.availability.filter((a) => a.isOutOfStock).map((a) => a.id) ) /** * The products the UI should treat as unavailable: flagged out of stock by the * availability cache, or present in no upcoming slot. Mirrors * displayIsOutOfStock / productsByTagId in the page. Combo-only SKUs are * dropped because useAllProducts filters them out. */ export const outOfStockIds = new Set( products.products .filter((p) => !p.isComboOnly) .map((p) => p.id) .filter((id) => flaggedOutOfStock.has(id) || !productsInAnySlot.has(id)) ) export const ESSENTIAL_CONSTS_URL = 'https://worker.freshyo.in/api/trpc/common.essentialConsts?batch=1&input=%7B%220%22%3A%7B%22json%22%3Anull%2C%22meta%22%3A%7B%22values%22%3A%5B%22undefined%22%5D%7D%7D%7D' // Derived by useCacheUrl / useAvailabilityCacheUrl / useSlotsCacheUrl from the // essentialConsts payload above (assetsDomain, apiCacheKey, cacheVersion, // availabilityVersionNum, slotsVersionNum). Cache files are region-owned, so // each URL carries the browsing region (1 = Mahabubnagar in these fixtures). export const PRODUCTS_URL = 'https://assets.freshyo.in/api-cache/regions/1/v-755/products.json' export const AVAILABILITY_URL = 'https://assets.freshyo.in/regions/1/av-72/availability.json' export const STORES_URL = 'https://assets.freshyo.in/api-cache/regions/1/v-755/stores.json' export const SLOTS_URL = 'https://assets.freshyo.in/regions/1/slots/v-401/slots.json?v=123' /** useStoreWithProducts URL for a given store id. */ export const storeDetailUrl = (storeId: number | string) => `https://assets.freshyo.in/api-cache/regions/1/v-755/stores/${storeId}.json` const jsonResponse = (body: unknown) => ({ ok: true, status: 200, statusText: 'OK', headers: new Map(), url: '', json: async () => body, text: async () => JSON.stringify(body), }) const errorResponse = (status: number, message: string) => ({ ok: false, status, statusText: message, headers: new Map(), url: '', json: async () => ({ message }), text: async () => message, }) export interface ApiMockOptions { /** Replace the products.json body entirely (e.g. EMPTY_PRODUCTS). */ products?: unknown /** Append tags to the products.json body's `tags` (empty-tag-grid test). */ extraTags?: unknown[] /** Override the stores.json body. */ stores?: unknown /** Override the stores/.json body (useStoreWithProducts). */ storeProducts?: unknown /** Override the essentialConsts payload (unwrapped procedure data). */ consts?: unknown /** user.order.getOrders data (NextOrderGlimpse). */ orders?: unknown[] /** * tRPC procedure registry: name -> data, or (input) => data. Merged over the * built-in essentials (common.essentialConsts, user.order.getOrders/orders). * An unknown procedure throws, so a new dependency surfaces loudly. */ procedures?: Record unknown)> /** axios.get(products.json) rejects -> the products query errors. */ failProducts?: boolean /** axios.get(stores.json) rejects -> the stores query errors. */ failStores?: boolean /** axios.get(slots.json) rejects -> the slots query errors. */ failSlots?: boolean /** The essentialConsts fetch resolves non-ok -> the consts query errors. */ failConsts?: boolean /** axios.get(products.json) never resolves -> the products query stays loading. */ pendingProducts?: boolean /** axios.get(slots.json) never resolves -> the slots query stays loading. */ pendingSlots?: boolean } /** * Install the fetch + axios stubs and return the handles for assertions. * Call from beforeEach so each test starts from a clean call history. */ export function setupApiMocks(opts: ApiMockOptions = {}) { const axios = require('axios') const constsData = opts.consts ?? ESSENTIAL_CONSTS_DATA const orders = opts.orders ?? [] const baseProducts = (opts.products ?? products) as { tags?: unknown[] } const productsBody = opts.extraTags?.length ? { ...baseProducts, tags: [...(baseProducts.tags ?? []), ...opts.extraTags] } : baseProducts /** Route a CDN file name to its mock response. */ const mockForCacheFile = (url: string): unknown => { if (url.includes('products.json')) return productsBody if (/stores\/\d+\.json/.test(url)) return opts.storeProducts ?? storeProducts if (url.includes('stores.json')) return opts.stores ?? stores if (url.includes('slots.json')) return mockSlots if (url.includes('availability.json')) return availability throw new Error(`[tests] unmocked assets request: ${url}`) } axios.get.mockImplementation(async (url: string) => { const target = String(url) if (target.includes('products.json')) { if (opts.pendingProducts) return new Promise(() => {}) if (opts.failProducts) throw new Error('products request failed') } if (opts.failStores && target.includes('stores')) { throw new Error('stores request failed') } if (target.includes('slots.json')) { if (opts.pendingSlots) return new Promise(() => {}) if (opts.failSlots) throw new Error('slots request failed') } return { data: mockForCacheFile(target), status: 200, statusText: 'OK', headers: {}, config: {}, } }) /** Resolve one procedure name from a (possibly batched) tRPC request. */ const resolveProcedure = (name: string, input: unknown): unknown => { const override = opts.procedures?.[name] if (override !== undefined) { return typeof override === 'function' ? (override as (value: unknown) => unknown)(input) : override } if (name === 'common.essentialConsts') return constsData if (name === 'user.order.getOrders' && opts.orders !== undefined) { return { data: orders } } // Region/location plumbing used by useRegion, the region gate and the // address form. Tests can still override any of these via `procedures`. if (name === 'common.listRegions') return MOCK_REGIONS if (name === 'common.activeBound') return { boundId: 1 } if (name === 'common.resolveRegionByLocation') { return { region: MOCK_REGIONS[0], bound: { id: 1 } } } if (name === 'common.resolveBound') return { boundId: 1 } if (name === 'user.address.getDefaultAddress') return { data: MOCK_ADDRESS } if (name === 'user.address.getUserAddresses') return { data: [MOCK_ADDRESS] } throw new Error( `[tests] unmocked trpc procedure: ${name} (add it to setupApiMocks({ procedures }))` ) } const fetchMock = jest.fn( async (url: string, options?: { method?: string; body?: unknown }) => { const target = String(url) if (opts.failConsts && target.includes('common.essentialConsts')) { return errorResponse(500, 'consts request failed') } // The path after /api/trpc/ is a comma-separated list of procedure names // (httpBatchLink batches every operation issued in the same tick). const calls = parseTrpcUrl(target, options?.body) if (calls.length === 0) { // Presigned S3 uploads (useUploadToObjectStorage) PUT straight to a URL. if (options?.method === 'PUT') return jsonResponse({}) throw new Error(`[tests] unmocked fetch: ${url}`) } const batch = calls.map(({ name, input }) => ({ result: { data: resolveProcedure(name, input) }, })) return jsonResponse(batch) } ) ;(global as unknown as { fetch: unknown }).fetch = fetchMock return { fetchMock, axiosGet: axios.get } }