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

354 lines
13 KiB
TypeScript

/* 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 { useNeoRegionStore } from '@/src/store/neoRegionStore'
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/useRegionNeo', () => ({
useRegionNeo: () => (globalThis as any).__neoHook,
}))
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<string, any> = {}) {
const state: any = {
regionId: 1,
boundId: 7,
regionName: 'Mahabubnagar',
coords: { latitude: 16.7488, longitude: 77.9851 },
selectedAddressId: null,
selectedAddress: null,
fullAddress: null,
isCache: false,
changeRegion: jest.fn(),
selectAddress: jest.fn(),
...overrides,
}
;(globalThis as any).__neoHook = state
return state
}
function selector(selectedAddress: number | null, onAddressSelect = jest.fn()) {
setRegionHook({ selectedAddressId: selectedAddress, selectAddress: onAddressSelect })
return renderWithProviders(<CheckoutAddressSelector />, { auth: false })
}
function seedNeo(addresses: any[], selectedAddressId: number | null) {
useNeoRegionStore.setState({ addresses, selectedAddressId })
setRegionHook({
selectedAddressId,
selectedAddress: addresses.find((address) => address.id === selectedAddressId) ?? null,
})
}
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 } = selector(12, jest.fn())
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 } = selector(13, jest.fn())
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 } = selector(null, jest.fn())
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-05: a default in another region is never auto-selected', async () => {
signIn()
setAddresses([S2, S3])
const onAddressSelect = jest.fn()
selector(null, onAddressSelect)
await flush(2)
expect(onAddressSelect).not.toHaveBeenCalled()
})
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 } = selector(11, jest.fn())
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 } = selector(11, onAddressSelect)
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 selectAddress = jest.fn()
const { getByTestId } = selector(11, selectAddress)
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()
})
// `selectAddress` performs the switch in the neo store before navigating.
await flush()
expect(selectAddress).toHaveBeenCalledWith(12)
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 } = selector(11, jest.fn())
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 } = selector(null, onAddressSelect)
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 } = selector(null, jest.fn())
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 } = selector(null, jest.fn())
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 } = selector(11, jest.fn())
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 } = selector(11, jest.fn())
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 } = selector(11, jest.fn())
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 } = selector(null, onAddressSelect)
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])
seedNeo([S1, S2, S3], 12)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('Work')).toBeTruthy()
})
it('CAS-19: the display never falls back to a default from another region', async () => {
signIn()
setAddresses([S1, S2, S3])
seedNeo([S1, S2, S3], null)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('No address selected')).toBeTruthy()
})
it('CAS-20: the display shows an empty state with no address', async () => {
signIn()
setAddresses([])
seedNeo([], null)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('No address selected')).toBeTruthy()
})
it('CAS-22: the display does not query addresses when signed out', async () => {
__setAuthState({ isAuthenticated: false, isLoading: false })
await flush()
resetAllMocks()
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('No address selected')).toBeTruthy()
})
})