/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 24 — CheckoutAddressSelector / Display (CAS-01..22). * * The selector sorts the saved addresses (selected → default → id) on a * horizontal carousel, confirms cross-region switches and can attach the device * location; the display is a read-only card for the checkout page. */ import * as React from 'react' import { Alert, StyleSheet } from 'react-native' import { act, fireEvent, within } from '@testing-library/react-native' import CheckoutAddressSelector from '@/components/CheckoutAddressSelector' import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay' import AddressForm from '@/src/components/AddressForm' import { useRegionStore } from '@/src/store/regionStore' import { useAddressStore } from '@/src/store/addressStore' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { setProcedure, lastMutationInput, procedureMutationCalls, 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, REGION_2 } from '../fixtures' jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) jest.mock('@/src/hooks/useRegion', () => ({ useRegion: () => (globalThis as any).__regionHook, })) const ser = (address: any) => ({ ...address, addressLine1: address.line1, addressLine2: address.line2, phone: address.mobile, }) const S1 = ser(A1) // Home, region 1, default const S2 = ser(A2) // Work, region 2 const S3 = ser(A3) // NoRegion function setRegionHook(overrides: Record = {}) { 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 } }) } const dotColor = (node: any) => StyleSheet.flatten(node.props.style).backgroundColor describe('CheckoutAddressSelector / Display (CAS)', () => { beforeEach(() => { resetAllMocks() setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 }) }) it('CAS-01: the selected address is sorted first', async () => { signIn() setAddresses([S1, S2, S3]) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) expect(within(getByTestId('address-option-0')).getByText('Work')).toBeTruthy() }) it('CAS-02: the default address is sorted after the selected one', async () => { signIn() setAddresses([S1, S2, S3]) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) const optionOne = getByTestId('address-option-1') expect(within(optionOne).getByText('Home')).toBeTruthy() }) it('CAS-03: the remaining addresses keep a stable ascending id order', async () => { signIn() setAddresses([ { ...S3, isDefault: false }, { ...S1, isDefault: false }, { ...S2, isDefault: false }, ]) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy() expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy() expect(within(getByTestId('address-option-2')).getByText('NoRegion')).toBeTruthy() }) it('CAS-04: no selection auto-selects a default in the current region', async () => { signIn() setAddresses([S1, S2]) const onAddressSelect = jest.fn() renderWithProviders( , { auth: false } ) await flush(2) expect(onAddressSelect).toHaveBeenCalledWith(11) }) it('CAS-05: a default in another region is never auto-selected', async () => { signIn() setAddresses([S2, S3]) const onAddressSelect = jest.fn() renderWithProviders( , { auth: false } ) await flush(2) expect(onAddressSelect).not.toHaveBeenCalled() }) it('CAS-06: a default without a region is auto-selected', async () => { signIn() setAddresses([{ ...S1, regionId: null }]) const onAddressSelect = jest.fn() renderWithProviders( , { auth: false } ) await flush(2) expect(onAddressSelect).toHaveBeenCalledWith(11) }) it('CAS-07: tapping an address in another region opens the confirm dialog', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() setAddresses([S1, S2]) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) fireEvent.press(getByTestId('address-option-1')) expect(alertSpy).toHaveBeenCalled() expect(alertSpy.mock.calls[0][0]).toBe('Switch region?') alertSpy.mockRestore() }) it('CAS-08: cancelling the region switch changes nothing', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() useRegionStore.getState().setRegion(REGION_1, 7) setAddresses([S1, S2]) const onAddressSelect = jest.fn() const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) fireEvent.press(getByTestId('address-option-1')) const buttons = alertSpy.mock.calls[0][2] as any[] const cancel = buttons.find((button) => button.text === 'Cancel') // The cancel entry is inert: dismissing the dialog simply leaves the state. expect(cancel.onPress).toBeUndefined() expect(useRegionStore.getState().selectedRegionId).toBe(1) expect(onAddressSelect).not.toHaveBeenCalled() alertSpy.mockRestore() }) it('CAS-09: confirming the switch switches the region and replaces with home', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() useRegionStore.getState().setRegion(REGION_1, 7) setAddresses([S1, S2]) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) fireEvent.press(getByTestId('address-option-1')) const buttons = alertSpy.mock.calls[0][2] as any[] const confirm = buttons.find((button) => button.text === 'Switch & clear cart') await act(async () => { await confirm.onPress() }) // `confirmRegionSwitch` awaits the cart clear before navigating. await flush() expect(useRegionStore.getState().selectedRegionId).toBe(2) expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') alertSpy.mockRestore() }) it('CAS-10: an address in a missing region shows "Unavailable region"', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() setAddresses([S1, { ...S2, id: 31, regionId: 99 }]) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) fireEvent.press(getByTestId('address-option-1')) expect(alertSpy).toHaveBeenCalledWith( 'Unavailable region', 'This address belongs to a region that is not currently available.' ) alertSpy.mockRestore() }) it('CAS-11: tapping a same-region address selects it and resets the scroll', async () => { signIn() setAddresses([S1, S2]) const onAddressSelect = jest.fn() const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) fireEvent.scroll(getByTestId('address-scroll'), { nativeEvent: { contentOffset: { x: 300, y: 0 }, contentSize: { width: 900, height: 100 }, layoutMeasurement: { width: 300, height: 100 }, }, }) const activeColor = dotColor(getByTestId('address-dot-1')) expect(dotColor(getByTestId('address-dot-0'))).not.toBe(activeColor) fireEvent.press(getByTestId('address-option-0')) expect(onAddressSelect).toHaveBeenCalledWith(11) expect(dotColor(getByTestId('address-dot-0'))).toBe(activeColor) }) it('CAS-12: one pagination dot per address reflects the scroll index', async () => { signIn() setAddresses([S1, S2, S3]) const { getAllByTestId, getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) expect(getAllByTestId(/address-dot-/)).toHaveLength(3) fireEvent.scroll(getByTestId('address-scroll'), { nativeEvent: { contentOffset: { x: 600, y: 0 }, contentSize: { width: 900, height: 100 }, layoutMeasurement: { width: 300, height: 100 }, }, }) expect(dotColor(getByTestId('address-dot-2'))).not.toBe( dotColor(getByTestId('address-dot-0')) ) }) it('CAS-13: with no addresses the empty card offers adding one', async () => { signIn() setAddresses([]) const { getByText, getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) expect(getByText('No addresses found')).toBeTruthy() expect(getByTestId('add-address-empty')).toBeTruthy() }) it('CAS-14: attach location updates the address with the device coordinates', async () => { signIn() setAddresses([{ ...S1, latitude: null, longitude: null }]) configureLocation({ permission: 'granted' }) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) expect(getByTestId('attach-location')).toBeTruthy() fireEvent.press(getByTestId('attach-location')) await flush(2) expect(lastMutationInput('user.address.updateAddress')).toMatchObject({ id: 11, latitude: 17.00012, longitude: 78.00034, }) }) it('CAS-15: a denied permission alerts and does not update the address', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() setAddresses([{ ...S1, latitude: null, longitude: null }]) configureLocation({ permission: 'denied' }) const { getByTestId } = renderWithProviders( , { auth: false } ) await flush(2) fireEvent.press(getByTestId('attach-location')) await flush(2) expect(alertSpy).toHaveBeenCalledWith( 'Permission Denied', 'Location permission is required to attach your current location' ) expect(procedureMutationCalls('user.address.updateAddress')).toHaveLength(0) alertSpy.mockRestore() }) it('CAS-16: a location error alerts and clears the loading state', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() setAddresses([{ ...S1, latitude: null, longitude: null }]) configureLocation({ permission: 'granted', throwOnPosition: true }) const { getByTestId, getByText } = renderWithProviders( , { auth: false } ) await flush(2) fireEvent.press(getByTestId('attach-location')) await flush(2) expect(alertSpy).toHaveBeenCalledWith( 'Error', 'Unable to fetch location. Please check your GPS settings.' ) expect(getByText('+ Attach Current Location')).toBeTruthy() alertSpy.mockRestore() }) it('CAS-17: a successful add auto-selects the new address and invalidates queries', async () => { signIn() setAddresses([S1]) const onAddressSelect = jest.fn() const { getByTestId, UNSAFE_getByType, queryClient } = renderWithProviders( , { auth: false } ) await flush(2) const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries') fireEvent.press(getByTestId('add-new-address')) await flush(1) await act(async () => { UNSAFE_getByType(AddressForm).props.onSuccess(55) }) await flush(1) expect(onAddressSelect).toHaveBeenCalledWith(55) expect(invalidateSpy).toHaveBeenCalled() }) it('CAS-18: the display shows the selected address', async () => { signIn() setAddresses([S1, S2, S3]) useAddressStore.getState().setSelectedAddressId(12) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('Work')).toBeTruthy() }) it('CAS-19: the display falls back to the default address', async () => { signIn() setAddresses([S1, S2, S3]) useAddressStore.getState().setSelectedAddressId(null) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('Home')).toBeTruthy() }) it('CAS-20: the display shows an empty state with no address', async () => { signIn() setAddresses([]) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('No address selected')).toBeTruthy() }) it('CAS-21: the display shows a loading state while addresses load', () => { signIn() setProcedure('user.address.getUserAddresses', { mode: 'pending' }) const { getByText } = renderWithProviders(, { auth: false }) expect(getByText('Loading address...')).toBeTruthy() }) it('CAS-22: the display is query-disabled when signed out and does not crash', async () => { __setAuthState({ isAuthenticated: false, isLoading: false }) // The real batch link schedules requests on a timer; drain one left over // from the previous case and clear its record before asserting this render // issued none. await flush() resetAllMocks() const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('No address selected')).toBeTruthy() expect(procedureQueryCalls('user.address.getUserAddresses')).toHaveLength(0) }) })