freshyo/apps/user-ui/tests/pages/addresses.test.tsx
2026-10-20 11:19:25 +05:30

392 lines
13 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 17.1 — the saved-address list
* (`app/(drawer)/(tabs)/me/addresses/index.tsx`, ADDR-01..20).
*
* `AddressForm` has its own suite (ADDRF-*), so this file only exercises the
* list: loading/error/empty states, the card actions and the modal wiring.
*
* The real tRPC client runs; `refetchCount()` counts the recorded network
* requests for `user.address.getUserAddresses`, so every explicit `refetch()`
* (and the focus refetch) is observable.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import Addresses from '@/app/(drawer)/(tabs)/me/addresses/index'
import AddressForm from '@/src/components/AddressForm'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastMutationInput,
procedureInvalidations,
procedureMutationCalls,
procedureQueryCalls,
} from '../mocks/trpc-client'
import { A1, A2, A3 } from '../fixtures'
/** Focus listeners registered through the (narrowed) navigation mock. */
const mockFocusCallbacks = new Set<() => void>()
jest.mock('@react-navigation/native', () => {
const React = require('react')
const actual = jest.requireActual(__dirname + '/../mocks/react-navigation-mock')
return {
...actual,
useFocusEffect: (callback: () => void | (() => void)) => {
React.useEffect(() => {
mockFocusCallbacks.add(callback)
const cleanup = callback()
return () => {
mockFocusCallbacks.delete(callback)
if (typeof cleanup === 'function') cleanup()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
},
}
})
const ADDRESSES_PATH = 'user.address.getUserAddresses'
/** Map the backend fixture onto the list/page `UserAddress` shape. */
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
let alertSpy: jest.SpyInstance
function setAddresses(addresses: any[]) {
setProcedure(ADDRESSES_PATH, { data: { data: addresses } })
}
function refetchCount(path = ADDRESSES_PATH) {
return procedureQueryCalls(path).length
}
function renderPage() {
return renderWithProviders(<Addresses />, { auth: false })
}
/** Render and let the real address query (and the batch fetch) settle. */
async function renderPageSettled() {
const view = renderPage()
await flush()
return view
}
function alertButtons(callIndex = -1) {
const calls = alertSpy.mock.calls
return calls[calls.length + callIndex]?.[2] ?? []
}
async function pressAlertButton(text: string) {
const button = alertButtons().find((candidate: any) => candidate.text === text)
if (!button) throw new Error(`Alert button ${text} not found`)
await act(async () => {
button.onPress?.()
})
await flush()
}
async function emitFocus() {
await act(async () => {
Array.from(mockFocusCallbacks).forEach((callback) => callback())
})
}
describe('Addresses (ADDR-01..ADDR-20)', () => {
beforeEach(() => {
resetAllMocks()
mockFocusCallbacks.clear()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('ADDR-01: shows loading copy while the address query is pending', () => {
setProcedure(ADDRESSES_PATH, { mode: 'pending' })
const { getByText } = renderPage()
expect(getByText('Loading addresses...')).toBeTruthy()
})
it('ADDR-02: a failed query shows the error state and Retry refetches', async () => {
setProcedure(ADDRESSES_PATH, { mode: 'error', error: new Error('offline') })
const { getByText, getByTestId } = await renderPageSettled()
expect(getByText('Failed to load addresses. Please try again.')).toBeTruthy()
const before = refetchCount()
fireEvent.press(getByTestId('addresses-retry-button'))
await flush()
expect(refetchCount()).toBeGreaterThan(before)
})
it('ADDR-03: an empty list shows the empty copy and opens the form from Add Address', async () => {
setAddresses([])
const { getByText, getByTestId } = await renderPageSettled()
expect(getByText('No addresses found')).toBeTruthy()
fireEvent.press(getByTestId('addresses-empty-add-button'))
await flush()
expect(getByTestId('address-name')).toBeTruthy()
})
it('ADDR-04: renders name, phone and the formatted address line', async () => {
setAddresses([S1])
const { getByText } = await renderPageSettled()
expect(getByText('Home')).toBeTruthy()
expect(getByText('📞 9876543210')).toBeTruthy()
expect(getByText('📍 12 Main Road, Near Temple, Mahabubnagar, Telangana')).toBeTruthy()
})
it('ADDR-05: the default address carries the badge and no Set Default action', async () => {
setAddresses([S1])
const { getByText, queryByTestId } = await renderPageSettled()
expect(getByText('Default')).toBeTruthy()
expect(queryByTestId('address-set-default-11')).toBeNull()
})
it('ADDR-06: a non-default address offers Set Default', async () => {
setAddresses([S1, S2])
const { getByTestId } = await renderPageSettled()
expect(getByTestId('address-set-default-12')).toBeTruthy()
})
it('ADDR-07: Add opens the form in add mode', async () => {
setAddresses([S1])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('addresses-add-button'))
await flush()
expect(view.getByTestId('address-name')).toBeTruthy()
expect(view.UNSAFE_getByType(AddressForm).props.isEdit).toBe(false)
})
it('ADDR-08: Edit opens the form prefilled with the address', async () => {
setAddresses([S1])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-edit-11'))
await flush()
const form = view.UNSAFE_getByType(AddressForm)
expect(form.props.isEdit).toBe(true)
expect(form.props.initialValues).toMatchObject({
id: 11,
regionId: 1,
name: 'Home',
phone: '9876543210',
addressLine1: '12 Main Road',
addressLine2: 'Near Temple',
city: 'Mahabubnagar',
state: 'Telangana',
isDefault: true,
latitude: 17,
longitude: 78,
})
expect(form.props.initialValues.googleMapsUrl).toBeUndefined()
})
it('ADDR-09: deleting the only address is refused before the confirmation', async () => {
setAddresses([S1])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-11'))
await flush()
expect(
view.getByText('This is your only address. Add another address before deleting this one.')
).toBeTruthy()
expect(alertSpy).not.toHaveBeenCalled()
expect(procedureMutationCalls('user.address.deleteAddress')).toHaveLength(0)
})
it('ADDR-10: deleting with more than one address asks for confirmation and Cancel does nothing', async () => {
setAddresses([S1, S2])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-12'))
expect(alertSpy).toHaveBeenCalledWith(
'Delete Address',
'Are you sure you want to delete this address?',
expect.any(Array)
)
await pressAlertButton('Cancel')
expect(procedureMutationCalls('user.address.deleteAddress')).toHaveLength(0)
})
it('ADDR-11: confirming delete mutates, refetches, invalidates the default and alerts', async () => {
setAddresses([S1, S2])
const view = await renderPageSettled()
const before = refetchCount()
fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete')
expect(lastMutationInput('user.address.deleteAddress')).toEqual({ id: 12 })
expect(refetchCount()).toBeGreaterThan(before)
expect(procedureInvalidations('user.address.getDefaultAddress').length).toBeGreaterThan(0)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Address deleted successfully')
})
it('ADDR-12: a rejected delete shows the Cannot delete address sheet', async () => {
setProcedure('user.address.deleteAddress', {
mode: 'error',
error: new Error('Address is used by an open order'),
})
setAddresses([S1, S2])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete')
expect(view.getByText('Cannot delete address')).toBeTruthy()
expect(view.getByText('Address is used by an open order')).toBeTruthy()
fireEvent.press(view.getByTestId('address-delete-error-ok'))
await flush()
expect(view.queryByText('Cannot delete address')).toBeNull()
})
it('ADDR-13: the current list does not pass isDeleting, so no Deleting... label appears', async () => {
setProcedure('user.address.deleteAddress', { mode: 'pending' })
setAddresses([S1, S2])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete')
expect(view.queryByText('Deleting...')).toBeNull()
expect(view.getByTestId('address-delete-12')).toBeTruthy()
// `mode: 'pending'` short-circuits the registry before it records calls, so
// count the real client's request at the network boundary instead.
const deleteRequests = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
String(url).includes('user.address.deleteAddress')
)
expect(deleteRequests).toHaveLength(1)
})
it('ADDR-14: setting a null-region address as default alerts without mutating', async () => {
setAddresses([S1, S3])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-set-default-13'))
await flush()
expect(alertSpy).toHaveBeenCalledWith(
'Error',
'This address has no region. Please edit it and choose a region first.'
)
expect(procedureMutationCalls('user.address.updateAddress')).toHaveLength(0)
})
it('ADDR-15: Set Default preserves the address fields and sends isDefault true', async () => {
setAddresses([S1, S2])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-set-default-12'))
await flush()
expect(lastMutationInput('user.address.updateAddress')).toEqual({
id: 12,
regionId: 2,
name: 'Work',
phone: '9876543211',
addressLine1: '45 Office Street',
addressLine2: undefined,
city: 'Hyderabad',
state: 'Telangana',
isDefault: true,
latitude: 18,
longitude: 79,
})
expect(procedureInvalidations('user.address.getDefaultAddress').length).toBeGreaterThan(0)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Default address updated')
})
it('ADDR-16: a rejected Set Default alerts with the server message', async () => {
setProcedure('user.address.updateAddress', {
mode: 'error',
error: new Error('Region mismatch'),
})
setAddresses([S1, S2])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-set-default-12'))
await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Region mismatch')
})
it('ADDR-17: a successful form submit closes the modal and refetches the list', async () => {
setAddresses([S1])
const view = await renderPageSettled()
const before = refetchCount()
fireEvent.press(view.getByTestId('addresses-add-button'))
await flush()
await act(async () => {
view.UNSAFE_getByType(AddressForm).props.onSuccess()
})
await flush()
expect(view.queryByTestId('address-name')).toBeNull()
expect(refetchCount()).toBeGreaterThan(before)
})
it('ADDR-18: re-focusing through useMarkDataFetchers refetches the list', async () => {
setAddresses([S1])
await renderPageSettled()
const before = refetchCount()
await emitFocus()
await flush()
expect(refetchCount()).toBeGreaterThan(before)
})
it('ADDR-19: an address without line 2 is formatted without a double comma', async () => {
setAddresses([S2])
const { getByText } = await renderPageSettled()
expect(getByText('📍 45 Office Street, Hyderabad, Telangana')).toBeTruthy()
})
it('ADDR-20: a Google Maps address passes coords as undefined to the form', async () => {
const mapped = {
...S2,
googleMapsUrl: 'https://maps.google.com/?q=18,79',
latitude: 18,
longitude: 79,
}
setAddresses([mapped])
const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-edit-12'))
await flush()
const values = view.UNSAFE_getByType(AddressForm).props.initialValues
expect(values.googleMapsUrl).toBe('https://maps.google.com/?q=18,79')
expect(values.latitude).toBeUndefined()
expect(values.longitude).toBeUndefined()
})
})