freshyo/apps/user-ui/tests/components/location-components.test.tsx
2026-11-08 13:49:17 +05:30

912 lines
34 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — Location components (LOC-01..54).
*
* Covers the region gate (`LocationTestWrapper`), the address chooser
* (`LocationFallbackFlow`), the bar, the map step, the location attacher, the
* cart address gate and the quick-delivery header.
*
* `useRegion` is replaced with a controllable stub so the `LocationTestWrapper`
* contract (region known / loading / resolving / no region / stale region) can be
* exercised deterministically without the hook's module-level startup state.
* Everything below the gate (stores, `confirmRegionSwitch`, cart helpers) runs for
* real.
*/
import * as React from 'react'
import { Linking, Platform, Text } from 'react-native'
import { act, fireEvent, within } from '@testing-library/react-native'
import dayjs from 'dayjs'
import LocationTestWrapper from '@/components/LocationTestWrapper'
import CartAddressGate from '@/components/CartAddressGate'
import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'
import LocationBar from '@/src/components/LocationBar'
import LocationAttacher from '@/src/components/LocationAttacher'
import LocationMapStep from '@/src/components/location/LocationMapStep'
import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow'
import AddressForm from '@/src/components/AddressForm'
import constants from '@/src/constants'
import { useRegionStore } from '@/src/store/regionStore'
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useLocationStore } from '@/src/store/locationStore'
import { renderWithProviders, flush, seedJsonCache, seedSelectedAddress } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastMutationInput,
procedureInvalidations,
procedureQueryCalls,
} from '../mocks/trpc-client'
import { __setAuthState } from '../mocks/auth-context'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, BOUND_1, SLOTS, CONSTS } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
jest.mock('@/src/hooks/useRegion', () => ({
useRegion: () => (globalThis as any).__regionHook,
}))
/** Serialize an address fixture into the API shape the chooser/bar consume. */
const ser = (address: any) => ({
...address,
addressLine1: address.line1,
addressLine2: address.line2,
phone: address.mobile,
})
const S1 = ser(A1) // Home, region 1, default, bound 7
const S2 = ser(A2) // Work, region 2, bound 8
const S3 = ser(A3) // NoRegion, region null
function setRegionHook(overrides: Record<string, any> = {}) {
const state: any = {
region: null,
regionId: null,
boundId: null,
bound: null,
regionGeneration: 0,
hydrated: true,
coords: null,
locationStatus: 'idle',
isResolvingRegion: false,
setRegion: jest.fn(),
clearRegion: jest.fn(),
refreshLocation: jest.fn(),
...overrides,
}
;(globalThis as any).__regionHook = state
return state
}
function signIn() {
__setAuthState({ isAuthenticated: true, isLoading: false })
}
function setAddresses(addresses: any[]) {
setProcedure('user.address.getUserAddresses', { data: { data: addresses } })
}
async function withPlatform(os: 'ios' | 'android', fn: () => Promise<void>) {
const original = Platform.OS
Object.defineProperty(Platform, 'OS', { value: os, configurable: true })
try {
await fn()
} finally {
Object.defineProperty(Platform, 'OS', { value: original, configurable: true })
}
}
/** Mirrors the component's slot label formatter. */
function formatTimeRange(deliveryTime: string | Date) {
const time = dayjs(deliveryTime)
const endTime = time.add(1, 'hour')
const startPeriod = time.format('A')
const endPeriod = endTime.format('A')
const timeRange =
startPeriod === endPeriod
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
return `${time.format('ddd, DD MMM ')}${timeRange}`
}
/** Build a quick-delivery tree with a controlled, unsorted slot document. */
function setupQuickDelivery() {
seedJsonCache()
const slots = [...SLOTS].reverse().map((slot) => ({ ...slot }))
setProcedure('common.essentialConsts', { data: { ...CONSTS } })
setProcedure('user.address.getUserAddresses', { data: { data: [S1, S2] } })
return slots
}
describe('Location components (LOC)', () => {
beforeEach(() => {
resetAllMocks()
setRegionHook()
})
it('LOC-01: LocationTestWrapper renders children when a region is known', () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
const { getByText, queryByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByText('gate children')).toBeTruthy()
expect(queryByTestId('location-loading')).toBeNull()
})
it('LOC-02: LocationTestWrapper shows a spinner while the store is not hydrated', () => {
setRegionHook({ hydrated: false })
const { getByTestId, queryByText } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByTestId('location-loading')).toBeTruthy()
expect(queryByText('Finding your region...')).toBeNull()
})
it('LOC-03: LocationTestWrapper shows "Finding your region..." while resolving', () => {
setRegionHook({ isResolvingRegion: true })
const { getByText, getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByTestId('location-loading')).toBeTruthy()
expect(getByText('Finding your region...')).toBeTruthy()
})
it('LOC-04: LocationTestWrapper falls back to the address flow with no region', () => {
const { getByText, queryByText } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByText('Delivery Address')).toBeTruthy()
expect(queryByText('gate children')).toBeNull()
})
it('LOC-05: denied notice is shown with a settings button', () => {
setRegionHook({ locationStatus: 'denied' })
const { getByText, getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(
getByText(
'Location access is not granted. Allow location access for accurate delivery, or add a delivery address below.'
)
).toBeTruthy()
expect(getByTestId('open-location-settings')).toBeTruthy()
})
it('LOC-06: services-off notice is shown with a settings button', () => {
setRegionHook({ locationStatus: 'services-off' })
const { getByText, getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(
getByText('Your device location is turned off. Turn it on, or add a delivery address below.')
).toBeTruthy()
expect(getByTestId('open-location-settings')).toBeTruthy()
})
it('LOC-07: unavailable notice is shown without a settings button', () => {
setRegionHook({ locationStatus: 'unavailable' })
const { getByText, queryByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(
getByText('We could not get your location. Please try again, or add a delivery address below.')
).toBeTruthy()
expect(queryByTestId('open-location-settings')).toBeNull()
})
it('LOC-08: the settings button sends the Android location-source intent', async () => {
setRegionHook({ locationStatus: 'services-off' })
await withPlatform('android', async () => {
const sendIntent = jest.fn(async () => undefined)
;(Linking as any).sendIntent = sendIntent
const { getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
fireEvent.press(getByTestId('open-location-settings'))
await flush(2)
expect(sendIntent).toHaveBeenCalledWith('android.settings.LOCATION_SOURCE_SETTINGS')
})
})
it('LOC-09: the settings button calls Linking.openSettings on iOS', async () => {
setRegionHook({ locationStatus: 'denied' })
await withPlatform('ios', async () => {
const openSettings = jest.fn(async () => undefined)
;(Linking as any).openSettings = openSettings
const { getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
fireEvent.press(getByTestId('open-location-settings'))
await flush(2)
expect(openSettings).toHaveBeenCalled()
})
})
it('LOC-10: a failing settings intent falls back to Linking.openSettings without crashing', async () => {
setRegionHook({ locationStatus: 'services-off' })
await withPlatform('android', async () => {
;(Linking as any).sendIntent = jest.fn(async () => {
throw new Error('no activity')
})
const openSettings = jest.fn(async () => undefined)
;(Linking as any).openSettings = openSettings
const { getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
fireEvent.press(getByTestId('open-location-settings'))
await flush(2)
expect(openSettings).toHaveBeenCalled()
})
})
it('LOC-11: a stale region absent from listRegions is cleared', async () => {
const region = setRegionHook({ region: REGION_1, regionId: 99, boundId: 7 })
renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await flush(2)
expect(region.clearRegion).toHaveBeenCalled()
})
it('LOC-12: the gate polling calls refreshLocation when the location becomes usable', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'denied' })
const region = setRegionHook()
renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await act(async () => {
await Promise.resolve()
})
configureLocation({ permission: 'granted' })
await act(async () => {
jest.advanceTimersByTime(3000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(region.refreshLocation).toHaveBeenCalled()
jest.useRealTimers()
})
it('LOC-13: a failing probe never triggers refreshLocation', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'denied' })
const region = setRegionHook()
renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await act(async () => {
await Promise.resolve()
})
await act(async () => {
jest.advanceTimersByTime(6000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(region.refreshLocation).not.toHaveBeenCalled()
jest.useRealTimers()
})
it('LOC-14: unmounting the gate clears the polling interval', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'denied' })
const region = setRegionHook()
const view = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await act(async () => {
await Promise.resolve()
})
view.unmount()
configureLocation({ permission: 'granted' })
await act(async () => {
jest.advanceTimersByTime(3000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(region.refreshLocation).not.toHaveBeenCalled()
jest.useRealTimers()
})
it('LOC-15: a saved address activates its region/bound, selects it and closes', async () => {
signIn()
setAddresses([S1, S2])
const onClose = jest.fn()
const { getByTestId } = renderWithProviders(<LocationFallbackFlow onClose={onClose} />, {
auth: false,
})
await flush(2)
fireEvent.press(getByTestId('location-address-11'))
await flush(3)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useRegionStore.getState().selectedBoundId).toBe(7)
expect(useAddressStore.getState().selectedAddressId).toBe(11)
expect(onClose).toHaveBeenCalled()
})
it('LOC-16: a saved address without a region shows a message', async () => {
signIn()
setAddresses([S3])
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
await flush(2)
fireEvent.press(getByTestId('location-address-13'))
await flush(2)
expect(
getByText('This saved address has no region. Please add a new address instead.')
).toBeTruthy()
})
it('LOC-17: a missing bound is resolved from the address coordinates', async () => {
signIn()
setAddresses([{ ...S1, id: 21, boundId: null, latitude: 17.0001, longitude: 78.0001 }])
setProcedure('common.resolveRegionByLocation', { data: { region: REGION_1, bound: BOUND_1 } })
const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByTestId('location-address-21'))
await flush(3)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useRegionStore.getState().selectedBoundId).toBe(7)
})
it('LOC-18: a failing bound resolve still activates the region', async () => {
signIn()
setAddresses([{ ...S1, id: 21, boundId: null, latitude: 17.0001, longitude: 78.0001 }])
setProcedure('common.resolveRegionByLocation', {
impl: () => {
throw new Error('resolve failed')
},
})
const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByTestId('location-address-21'))
await flush(3)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
})
it('LOC-19: an address in a no-longer-serviceable region shows a message and does not switch', async () => {
signIn()
setAddresses([{ ...S1, id: 31, regionId: 99, boundId: 7 }])
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
await flush(2)
fireEvent.press(getByTestId('location-address-31'))
await flush(3)
expect(getByText('This location is no longer serviceable.')).toBeTruthy()
expect(useRegionStore.getState().selectedRegionId).toBeNull()
})
it('LOC-20: the active address prefers the selection over the default (and is off at startup)', async () => {
signIn()
setAddresses([S1, S2])
seedSelectedAddress(12)
const first = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
expect(within(first.getByTestId('location-address-12')).getByTestId('location-address-active')).toBeTruthy()
expect(
within(first.getByTestId('location-address-11')).queryByTestId('location-address-active')
).toBeNull()
first.unmount()
useAddressStore.getState().setSelectedAddressId(null)
const second = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
expect(within(second.getByTestId('location-address-11')).getByTestId('location-address-active')).toBeTruthy()
second.unmount()
const startup = renderWithProviders(
<LocationFallbackFlow highlightActiveAddress={false} />,
{ auth: false }
)
await flush(2)
expect(startup.queryByTestId('location-address-active')).toBeNull()
})
it('LOC-21: set default posts the update payload and invalidates the address queries', async () => {
signIn()
setAddresses([S1, S2])
const { getByText } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByText('Set as default'))
await flush(3)
const input = lastMutationInput('user.address.updateAddress')
expect(input).toMatchObject({ id: 12, isDefault: true, name: 'Work' })
expect(procedureInvalidations('user.address.getUserAddresses').length).toBeGreaterThan(0)
expect(procedureInvalidations('user.address.getDefaultAddress').length).toBeGreaterThan(0)
})
it('LOC-22: a failed set default shows the error message', async () => {
signIn()
setAddresses([S1, S2])
setProcedure('user.address.updateAddress', {
mode: 'error',
error: new Error('Could not set default'),
})
const { getByText } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByText('Set as default'))
await flush(3)
expect(getByText('Could not set default')).toBeTruthy()
})
it('LOC-23: signed out shows the login footer and never queries addresses', () => {
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
getByTestId('location-login')
expect(getByText('Login to get existing addresses.')).toBeTruthy()
expect(procedureQueryCalls('user.address.getUserAddresses')).toHaveLength(0)
})
it('LOC-24: login mode renders the login screen inline and the back button returns to the chooser', async () => {
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
fireEvent.press(getByTestId('location-login'))
await flush(2)
expect(getByText('Welcome')).toBeTruthy()
fireEvent.press(getByTestId('location-login-back'))
await flush(2)
expect(getByText('Delivery Address')).toBeTruthy()
})
it('LOC-25: add mode renders the address form and the back button returns to the chooser', async () => {
signIn()
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
fireEvent.press(getByTestId('location-add-address'))
await flush(2)
expect(getByTestId('address-submit')).toBeTruthy()
fireEvent.press(getByTestId('location-add-back'))
await flush(2)
expect(getByText('Delivery Address')).toBeTruthy()
})
it('LOC-26: a successful add activates the resolved region, selects the new id and closes', async () => {
signIn()
const onClose = jest.fn()
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<LocationFallbackFlow onClose={onClose} />,
{ auth: false }
)
fireEvent.press(getByTestId('location-add-address'))
await flush(2)
const form = UNSAFE_getByType(AddressForm)
await act(async () => {
form.props.onResolvedRegion({ regionId: 1, boundId: 7 })
await form.props.onSuccess(42)
})
await flush(2)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useAddressStore.getState().selectedAddressId).toBe(42)
expect(onClose).toHaveBeenCalled()
})
it('LOC-27: a successful add while signed out closes without selecting an id', async () => {
const onClose = jest.fn()
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<LocationFallbackFlow onClose={onClose} />,
{ auth: false }
)
fireEvent.press(getByTestId('location-add-address'))
await flush(2)
const form = UNSAFE_getByType(AddressForm)
await act(async () => {
await form.props.onSuccess()
})
await flush(2)
expect(onClose).toHaveBeenCalled()
expect(useAddressStore.getState().selectedAddressId).toBeNull()
})
it('LOC-28: signed in with no addresses shows the empty copy', async () => {
signIn()
setAddresses([])
const { getByText } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
expect(getByText('No saved addresses yet.')).toBeTruthy()
})
it('LOC-29: while busy an overlay is shown and the address cards are disabled', async () => {
signIn()
setAddresses([S1, S2])
// A never-settling batch keeps `listRegions.fetch()` (and therefore `busy`) pending.
setProcedure('common.listRegions', { mode: 'pending' })
const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByTestId('location-address-11'))
await flush(1)
expect(getByTestId('location-busy-overlay')).toBeTruthy()
expect(getByTestId('location-address-11')).toBeDisabled()
})
it('LOC-30: LocationBar shows the region and active address and opens the switcher', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setAddresses([S1, S2])
seedSelectedAddress(11)
const { getByTestId, getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2)
expect(getByText('Mahabubnagar')).toBeTruthy()
expect(getByText('12 Main Road, Near Temple, Mahabubnagar')).toBeTruthy()
fireEvent.press(getByTestId('location-bar'))
await flush(2)
expect(getByText('Delivery Address')).toBeTruthy()
})
it('LOC-32: LocationBar prefers the selected address over the default', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setAddresses([S1, S2])
seedSelectedAddress(12)
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2)
expect(getByText('45 Office Street, Hyderabad')).toBeTruthy()
})
it('LOC-33: LocationBar renders no address line without a selection or default', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setAddresses([])
const { getByText, queryByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2)
expect(getByText('Mahabubnagar')).toBeTruthy()
expect(queryByText('12 Main Road, Near Temple, Mahabubnagar')).toBeNull()
})
it('LOC-57: LocationBar truncates the address to a single line', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setAddresses([S1, S2])
seedSelectedAddress(11)
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2)
const address = getByText('12 Main Road, Near Temple, Mahabubnagar')
// Two-line bar: "Deliver to <region>" then one ellipsised address line.
expect(address.props.numberOfLines).toBe(1)
expect(address.props.ellipsizeMode).toBe('tail')
})
it('LOC-34: LocationMapStep builds the URL with optional lat/lng params', () => {
const withCoords = renderWithProviders(
<LocationMapStep lat={17} lng={78} onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(withCoords.getByTestId('webview').props.source.uri).toBe(
`${constants.WEB_UI_BASE_URL}/location-selector?lat=17&lng=78`
)
withCoords.unmount()
const withoutCoords = renderWithProviders(
<LocationMapStep onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(withoutCoords.getByTestId('webview').props.source.uri).toBe(
`${constants.WEB_UI_BASE_URL}/location-selector`
)
})
it('LOC-35: LocationMapStep shows "Loading map..." until the webview loads', () => {
const { getByTestId, getByText, queryByText } = renderWithProviders(
<LocationMapStep onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(getByText('Loading map...')).toBeTruthy()
fireEvent(getByTestId('webview'), 'loadEnd')
expect(queryByText('Loading map...')).toBeNull()
})
it('LOC-36: a valid location-selected message calls onSelect', () => {
const onSelect = jest.fn()
const { getByTestId } = renderWithProviders(
<LocationMapStep onSelect={onSelect} onCancel={jest.fn()} />,
{ auth: false }
)
fireEvent(getByTestId('webview'), 'message', {
nativeEvent: {
data: JSON.stringify({ type: 'location-selected', latitude: 1.5, longitude: 2.5 }),
},
})
expect(onSelect).toHaveBeenCalledWith({ latitude: 1.5, longitude: 2.5 })
})
it('LOC-37: an unrelated webview message is ignored', () => {
const onSelect = jest.fn()
const { getByTestId } = renderWithProviders(
<LocationMapStep onSelect={onSelect} onCancel={jest.fn()} />,
{ auth: false }
)
fireEvent(getByTestId('webview'), 'message', {
nativeEvent: { data: JSON.stringify({ type: 'something-else' }) },
})
expect(onSelect).not.toHaveBeenCalled()
})
it('LOC-38: LocationMapStep renders the error banner', () => {
const { getByText } = renderWithProviders(
<LocationMapStep error="Outside our delivery area" onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(getByText('Outside our delivery area')).toBeTruthy()
})
it('LOC-39: LocationMapStep Cancel calls onCancel', () => {
const onCancel = jest.fn()
const { getByText } = renderWithProviders(
<LocationMapStep onSelect={jest.fn()} onCancel={onCancel} />,
{ auth: false }
)
fireEvent.press(getByText('Cancel'))
expect(onCancel).toHaveBeenCalled()
})
it('LOC-40: LocationAttacher attaches the granted location and shows the success badge', async () => {
configureLocation({ permission: 'granted' })
const onLocationChange = jest.fn()
const { getByTestId, getByText } = renderWithProviders(
<LocationAttacher onLocationChange={onLocationChange} />,
{ auth: false }
)
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(onLocationChange).toHaveBeenCalledWith({
latitude: 17.00012,
longitude: 78.00034,
})
expect(getByText('✓ Location Attached')).toBeTruthy()
// The 3s timer clears the transient success flag; the attached coords persist.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 3100))
})
expect(getByText('✓ Location Attached')).toBeTruthy()
})
it('LOC-41: a denied permission shows the error text and does not emit a location', async () => {
configureLocation({ permission: 'denied' })
const onLocationChange = jest.fn()
const { getByTestId, getByText } = renderWithProviders(
<LocationAttacher onLocationChange={onLocationChange} />,
{ auth: false }
)
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(getByText('Location Permission denied')).toBeTruthy()
expect(onLocationChange).not.toHaveBeenCalled()
})
it('LOC-42: a failed location read shows the error text', async () => {
configureLocation({ permission: 'granted', throwOnPosition: true })
const { getByTestId, getByText } = renderWithProviders(<LocationAttacher />, { auth: false })
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(
getByText('Unable to fetch location. Please check your GPS settings.')
).toBeTruthy()
})
it('LOC-43: a disabled LocationAttacher never requests permission', async () => {
configureLocation({ permission: 'denied' })
const onLocationChange = jest.fn()
const { getByTestId, queryByText } = renderWithProviders(
<LocationAttacher disabled onLocationChange={onLocationChange} />,
{ auth: false }
)
expect(getByTestId('attach-current-location')).toBeDisabled()
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(onLocationChange).not.toHaveBeenCalled()
expect(queryByText('Location Permission denied')).toBeNull()
})
it('LOC-44: an initial location shows the attached badge straight away', () => {
const { getByText } = renderWithProviders(
<LocationAttacher initialLocation={{ latitude: 1, longitude: 2 }} />,
{ auth: false }
)
expect(getByText('✓ Location Attached')).toBeTruthy()
})
it('LOC-45: the Google Maps option is button-first when uncontrolled and hidden when controlled', () => {
const uncontrolled = renderWithProviders(<LocationAttacher />, { auth: false })
fireEvent.press(uncontrolled.getByTestId('attach-google-maps'))
expect(uncontrolled.getByText(/Open Google Maps and Find location/)).toBeTruthy()
uncontrolled.unmount()
const controlled = renderWithProviders(
<LocationAttacher googleMapsUrl="" onGoogleMapsUrlChange={jest.fn()} />,
{ auth: false }
)
expect(controlled.queryByTestId('attach-google-maps')).toBeNull()
})
it('LOC-46: CartAddressGate enables the current-location option and shows the coordinates', () => {
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
useNeoRegionStore.setState({ coords: { latitude: 17.1, longitude: 78.2 } })
const { getByTestId, getByText } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
expect(getByTestId('cart-address-current')).not.toBeDisabled()
expect(getByText('Use your current location (17.10000, 78.20000)')).toBeTruthy()
})
it('LOC-49: the cart gate current-location mode prefills the device coordinates', async () => {
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
useNeoRegionStore.setState({ coords: { latitude: 17.1, longitude: 78.2 } })
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-current'))
await flush(1)
const form = UNSAFE_getByType(AddressForm)
expect(form.props.initialValues).toMatchObject({
latitude: 17.1,
longitude: 78.2,
city: 'Mahabubnagar',
isDefault: true,
})
})
it('LOC-50: the cart gate other-location mode starts the form empty', async () => {
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-other'))
await flush(1)
expect(UNSAFE_getByType(AddressForm).props.initialValues).toBeUndefined()
})
it('LOC-51: a saved address in the cart gate closes the modal and calls onDone', async () => {
const onDone = jest.fn()
const { getByTestId, UNSAFE_getByType, UNSAFE_queryByType } = renderWithProviders(
<CartAddressGate onDone={onDone} onBack={jest.fn()} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-other'))
await flush(1)
await act(async () => {
UNSAFE_getByType(AddressForm).props.onSuccess()
})
await flush(1)
expect(onDone).toHaveBeenCalled()
expect(UNSAFE_queryByType(AddressForm)).toBeNull()
})
it('LOC-52: the cart gate back button calls onBack', () => {
const onBack = jest.fn()
const { getByTestId } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={onBack} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-gate-back'))
expect(onBack).toHaveBeenCalled()
})
it('LOC-53: quick delivery (regular) shows the earliest slot and reports slot changes', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
const slots = setupQuickDelivery()
const onSlotChange = jest.fn()
const { getByTestId, getByText } = renderWithProviders(
<QuickDeliveryAddressSelector onSlotChange={onSlotChange} />,
{ auth: false }
)
await flush(4)
const earliest = [...slots].sort((a, b) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))[0]
expect(getByText(formatTimeRange(earliest.deliveryTime))).toBeTruthy()
fireEvent.press(getByTestId('quick-delivery-slot-button'))
await flush(1)
fireEvent.press(getByTestId('quick-delivery-slot-1849'))
expect(onSlotChange).toHaveBeenCalledWith(1849)
})
it('LOC-54: quick delivery (flash) shows "within 1 hour", the location bar and a back button', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setupQuickDelivery()
const { getByTestId, getByText } = renderWithProviders(
<QuickDeliveryAddressSelector isForFlashDelivery />,
{ auth: false }
)
await flush(4)
expect(getByText('Delivery in within 1 hour')).toBeTruthy()
expect(getByTestId('location-bar')).toBeTruthy()
fireEvent.press(getByTestId('quick-delivery-flash-back'))
expect(router.back).toHaveBeenCalled()
})
it('LOC-55: the startup gate auto-opens a sole non-default address', async () => {
signIn()
const sole = { ...S1, isDefault: false }
setAddresses([sole])
const onClose = jest.fn()
const { getByTestId } = renderWithProviders(
<LocationFallbackFlow highlightActiveAddress={false} onClose={onClose} />,
{ auth: false }
)
await flush(5)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useRegionStore.getState().selectedBoundId).toBe(7)
expect(useAddressStore.getState().selectedAddressId).toBe(sole.id)
expect(onClose).toHaveBeenCalled()
expect(getByTestId(`location-address-${sole.id}`)).toBeTruthy()
})
it('LOC-56: the regular address switcher does not auto-select a sole address', async () => {
signIn()
const sole = { ...S1, isDefault: false }
setAddresses([sole])
const onClose = jest.fn()
const { getByTestId } = renderWithProviders(
<LocationFallbackFlow onClose={onClose} />,
{ auth: false }
)
await flush(5)
expect(useRegionStore.getState().selectedRegionId).toBeNull()
expect(useAddressStore.getState().selectedAddressId).toBeNull()
expect(onClose).not.toHaveBeenCalled()
expect(getByTestId(`location-address-${sole.id}`)).toBeTruthy()
})
})