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

183 lines
6.8 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — QuickDeliveryAddressSelector (SLOTQ-01..06).
*
* The header is a delivery-time picker (the address dropdown is currently
* commented out in the component) plus a warning when the selected/default
* address belongs to another region.
*/
import * as React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import dayjs from 'dayjs'
import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'
import { useRegionStore } from '@/src/store/regionStore'
import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client'
import { __setAuthState } from '../mocks/auth-context'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { setJsonResponse } from '../mocks/fetch-json'
import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, REGION_2, SLOTS, CART_REG, slotsCacheUrl } 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
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,
fullAddress: null,
isCache: false,
changeRegion: jest.fn(),
selectAddress: jest.fn(),
...overrides,
}
;(globalThis as any).__neoHook = state
return state
}
function setup(options: { addresses?: any[]; slots?: any[] } = {}) {
seedJsonCache()
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
__setAuthState({ isAuthenticated: true, isLoading: false })
setProcedure('user.address.getUserAddresses', { data: { data: options.addresses ?? [S1, S2] } })
const slots = (options.slots ?? SLOTS).map((slot) => ({ ...slot }))
setJsonResponse(slotsCacheUrl(1) + '?v=123', {
slots,
productAvailability: [],
count: slots.length,
})
return slots
}
/** 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}`
}
describe('QuickDeliveryAddressSelector (SLOTQ)', () => {
beforeEach(() => {
resetAllMocks()
setRegionHook()
})
it('SLOTQ-01: a foreign address warns, confirms the switch and clears the cart/home', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
useRegionStore.getState().setRegion(REGION_1, 7)
__set('cart_items', CART_REG)
setup()
;(globalThis as any).__neoHook.selectedAddressId = 12
const { getByTestId, getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false,
})
await flush(4)
expect(
getByText('Selected address is in another region. Tap to switch region (clears cart).')
).toBeTruthy()
fireEvent.press(getByTestId('quick-delivery-foreign-warning'))
expect(alertSpy).toHaveBeenCalled()
expect(alertSpy.mock.calls[0][0]).toBe('Switch region?')
const buttons = alertSpy.mock.calls[0][2] as any[]
const switchButton = buttons.find((button) => button.text === 'Switch & clear cart')
await act(async () => {
await switchButton.onPress()
})
expect((globalThis as any).__neoHook.selectAddress).toHaveBeenCalledWith(12)
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore()
})
it('SLOTQ-02: an address in an unavailable region alerts instead of switching', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
useRegionStore.getState().setRegion(REGION_1, 7)
setup({ addresses: [S1, { ...S1, id: 31, regionId: 99 }] })
;(globalThis as any).__neoHook.selectedAddressId = 31
const { getByTestId } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false,
})
await flush(4)
fireEvent.press(getByTestId('quick-delivery-foreign-warning'))
expect(alertSpy).toHaveBeenCalledWith(
'Unavailable region',
'This address belongs to a region that is not currently available.'
)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
alertSpy.mockRestore()
})
it('SLOTQ-03: no selected/default address leaves the address summary hidden', async () => {
setup({ addresses: [] })
const { getByTestId, queryByText } = renderWithProviders(
<QuickDeliveryAddressSelector />,
{ auth: false }
)
await flush(4)
// The address dropdown is commented out in the component, so `Select address`
// never renders; the delivery-time button remains the only header control.
expect(queryByText('Select address')).toBeNull()
expect(getByTestId('quick-delivery-slot-button')).toBeTruthy()
})
it('SLOTQ-04: the earliest slot is selected and the slot list is sorted in place', async () => {
const slots = setup({ slots: [SLOTS[3], SLOTS[0], SLOTS[1]] })
const earliest = [...slots].sort((a, b) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))[0]
const { getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, { auth: false })
await flush(4)
expect(getByText(formatTimeRange(earliest.deliveryTime))).toBeTruthy()
// `slotsData.slots.sort(...)` mutates the fetched array in place.
expect(slots[0].id).toBe(earliest.id)
})
it('SLOTQ-05: with no slots the header shows "Select time"', async () => {
setup({ slots: [] })
const { getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false,
})
await flush(4)
expect(getByText('Select time')).toBeTruthy()
})
it('SLOTQ-06: a selected slot id renders its formatted delivery range', async () => {
const slots = setup()
const chosen = slots.find((slot) => slot.id === 1849) ?? slots[0]
const { getByText } = renderWithProviders(
<QuickDeliveryAddressSelector slotId={1849} />,
{ auth: false }
)
await flush(4)
expect(getByText(formatTimeRange(chosen.deliveryTime))).toBeTruthy()
})
})