/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 25 — "Region and location" (`tests/lib/use-region.test.tsx`). * * REGION-01..15: the `useRegion()` startup region-resolution state machine. * * `useRegion` keeps the launch decision in module-level singletons * (`startupCheckDone` / `startupLaunchRegionId`), so every case runs against a * freshly loaded module registry (`jest.isolateModulesAsync`) together with its * own copies of the harness modules (stores, trpc mock, fetch-json mock, ...). * The trpc mock re-seeds its defaults on import, so nothing leaks across cases. * * Re-importing `@testing-library/react-native` per case would re-run its * top-level `afterEach`/`afterAll` registration, which Jest forbids inside a * running test; `RNTL_SKIP_AUTO_CLEANUP` suppresses that and we clean up by hand. */ jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) async function withFreshModules(fn: (ctx: any) => Promise) { await jest.isolateModulesAsync(async () => { const previousSkip = process.env.RNTL_SKIP_AUTO_CLEANUP process.env.RNTL_SKIP_AUTO_CLEANUP = 'true' const React = require('react') const rtl = require('@testing-library/react-native') require('../helpers/reset').resetAllMocks() if (previousSkip === undefined) delete process.env.RNTL_SKIP_AUTO_CLEANUP else process.env.RNTL_SKIP_AUTO_CLEANUP = previousSkip const ctx: any = { React, rtl, auth: require('../mocks/auth-context'), locationMock: require('../mocks/expo-location-mock'), trpc: require('../mocks/trpc-client'), testUtils: require('../helpers/test-utils'), fixtures: require('../fixtures'), secure: require('../mocks/secure-store-mock'), regionStore: require('@/src/store/regionStore').useRegionStore, locationStore: require('@/src/store/locationStore').useLocationStore, useRegion: require('@/src/hooks/useRegion').useRegion, } ctx.renderRegion = () => { const result: { current: any } = { current: null } const Probe = () => { result.current = ctx.useRegion() return null } const element = React.createElement(Probe) const view = ctx.testUtils.renderWithProviders(element, { auth: false }) return { result, view, element } } try { await fn(ctx) } finally { rtl.cleanup() } }) } describe('useRegion', () => { it('REGION-01: with no region and no coords it resolves then falls back to the chooser', async () => { await withFreshModules(async (ctx) => { ctx.locationMock.__configure({ permission: 'denied' }) const { result, view } = ctx.renderRegion() expect(result.current.isResolvingRegion).toBe(true) expect(result.current.regionId).toBeNull() await ctx.testUtils.flush(3) expect(result.current.isResolvingRegion).toBe(false) expect(result.current.regionId).toBeNull() expect(result.current.locationStatus).toBe('denied') view.unmount() }) }) it('REGION-02: a resolved region with no saved region is adopted without clearing the cart', async () => { await withFreshModules(async (ctx) => { const { CART_REG } = ctx.fixtures ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false }) ctx.locationMock.__configure({ permission: 'granted' }) ctx.secure.__set('cart_items', CART_REG) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(5) expect(result.current.regionId).toBe(1) expect(result.current.boundId).toBe(7) // Adopted as the first region of the launch -> no cart clear, no switch. expect(ctx.regionStore.getState().regionGeneration).toBe(1) expect(ctx.secure.__snapshot().cart_items).toBe(CART_REG) view.unmount() }) }) it('REGION-03: a resolved different region with no default confirms the switch', async () => { await withFreshModules(async (ctx) => { const { REGION_1, REGION_2 } = ctx.fixtures ctx.regionStore.getState().setRegion(REGION_1, 7) ctx.trpc.setProcedure('common.resolveRegionByLocation', { data: { region: REGION_2, bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' } }, }) ctx.locationMock.__configure({ permission: 'granted' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(6) expect(result.current.regionId).toBe(2) expect(ctx.regionStore.getState().selectedRegionId).toBe(2) view.unmount() }) }) it('REGION-04: a resolved same region with a new bound updates the bound', async () => { await withFreshModules(async (ctx) => { const { REGION_1 } = ctx.fixtures ctx.regionStore.getState().setRegion(REGION_1, 7) ctx.trpc.setProcedure('common.resolveRegionByLocation', { data: { region: REGION_1, bound: { id: 9, regionId: 1, priority: 1, name: 'Bound 9' } }, }) ctx.locationMock.__configure({ permission: 'granted' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(5) expect(result.current.regionId).toBe(1) expect(result.current.boundId).toBe(9) view.unmount() }) }) it('REGION-05: a signed-in default in the resolved region adopts the default bound', async () => { await withFreshModules(async (ctx) => { ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) ctx.locationMock.__configure({ permission: 'granted' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(5) // Default address A1 -> region 1, bound 7. expect(result.current.regionId).toBe(1) expect(result.current.boundId).toBe(7) view.unmount() }) }) it('REGION-06: a default in another region with a differently resolved region clears for the chooser', async () => { await withFreshModules(async (ctx) => { const { REGION_1, REGION_2 } = ctx.fixtures ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) ctx.regionStore.getState().setRegion(REGION_1, 7) ctx.trpc.setProcedure('common.resolveRegionByLocation', { data: { region: REGION_2, bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' } }, }) ctx.locationMock.__configure({ permission: 'granted' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(5) expect(result.current.regionId).toBeNull() view.unmount() }) }) it('REGION-07: no serviceable region with a default adopts the default', async () => { await withFreshModules(async (ctx) => { ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) ctx.locationMock.__configure({ permission: 'denied' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(5) expect(result.current.regionId).toBe(1) expect(result.current.boundId).toBe(7) view.unmount() }) }) it('REGION-08: it waits while auth is loading, then settles once auth resolves', async () => { await withFreshModules(async (ctx) => { ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: true }) ctx.locationMock.__configure({ permission: 'granted' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(3) expect(result.current.isResolvingRegion).toBe(true) expect(result.current.regionId).toBeNull() ctx.auth.__setAuthState({ isLoading: false }) // Auth is read from the mocked context; bump the trpc store so the hook // re-renders and picks the settled auth state up. await ctx.rtl.act(async () => { ctx.trpc.setProcedure('common.healthCheck', { data: { ok: true } }) }) await ctx.testUtils.flush(5) expect(result.current.regionId).toBe(1) view.unmount() }) }) it('REGION-09: it waits while the default address is loading, then settles', async () => { await withFreshModules(async (ctx) => { const { A1 } = ctx.fixtures ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) ctx.trpc.setProcedure('user.address.getDefaultAddress', { mode: 'pending' }) ctx.locationMock.__configure({ permission: 'granted' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(3) expect(result.current.isResolvingRegion).toBe(true) expect(result.current.regionId).toBeNull() await ctx.rtl.act(async () => { ctx.trpc.setProcedure('user.address.getDefaultAddress', { mode: 'success', data: { data: A1 }, }) }) await ctx.testUtils.flush(5) expect(result.current.regionId).toBe(1) view.unmount() }) }) it('REGION-10: a manual region pick before the fix resolves is respected', async () => { await withFreshModules(async (ctx) => { const { REGION_1, REGION_2, BOUND_1 } = ctx.fixtures ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'pending' }) ctx.locationMock.__configure({ permission: 'granted' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(3) expect(result.current.regionId).toBeNull() expect(result.current.isResolvingRegion).toBe(true) await ctx.rtl.act(async () => { ctx.regionStore.getState().setRegion(REGION_2, 8) }) // The late fix now resolves to region 1; the manual pick must win. await ctx.rtl.act(async () => { ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'success', data: { region: REGION_1, bound: BOUND_1 }, }) }) await ctx.testUtils.flush(5) expect(result.current.regionId).toBe(2) view.unmount() }) }) it('REGION-11: a resolve that hangs 8s settles via the safety-net timer', async () => { await withFreshModules(async (ctx) => { ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'pending' }) ctx.locationMock.__configure({ permission: 'granted' }) jest.useFakeTimers() const { result, view } = ctx.renderRegion() await ctx.rtl.act(async () => { await Promise.resolve() }) await ctx.rtl.act(async () => { await Promise.resolve() }) expect(result.current.isResolvingRegion).toBe(true) await ctx.rtl.act(async () => { jest.advanceTimersByTime(8000) }) expect(result.current.isResolvingRegion).toBe(false) expect(result.current.regionId).toBeNull() jest.useRealTimers() view.unmount() }) }) it('REGION-12: a saved region absent from listRegions is left untouched (current behaviour)', async () => { await withFreshModules(async (ctx) => { const { REGIONS } = ctx.fixtures ctx.trpc.setProcedure('common.listRegions', { data: REGIONS }) ctx.regionStore .getState() .setRegion({ id: 99, name: 'Ghost', description: 'Stale', effectiveBoundId: 1 } as any, 7) ctx.locationMock.__configure({ permission: 'denied' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(4) // The hook has no membership validation against `listRegions`, so a stale // region id is currently retained rather than cleared. expect(result.current.regionId).toBe(99) view.unmount() }) }) it('REGION-13: a missing stored bound is filled from the derived active bound', async () => { await withFreshModules(async (ctx) => { const { REGION_1 } = ctx.fixtures ctx.regionStore.getState().setRegion(REGION_1, null) ctx.locationMock.__configure({ permission: 'denied' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(4) expect(ctx.regionStore.getState().selectedBoundId).toBe(7) expect(result.current.boundId).toBe(7) view.unmount() }) }) it('REGION-14: an existing stored bound is not overwritten by the active bound', async () => { await withFreshModules(async (ctx) => { const { REGION_1 } = ctx.fixtures ctx.regionStore.getState().setRegion(REGION_1, 99) ctx.locationMock.__configure({ permission: 'denied' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(4) expect(result.current.boundId).toBe(99) expect(ctx.regionStore.getState().selectedBoundId).toBe(99) view.unmount() }) }) it('REGION-15: refreshLocation re-arms the startup check and can adopt a region', async () => { await withFreshModules(async (ctx) => { const { REGION_1, BOUND_1 } = ctx.fixtures ctx.locationMock.__configure({ permission: 'denied' }) const { result, view } = ctx.renderRegion() await ctx.testUtils.flush(4) expect(result.current.regionId).toBeNull() expect(result.current.isResolvingRegion).toBe(false) // The user now grants location and taps "use my location". ctx.locationMock.__configure({ permission: 'granted' }) await ctx.rtl.act(async () => { ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'success', data: { region: REGION_1, bound: BOUND_1 }, }) result.current.refreshLocation() }) await ctx.testUtils.flush(6) expect(result.current.regionId).toBe(1) view.unmount() }) }) })