/* eslint-disable @typescript-eslint/no-explicit-any */ /** * ROUTE-*, JWT-*, TRPC-*, HIDE-*, PSI-*, PENDING-01..04, FETCH-01..04 from * JEST-TEST-CASES.md section 25. * * Route/auth-gating cases use the deterministic `auth-context` mock. The trpc * link and `fetch-json` cases load the *real* modules (the jest moduleNameMapper * only rewrites the `@/src/...` bare specifier, so requiring the file with an * explicit extension gives us the real implementation and a shared registry). */ import * as React from 'react' import { Text, DeviceEventEmitter } from 'react-native' import { act, waitFor } from '@testing-library/react-native' import axios from 'axios' import { StorageServiceCasual } from 'common-ui' import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs' import { useAuthenticatedRoute } from '@/hooks/useAuthenticatedRoute' import { saveAuthToken, getAuthToken, deleteAuthToken, saveUserId, getUserId, AUTH_TOKEN_KEY, USER_ID_KEY, } from '@/hooks/useJWT' import { useHideTabNav } from '@/src/hooks/useHideTabNav' import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier' import { savePendingAddress, getPendingAddress, clearPendingAddress, } from '@/src/lib/pending-address' import { useAppStore } from '@/src/store/appStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore' import constants from '@/src/constants' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { router } from '../mocks/expo-router-mock' import { __set, __snapshot } from '../mocks/secure-store-mock' import { __setAuthState } from '../mocks/auth-context' import { TEST_JWT } from '../fixtures' // Real implementations (moduleNameMapper only matches the extension-less specifier). const realTrpcClient: any = require('../../src/trpc-client.ts').trpcClient const realFetchJson: any = require('../../src/lib/fetch-json.ts') const originalFetch: any = (global as any).fetch jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) /* -------------------------------------------------------------------------- */ /* ROUTE-01..04 */ /* -------------------------------------------------------------------------- */ function RouteProbe({ options }: { options?: any }) { useAuthenticatedRoute(options) return route } describe('useAuthenticatedRoute', () => { beforeEach(() => resetAllMocks()) it('ROUTE-01: does not redirect while auth is loading', async () => { __setAuthState({ isLoading: true, isAuthenticated: false }) renderWithProviders(, { auth: false }) await flush() expect(router.push).not.toHaveBeenCalled() expect(__snapshot()[constants.AUTH_REDIRECT_KEY]).toBeUndefined() }) it('ROUTE-02: does not redirect an authenticated user', async () => { __setAuthState({ isLoading: false, isAuthenticated: true }) renderWithProviders(, { auth: false }) await flush() expect(router.push).not.toHaveBeenCalled() expect(__snapshot()[constants.AUTH_REDIRECT_KEY]).toBeUndefined() }) it('ROUTE-03: stores redirect state and pushes login when unauthenticated', async () => { __setAuthState({ isLoading: false, isAuthenticated: false }) renderWithProviders(, { auth: false, }) await waitFor(() => expect(router.push).toHaveBeenCalledWith('/(auth)/login')) const stored = JSON.parse(__snapshot()[constants.AUTH_REDIRECT_KEY]) expect(stored.targetUrl).toBe('/orders') expect(stored.queryParams).toEqual({ id: 1 }) expect(typeof stored.timestamp).toBe('number') }) it('ROUTE-04: still pushes login when the storage write fails', async () => { __setAuthState({ isLoading: false, isAuthenticated: false }) const spy = jest .spyOn(StorageServiceCasual, 'setItem') .mockRejectedValueOnce(new Error('quota')) renderWithProviders(, { auth: false }) await waitFor(() => expect(router.push).toHaveBeenCalledWith('/(auth)/login')) spy.mockRestore() }) }) /* -------------------------------------------------------------------------- */ /* JWT-01..03 */ /* -------------------------------------------------------------------------- */ describe('useJWT', () => { beforeEach(() => resetAllMocks()) it('JWT-01: round-trips the auth token through save/get/delete', async () => { await saveAuthToken('token-1') expect(await getAuthToken()).toBe('token-1') await deleteAuthToken() expect(await getAuthToken()).toBeNull() }) it('JWT-02: round-trips the userId', async () => { await saveUserId('42') expect(await getUserId()).toBe('42') }) it('JWT-03: uses the authToken/userId storage keys', async () => { expect(AUTH_TOKEN_KEY).toBe('authToken') expect(USER_ID_KEY).toBe('userId') await saveAuthToken('token-1') await saveUserId('7') expect(__snapshot()[AUTH_TOKEN_KEY]).toBe('token-1') expect(__snapshot()[USER_ID_KEY]).toBe('7') }) }) /* -------------------------------------------------------------------------- */ /* TRPC-01..06 (real src/trpc-client) */ /* -------------------------------------------------------------------------- */ function makeResponse(status: number, body: any) { return { status, ok: status >= 200 && status < 300, json: async () => body, clone: () => ({ json: async () => body }), headers: { get: () => 'application/json' }, text: async () => JSON.stringify(body), } } describe('trpc client link', () => { beforeEach(() => resetAllMocks()) afterEach(() => { ;(global as any).fetch = originalFetch }) it('TRPC-01: emits force-logout on a 401 UNAUTHORIZED response', async () => { const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit') ;(global as any).fetch = jest.fn(async () => makeResponse(401, [{ error: { message: 'UNAUTHORIZED' } }]) ) await realTrpcClient.common.healthCheck.query().catch(() => undefined) await flush() expect(emitSpy).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT) emitSpy.mockRestore() }) it('TRPC-02: does not emit on a 401 with another message', async () => { const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit') ;(global as any).fetch = jest.fn(async () => makeResponse(401, [{ error: { message: 'TOKEN_EXPIRED' } }]) ) await realTrpcClient.common.healthCheck.query().catch(() => undefined) await flush() expect(emitSpy).not.toHaveBeenCalledWith(FORCE_LOGOUT_EVENT) emitSpy.mockRestore() }) it('TRPC-03: does not emit on a 500 response', async () => { const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit') ;(global as any).fetch = jest.fn(async () => makeResponse(500, [])) await realTrpcClient.common.healthCheck.query().catch(() => undefined) await flush() expect(emitSpy).not.toHaveBeenCalled() emitSpy.mockRestore() }) it('TRPC-04: sends a bearer header only when a token is stored', async () => { const fetchMock = jest.fn(async () => makeResponse(200, [{ result: { data: { ok: true } } }]) ) ;(global as any).fetch = fetchMock await saveAuthToken(TEST_JWT) await realTrpcClient.common.healthCheck.query().catch(() => undefined) expect(((fetchMock.mock.calls as any)[0][1]).headers.Authorization).toBe(`Bearer ${TEST_JWT}`) await deleteAuthToken() await realTrpcClient.common.healthCheck.query().catch(() => undefined) expect(((fetchMock.mock.calls as any)[1][1]).headers.Authorization).toBeUndefined() }) it('TRPC-05: aborts the request after the JSON fetch timeout', async () => { jest.useFakeTimers() let captured: AbortSignal | undefined ;(global as any).fetch = jest.fn((_url: string, options: any) => { captured = options.signal return new Promise((_resolve, reject) => { options.signal?.addEventListener('abort', () => reject(new Error('aborted'))) }) }) const pending = realTrpcClient.common.healthCheck.query().catch(() => undefined) // Let the batched dispatch timer fire so the link hands the signal to fetch. await jest.advanceTimersByTimeAsync(1) expect(captured).toBeDefined() expect(captured?.aborted).toBe(false) await jest.advanceTimersByTimeAsync(90_000) expect(captured?.aborted).toBe(true) await pending jest.useRealTimers() }) it('TRPC-06: forwards an upstream abort to the request signal', async () => { let captured: AbortSignal | undefined ;(global as any).fetch = jest.fn((_url: string, options: any) => { captured = options.signal return new Promise((_resolve, reject) => { options.signal?.addEventListener('abort', () => reject(new Error('aborted'))) }) }) const upstream = new AbortController() const pending = realTrpcClient.common.healthCheck .query({}, { signal: upstream.signal }) .catch(() => undefined) await flush() expect(captured).toBeDefined() expect(captured?.aborted).toBe(false) upstream.abort() expect(captured?.aborted).toBe(true) await pending }) it('TRPC-07: emits force-logout on a 401 tRPC envelope (error.data.code)', async () => { const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit') ;(global as any).fetch = jest.fn(async () => makeResponse(401, [ { error: { message: 'Unauthorized', data: { code: 'UNAUTHORIZED', httpStatus: 401 } } }, ]) ) await realTrpcClient.common.healthCheck.query().catch(() => undefined) await flush() expect(emitSpy).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT) emitSpy.mockRestore() }) }) /* -------------------------------------------------------------------------- */ /* HIDE-01..03 */ /* -------------------------------------------------------------------------- */ function HideProbe({ caller }: { caller?: string }) { useHideTabNav(caller) return hide } describe('useHideTabNav', () => { beforeEach(() => resetAllMocks()) it('HIDE-01: hides tabs for the caller key on focus', () => { renderWithProviders(, { auth: false }) expect(useAppStore.getState().hideTabsNav.productDetail).toBe(true) }) it('HIDE-02: uses the "default" key when no caller is given', () => { renderWithProviders(, { auth: false }) expect(useAppStore.getState().hideTabsNav.default).toBe(true) }) it('HIDE-03: shows tabs again on blur (unmount)', () => { const view = renderWithProviders(, { auth: false }) expect(useAppStore.getState().hideTabsNav.cart).toBe(true) act(() => view.unmount()) expect(useAppStore.getState().hideTabsNav.cart).toBe(false) }) }) /* -------------------------------------------------------------------------- */ /* PSI-01..04 */ /* -------------------------------------------------------------------------- */ const HOUR = 60 * 60 * 1000 const slot = (id: number, offsetMs: number) => ({ id, deliveryTime: new Date(Date.now() + offsetMs).toISOString(), freezeTime: new Date(Date.now() + offsetMs - HOUR).toISOString(), products: [], }) let getQuickestSlot: (productId: number) => number | null function PsiProbe() { const api = useProductSlotIdentifier() getQuickestSlot = api.getQuickestSlot return psi } function seedSlots(slots: any[], map: Record) { useCentralSlotStore.setState({ slots, productSlotsMap: map }) } describe('useProductSlotIdentifier', () => { beforeEach(() => resetAllMocks()) it('PSI-01: returns the id of the earliest future slot for the product', () => { const soon = slot(100, 2 * HOUR) const later = slot(200, 4 * HOUR) seedSlots([soon], { 2: { slots: [later, soon] } }) renderWithProviders(, { auth: false }) expect(getQuickestSlot(2)).toBe(100) }) it('PSI-02: returns null when the product only has past slots', () => { const past = slot(1, -2 * HOUR) seedSlots([past], { 2: { slots: [past] } }) renderWithProviders(, { auth: false }) expect(getQuickestSlot(2)).toBeNull() }) it('PSI-03: returns null with no map entry or no slots', () => { seedSlots([], {}) renderWithProviders(, { auth: false }) expect(getQuickestSlot(2)).toBeNull() act(() => useCentralSlotStore.setState({ slots: [slot(1, HOUR)] as any, productSlotsMap: {} })) expect(getQuickestSlot(2)).toBeNull() }) it('PSI-04: sorts by delivery time and returns the earliest', () => { const two = slot(2, 2 * HOUR) const four = slot(4, 4 * HOUR) const six = slot(6, 6 * HOUR) seedSlots([six], { 2: { slots: [six, two, four] } }) renderWithProviders(, { auth: false }) expect(getQuickestSlot(2)).toBe(2) }) }) /* -------------------------------------------------------------------------- */ /* PENDING-01..04 */ /* -------------------------------------------------------------------------- */ const PENDING_ADDRESS = { regionId: 1, name: 'Home', phone: '9876543210', addressLine1: '12 Main Road', city: 'Mahabubnagar', state: 'Telangana', latitude: 17, longitude: 78, } describe('pending-address', () => { beforeEach(() => resetAllMocks()) it('PENDING-01: saves and reads back a pending address', async () => { await savePendingAddress(PENDING_ADDRESS) expect(await getPendingAddress()).toEqual(PENDING_ADDRESS) }) it('PENDING-02: returns null when nothing was saved', async () => { expect(await getPendingAddress()).toBeNull() }) it('PENDING-03: clearPendingAddress removes it', async () => { await savePendingAddress(PENDING_ADDRESS) await clearPendingAddress() expect(await getPendingAddress()).toBeNull() }) it('PENDING-04: returns null for corrupt stored JSON', async () => { __set('freshyo_pending_address', '{not json') expect(await getPendingAddress()).toBeNull() }) }) /* -------------------------------------------------------------------------- */ /* FETCH-01..04 (real src/lib/fetch-json) */ /* -------------------------------------------------------------------------- */ describe('fetch-json', () => { beforeEach(() => resetAllMocks()) afterEach(() => { jest.restoreAllMocks() jest.useRealTimers() }) it('FETCH-01: returns the JSON payload on success', async () => { const getSpy = jest .spyOn(axios, 'get') .mockResolvedValue({ data: { hello: 'world' } } as any) const data = await realFetchJson.fetchJson('https://cdn.test/a.json') expect(data).toEqual({ hello: 'world' }) expect(getSpy).toHaveBeenCalledWith( 'https://cdn.test/a.json', expect.objectContaining({ signal: expect.anything() }) ) }) it('FETCH-02: aborts the request when the timeout elapses', async () => { jest.useFakeTimers() let captured: AbortSignal | undefined jest.spyOn(axios, 'get').mockImplementation(((_url: string, config: any) => { captured = config.signal return new Promise((_resolve, reject) => { config.signal?.addEventListener('abort', () => reject(new Error('aborted'))) }) }) as any) const pending = realFetchJson.fetchJson('https://cdn.test/slow.json').catch(() => undefined) expect(captured).toBeDefined() expect(captured?.aborted).toBe(false) jest.advanceTimersByTime(realFetchJson.JSON_FETCH_TIMEOUT_MS) expect(captured?.aborted).toBe(true) await pending }) it('FETCH-03: isAbortError recognises axios and fetch cancellations', () => { expect(realFetchJson.isAbortError({ name: 'CanceledError' })).toBe(true) expect(realFetchJson.isAbortError({ name: 'AbortError' })).toBe(true) expect(realFetchJson.isAbortError({ code: 'ERR_CANCELED' })).toBe(true) }) it('FETCH-04: isAbortError is false for other errors', () => { expect(realFetchJson.isAbortError(new Error('boom'))).toBe(false) expect(realFetchJson.isAbortError(null)).toBe(false) expect(realFetchJson.isAbortError('nope')).toBe(false) }) })