362 lines
15 KiB
TypeScript
362 lines
15 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
/**
|
|
* Catalogue section 25 — "App helpers" (`tests/lib/app-helpers.test.tsx`).
|
|
*
|
|
* - REGSW-01..09 the region-switch side effects (`confirmRegionSwitch`)
|
|
* - PENDING-05..10 the signed-out address draft sync (`PendingAddressSync`)
|
|
* - CENTRAL-01..02 the central store wiring (`CentralStoreInitializer`)
|
|
*
|
|
* AuthContext is replaced with the deterministic mock so `PendingAddressSync`
|
|
* can be driven through exact auth states.
|
|
*/
|
|
import * as React from 'react'
|
|
import { Text } from 'react-native'
|
|
import { waitFor } from '@testing-library/react-native'
|
|
|
|
import { resetAllMocks } from '../helpers/reset'
|
|
import {
|
|
createTestQueryClient,
|
|
flush,
|
|
renderWithProviders,
|
|
seedCentralStores,
|
|
seedJsonCache,
|
|
seedRegion,
|
|
} from '../helpers/test-utils'
|
|
import { __set, __snapshot } from '../mocks/secure-store-mock'
|
|
import { lastProcedureInput, procedureInvalidations, procedureMutationCalls, setProcedure } from '../mocks/trpc-client'
|
|
import { jsonCallsFor } from '../mocks/fetch-json'
|
|
import { __setAuthState } from '../mocks/auth-context'
|
|
|
|
import { confirmRegionSwitch } from '@/src/lib/region-switch'
|
|
import { useRegionStore } from '@/src/store/regionStore'
|
|
import { useAddressStore } from '@/src/store/addressStore'
|
|
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'
|
|
import { useCartStore } from '@/src/store/cartStore'
|
|
import { useFlashCartStore } from '@/src/store/flashCartStore'
|
|
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
|
import { useSlotStore } from '@/components/stores/slotStore'
|
|
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
|
import CentralStoreInitializer from '@/src/components/CentralStoreInitializer'
|
|
import PendingAddressSync from '@/src/components/PendingAddressSync'
|
|
|
|
import { A1, AUTH_USER, CART_REG, MERGED_PRODUCTS, P_CHICKEN, productsCacheUrl, REGION_1, REGION_2 } from '../fixtures'
|
|
|
|
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
|
|
|
const addedProduct = P_CHICKEN as any
|
|
|
|
const PENDING_INPUT = {
|
|
regionId: 1,
|
|
name: 'Home',
|
|
phone: '9876543210',
|
|
addressLine1: '12 Main Road',
|
|
addressLine2: 'Near Temple',
|
|
city: 'Mahabubnagar',
|
|
state: 'Telangana',
|
|
isDefault: true,
|
|
latitude: 17,
|
|
longitude: 78,
|
|
}
|
|
|
|
const pendingSnapshot = () => __snapshot().freshyo_pending_address
|
|
|
|
describe('app helpers', () => {
|
|
beforeEach(() => {
|
|
resetAllMocks()
|
|
})
|
|
|
|
it('REGSW-01: same region keeps both carts and the chosen address but clears selections/caches', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
__set('cart_items', CART_REG)
|
|
useAddressStore.getState().setSelectedAddressId(A1.id)
|
|
useQuickDeliveryStore.getState().setSelectedSlotId(1849)
|
|
useSlotStore.getState().setSlotId(1849)
|
|
useSlotStore.getState().setStoreId(2)
|
|
useCartStore.getState().setAddedToCartProduct(addedProduct)
|
|
useFlashCartStore.getState().setAddedFlashProduct(addedProduct)
|
|
useFlashNavigationStore.getState().setShouldNavigateToCart(true)
|
|
|
|
const queryClient = createTestQueryClient()
|
|
const removeSpy = jest.spyOn(queryClient, 'removeQueries')
|
|
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
|
|
const generationBefore = useRegionStore.getState().regionGeneration
|
|
|
|
await confirmRegionSwitch(REGION_1 as any, queryClient)
|
|
|
|
// Same-region switch must not touch the persisted carts or stash anything.
|
|
expect(__snapshot().cart_items).toBe(CART_REG)
|
|
expect(Object.keys(__snapshot()).some((key) => key.startsWith('region_carts_'))).toBe(false)
|
|
expect(useAddressStore.getState().selectedAddressId).toBe(A1.id)
|
|
expect(useRegionStore.getState().selectedRegionId).toBe(1)
|
|
expect(useRegionStore.getState().regionGeneration).toBe(generationBefore)
|
|
|
|
// ...but the in-memory selections/caches are still reset and queries refreshed.
|
|
expect(useQuickDeliveryStore.getState().selectedSlotId).toBeNull()
|
|
expect(useSlotStore.getState().slotId).toBeUndefined()
|
|
expect(useSlotStore.getState().storeId).toBeUndefined()
|
|
expect(useCartStore.getState().addedToCartProduct).toBeNull()
|
|
expect(useFlashCartStore.getState().addedFlashProduct).toBeNull()
|
|
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false)
|
|
expect(useCentralProductStore.getState().products).toEqual([])
|
|
expect(removeSpy).toHaveBeenCalledTimes(5)
|
|
expect(invalidateSpy).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('REGSW-02: different region stashes the old carts, clears both and drops the address', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
__set('cart_items', CART_REG)
|
|
__set('flash_cart_items', '[]')
|
|
useAddressStore.getState().setSelectedAddressId(A1.id)
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
|
|
|
|
const snapshot = __snapshot()
|
|
expect(JSON.parse(snapshot.region_carts_1)).toEqual({
|
|
regular: [{ skuId: 2, slotId: 1849, quantity: 2 }],
|
|
flash: [],
|
|
})
|
|
expect(snapshot.cart_items).toBe('[]')
|
|
expect(snapshot.flash_cart_items).toBe('[]')
|
|
expect(useAddressStore.getState().selectedAddressId).toBeNull()
|
|
expect(useRegionStore.getState().selectedRegionId).toBe(REGION_2.id)
|
|
expect(useRegionStore.getState().selectedBoundId).toBe(8)
|
|
})
|
|
|
|
it('REGSW-03: no previous region does not stash anything', async () => {
|
|
__set('cart_items', CART_REG)
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
|
|
|
|
expect(Object.keys(__snapshot()).filter((key) => key.startsWith('region_carts_'))).toHaveLength(0)
|
|
expect(__snapshot().cart_items).toBe('[]')
|
|
})
|
|
|
|
it('REGSW-04: a known region restores its stashed carts', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
__set('region_carts_2', JSON.stringify({ regular: [{ skuId: 8, slotId: 0, quantity: 3 }], flash: [] }))
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
|
|
|
|
const items = JSON.parse(__snapshot().cart_items)
|
|
expect(items).toHaveLength(1)
|
|
expect(items[0]).toMatchObject({ skuId: 8, slotId: 0, quantity: 3 })
|
|
expect(items[0].id).toBe(1)
|
|
})
|
|
|
|
it('REGSW-05: resets the quick-delivery, slot, cart and flash stores', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
useQuickDeliveryStore.getState().setSelectedSlotId(1849)
|
|
useSlotStore.getState().setSlotId(1849)
|
|
useSlotStore.getState().setStoreId(2)
|
|
useCartStore.getState().setAddedToCartProduct(addedProduct)
|
|
useFlashCartStore.getState().setAddedFlashProduct(addedProduct)
|
|
useFlashNavigationStore.getState().setShouldNavigateToCart(true)
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
|
|
|
|
expect(useQuickDeliveryStore.getState().selectedSlotId).toBeNull()
|
|
expect(useSlotStore.getState().slotId).toBeUndefined()
|
|
expect(useSlotStore.getState().storeId).toBeUndefined()
|
|
expect(useCartStore.getState().addedToCartProduct).toBeNull()
|
|
expect(useFlashCartStore.getState().addedFlashProduct).toBeNull()
|
|
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false)
|
|
})
|
|
|
|
it('REGSW-06: clears the central product and slot stores', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
seedCentralStores()
|
|
expect(useCentralProductStore.getState().products.length).toBeGreaterThan(0)
|
|
expect(Object.keys(useCentralSlotStore.getState().productSlotsMap).length).toBeGreaterThan(0)
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
|
|
|
|
expect(useCentralProductStore.getState().products).toEqual([])
|
|
expect(useCentralProductStore.getState().productsById).toEqual({})
|
|
expect(useCentralSlotStore.getState().slots).toEqual([])
|
|
expect(useCentralSlotStore.getState().productSlotsMap).toEqual({})
|
|
})
|
|
|
|
it('REGSW-07: removes the region-scoped catalog queries', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
const queryClient = createTestQueryClient()
|
|
const removeSpy = jest.spyOn(queryClient, 'removeQueries')
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, queryClient, 8)
|
|
|
|
for (const key of ['all-products', 'stores', 'slots', 'availability', 'store-with-products']) {
|
|
expect(removeSpy).toHaveBeenCalledWith({ queryKey: [key] })
|
|
}
|
|
})
|
|
|
|
it('REGSW-08: sets the new region, falling back to its effective bound', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient())
|
|
|
|
expect(useRegionStore.getState().selectedRegionId).toBe(REGION_2.id)
|
|
expect(useRegionStore.getState().selectedBoundId).toBe(REGION_2.effectiveBoundId)
|
|
expect(REGION_2.effectiveBoundId).toBe(8)
|
|
})
|
|
|
|
it('REGSW-09: invalidates all queries after the switch', async () => {
|
|
seedRegion(REGION_1 as any, 7)
|
|
const queryClient = createTestQueryClient()
|
|
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
|
|
|
|
await confirmRegionSwitch(REGION_2 as any, queryClient, 8)
|
|
|
|
expect(invalidateSpy).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('PENDING-05: signed out does not sync the pending address', async () => {
|
|
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
|
|
|
|
renderWithProviders(<PendingAddressSync />, { auth: false })
|
|
await flush(3)
|
|
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(0)
|
|
expect(pendingSnapshot()).toBe(JSON.stringify(PENDING_INPUT))
|
|
})
|
|
|
|
it('PENDING-06: signed in posts the pending address, clears it and invalidates addresses', async () => {
|
|
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
|
|
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
|
|
|
|
renderWithProviders(<PendingAddressSync />, { auth: false })
|
|
await flush(3)
|
|
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
|
|
expect(lastProcedureInput('user.address.createAddress')).toEqual(PENDING_INPUT)
|
|
expect(pendingSnapshot()).toBeUndefined()
|
|
expect(procedureInvalidations('user.address.getUserAddresses')).toHaveLength(1)
|
|
expect(procedureInvalidations('user.address.getDefaultAddress')).toHaveLength(1)
|
|
})
|
|
|
|
it('PENDING-07: signed in with no pending address creates nothing', async () => {
|
|
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
|
|
|
|
renderWithProviders(<PendingAddressSync />, { auth: false })
|
|
await flush(3)
|
|
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(0)
|
|
})
|
|
|
|
it('PENDING-08: a failed create keeps the draft and a later mount retries', async () => {
|
|
setProcedure('user.address.createAddress', { mode: 'error', error: new Error('boom') })
|
|
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
|
|
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
|
|
|
|
const first = renderWithProviders(<PendingAddressSync />, { auth: false })
|
|
await flush(3)
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
|
|
expect(pendingSnapshot()).toBe(JSON.stringify(PENDING_INPUT))
|
|
|
|
// Remount: a later authenticated mount retries the kept draft.
|
|
first.unmount()
|
|
renderWithProviders(<PendingAddressSync />, { auth: false })
|
|
await flush(3)
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(2)
|
|
})
|
|
|
|
it('PENDING-09: concurrent auth events run one sync at a time', async () => {
|
|
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
|
|
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
|
|
|
|
// Keep the first create in flight by holding its *response* (a
|
|
// `mode: 'pending'` procedure is never recorded by the network mock), so the
|
|
// request is observable and a second one would be too.
|
|
const networkMock = global.fetch as any
|
|
let release!: () => void
|
|
const held = new Promise<void>((resolve) => {
|
|
release = resolve
|
|
})
|
|
;(global as any).fetch = jest.fn(async (input: any, init: any) => {
|
|
const response = await networkMock(input, init)
|
|
if (String(input).includes('user.address.createAddress')) await held
|
|
return response
|
|
})
|
|
|
|
try {
|
|
const { rerender } = renderWithProviders(<PendingAddressSync />, { auth: false })
|
|
await flush(3)
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
|
|
|
|
// Flip auth off and on again while the first create is still in flight.
|
|
__setAuthState({ isAuthenticated: false })
|
|
rerender(<PendingAddressSync />)
|
|
__setAuthState({ isAuthenticated: true })
|
|
rerender(<PendingAddressSync />)
|
|
await flush(3)
|
|
|
|
// The in-flight guard holds, so no second create is fired.
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
|
|
|
|
release()
|
|
await flush(3)
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
|
|
} finally {
|
|
;(global as any).fetch = networkMock
|
|
}
|
|
})
|
|
|
|
it('PENDING-10: unmounting before the read resolves cancels the sync', async () => {
|
|
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
|
|
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
|
|
|
|
const { unmount } = renderWithProviders(<PendingAddressSync />, { auth: false })
|
|
unmount()
|
|
await flush(3)
|
|
|
|
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(0)
|
|
expect(pendingSnapshot()).toBe(JSON.stringify(PENDING_INPUT))
|
|
})
|
|
|
|
it('CENTRAL-01: the initializer populates the central stores and reconciles slots', async () => {
|
|
seedJsonCache()
|
|
seedRegion(REGION_1 as any, 7)
|
|
__set(
|
|
'cart_items',
|
|
JSON.stringify([{ id: 1, skuId: 2, quantity: 1, slotId: 9999, addedAt: new Date().toISOString() }])
|
|
)
|
|
|
|
const { getByText } = renderWithProviders(
|
|
<CentralStoreInitializer>
|
|
<Text>child</Text>
|
|
</CentralStoreInitializer>,
|
|
{ auth: false }
|
|
)
|
|
expect(getByText('child')).toBeTruthy()
|
|
|
|
await waitFor(() => expect(useCentralProductStore.getState().products).toHaveLength(MERGED_PRODUCTS.length))
|
|
await waitFor(() => expect(useCentralSlotStore.getState().isSlotsLoaded).toBe(true))
|
|
expect(useCentralSlotStore.getState().productSlotsMap[2].slots.length).toBeGreaterThan(0)
|
|
|
|
// Reconcile rewrites the stale slot to the product's earliest valid slot.
|
|
await waitFor(() => {
|
|
const items = JSON.parse(__snapshot().cart_items ?? '[]')
|
|
expect(items[0]?.slotId).toBe(1851)
|
|
})
|
|
})
|
|
|
|
it('CENTRAL-02: unmounting stops the initializer without further fetching', async () => {
|
|
seedJsonCache()
|
|
seedRegion(REGION_1 as any, 7)
|
|
|
|
const { unmount } = renderWithProviders(
|
|
<CentralStoreInitializer>
|
|
<Text>child</Text>
|
|
</CentralStoreInitializer>,
|
|
{ auth: false }
|
|
)
|
|
|
|
await waitFor(() => expect(useCentralProductStore.getState().products.length).toBeGreaterThan(0))
|
|
const callsBefore = jsonCallsFor(productsCacheUrl()).length
|
|
expect(callsBefore).toBeGreaterThan(0)
|
|
|
|
unmount()
|
|
await flush(2)
|
|
|
|
expect(jsonCallsFor(productsCacheUrl())).toHaveLength(callsBefore)
|
|
})
|
|
})
|