freshyo/apps/user-ui/tests/lib/cart-query-hooks.test.tsx
2026-10-18 21:51:01 +05:30

509 lines
18 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Section 25 — Cart hook contract.
*
* Covers `apps/user-ui/hooks/cart-query-hooks.tsx`: the local-cart CRUD helpers
* behind `useAddToCart` / `useUpdateCartItem` / `useRemoveFromCart`, the
* `useGetCart` enrichment + totals, `useReconcileCartSlots`, and the exported
* per-region snapshot helpers (`clearLocalCart`, `stashRegionCarts`,
* `restoreRegionCarts`).
*
* The helpers talk to `StorageServiceCasual` directly, so every write lands in
* the in-memory secure-store mock and can be read back with `__snapshot()`.
*/
import * as React from 'react'
import { act, waitFor } from '@testing-library/react-native'
import { QueryClient } from '@tanstack/react-query'
import { StorageServiceCasual } from 'common-ui'
import {
useGetCart,
useAddToCart,
useUpdateCartItem,
useRemoveFromCart,
useReconcileCartSlots,
clearLocalCart,
stashRegionCarts,
restoreRegionCarts,
type CartType,
} from '@/hooks/cart-query-hooks'
import { renderWithProviders, seedCentralStores, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { MERGED_PRODUCTS } from '../fixtures'
const ADDED_AT = '2024-01-01T00:00:00.000Z'
const REGULAR_KEY = 'cart_items'
const FLASH_KEY = 'flash_cart_items'
const makeLine = (id: number, skuId: number, quantity: number, slotId: number) => ({
id,
skuId,
quantity,
slotId,
addedAt: ADDED_AT,
})
function seedCart(key: string, lines: any[]) {
__set(key, JSON.stringify(lines))
}
/** Read a cart (or region snapshot) straight out of the storage mock. */
function stored(key = REGULAR_KEY): any[] {
const raw = __snapshot()[key]
return raw ? JSON.parse(raw) : []
}
/* -------------------------------------------------------------------------- */
/* Probes: expose the hook's return value to the test body. */
/* -------------------------------------------------------------------------- */
interface ProbeApi {
current: any
}
function GetCartProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useGetCart({ refetchOnWindowFocus: false }, cartType)
return null
}
function AddProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useAddToCart({ showSuccessAlert: false, showErrorAlert: false }, cartType)
return null
}
function UpdateProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false }, cartType)
return null
}
function RemoveProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false }, cartType)
return null
}
function ReconcileProbe() {
useReconcileCartSlots()
return null
}
/** Let an async mutation settle inside `act`. */
async function run<T>(fn: () => Promise<T>): Promise<T | undefined> {
let result: T | undefined
await act(async () => {
result = await fn()
// Let react-query's notify manager `setTimeout(0)` flush inside `act`.
await new Promise((resolve) => setTimeout(resolve, 0))
})
return result
}
/**
* Same defaults as the shared harness client, except mutations use `gcTime: 0`.
* React Query's `Mutation` otherwise schedules a 5-minute GC timeout on
* unmount, which keeps the jest process alive after the run has finished.
*/
function createCartQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: Infinity,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false, gcTime: 0 },
},
})
}
function mount(ui: React.ReactElement, queryClient: QueryClient = createCartQueryClient()) {
return renderWithProviders(ui, { auth: false, queryClient })
}
describe('Cart query hooks', () => {
beforeEach(() => resetAllMocks())
it('CARTQ-01: add new item writes a storage line with id 1, quantity and slot', async () => {
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
await run(() => api.current.addToCartAsync(2, 2, 1849))
const lines = stored()
expect(lines).toHaveLength(1)
expect(lines[0]).toMatchObject({ id: 1, skuId: 2, quantity: 2, slotId: 1849 })
expect(lines[0].addedAt).toEqual(expect.any(String))
})
it('CARTQ-02: add existing SKU increments the quantity and moves the slot when provided', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
await run(() => api.current.addToCartAsync(2, 3, 1850))
expect(stored()).toHaveLength(1)
expect(stored()[0]).toMatchObject({ id: 1, skuId: 2, quantity: 5, slotId: 1850 })
})
it('CARTQ-03: adding an existing SKU without a slot leaves the slot unchanged', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
// The public `addToCart`/`addToCartAsync` guard slotId, but the raw mutation
// passes `undefined` through to `addToLocalCart`, which then keeps the slot.
await run(() => api.current.mutateAsync({ skuId: 2, quantity: 1, slotId: undefined } as any))
expect(stored()).toHaveLength(1)
expect(stored()[0]).toMatchObject({ id: 1, skuId: 2, quantity: 3, slotId: 1849 })
})
it('CARTQ-04: adding without a slot throws "slotId is required for adding to cart"', async () => {
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
expect(() => api.current.addToCart(2, 1)).toThrow('slotId is required for adding to cart')
expect(() => api.current.addToCartAsync(2, 1)).toThrow('slotId is required for adding to cart')
// Nothing reached storage.
expect(stored()).toEqual([])
})
it('CARTQ-05: new ids are allocated from the current maximum, not the length', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 1, 1849), makeLine(5, 5, 1, 1850)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
await run(() => api.current.addToCartAsync(8, 1, 1852))
expect(stored().map((item) => item.id)).toEqual([1, 5, 6])
})
it('CARTQ-06: update item persists the new quantity', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<UpdateProbe api={api} />)
await run(() => api.current.updateCartItemAsync(1, 5))
expect(stored()).toHaveLength(1)
expect(stored()[0].quantity).toBe(5)
})
it('CARTQ-07: updating a missing item leaves the cart unchanged', async () => {
const seeded = [makeLine(1, 2, 2, 1849)]
seedCart(REGULAR_KEY, seeded)
const api: ProbeApi = { current: null }
mount(<UpdateProbe api={api} />)
await run(() => api.current.updateCartItemAsync(999, 5))
expect(stored()).toEqual(seeded)
})
it('CARTQ-08: remove filters the line out of the cart', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 1, 1850)])
const api: ProbeApi = { current: null }
mount(<RemoveProbe api={api} />)
await run(() => api.current.removeFromCartAsync(1))
expect(stored()).toEqual([makeLine(2, 5, 1, 1850)])
})
it('CARTQ-09: removing a missing item leaves the cart unchanged', async () => {
const seeded = [makeLine(1, 2, 2, 1849)]
seedCart(REGULAR_KEY, seeded)
const api: ProbeApi = { current: null }
mount(<RemoveProbe api={api} />)
await run(() => api.current.removeFromCartAsync(999))
expect(stored()).toEqual(seeded)
})
it('CARTQ-10: clearLocalCart stores an empty array', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
await clearLocalCart('regular')
expect(stored()).toEqual([])
expect(JSON.parse(__snapshot()[REGULAR_KEY])).toEqual([])
})
it('CARTQ-11: the flash cart is stored separately and leaves the regular cart alone', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} cartType="flash" />)
await run(() => api.current.addToCartAsync(8, 3, 0))
expect(stored(FLASH_KEY)).toEqual([expect.objectContaining({ id: 1, skuId: 8, quantity: 3, slotId: 0 })])
expect(stored(REGULAR_KEY)).toEqual([makeLine(1, 2, 2, 1849)])
})
it('CARTQ-12: corrupt cart JSON surfaces as an error and is left in place (no fallback)', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [] as any)
__set(REGULAR_KEY, '{not json')
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.error).toBeTruthy())
expect(api.current.error).toBeInstanceOf(Error)
expect(api.current.data).toBeUndefined()
// Current behaviour: no fallback — the corrupt blob is not repaired.
expect(__snapshot()[REGULAR_KEY]).toBe('{not json')
})
it('CARTQ-13: useGetCart enriches lines from the central product store', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
// P_CHICKEN (id 2) price 215 -> subtotal 215 * 2.
// Current behaviour: the enriched line surfaces only the six cart fields;
// the product's name / unitNotation / marketPrice feed the lookup but are
// not part of the returned line shape.
expect(api.current.cartItems).toEqual([
{
id: 1,
skuId: 2,
quantity: 2,
addedAt: ADDED_AT,
subtotal: 430,
slotId: 1849,
},
])
expect(api.current.data.items).toEqual(api.current.cartItems)
})
it('CARTQ-14: a line whose product is missing from the store is hidden', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 999, 1, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toEqual([])
expect(api.current.isEmpty).toBe(true)
expect(api.current.hasItems).toBe(false)
})
it('CARTQ-15: a line whose SKU has no slot entry is hidden', async () => {
// Product 777 exists in the product store but not in PRODUCT_AVAILABILITY,
// so it never appears in `productSlotsMap`.
const ghost = { ...MERGED_PRODUCTS[0], id: 777, name: 'Ghost Product' }
seedCentralStores({ products: [...MERGED_PRODUCTS, ghost] })
seedCart(REGULAR_KEY, [makeLine(1, 777, 1, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toEqual([])
expect(api.current.isEmpty).toBe(true)
})
it('CARTQ-16: a zero-quantity line is preserved', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 0, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toHaveLength(1)
expect(api.current.cartItems[0]).toMatchObject({ quantity: 0, subtotal: 0 })
expect(api.current.isEmpty).toBe(false)
})
it('CARTQ-17: the query stays disabled (loading false, no data) until products load', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await flush()
// No products in the central store -> `enabled` is false, so the query never
// fetches: React Query reports `isLoading === false` and no data.
expect(api.current.isLoading).toBe(false)
expect(api.current.data).toBeUndefined()
act(() => {
seedCentralStores()
})
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toHaveLength(1)
})
it('CARTQ-18: totals sum the enriched subtotals', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 4, 1850)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
// 215 * 2 + 15 * 4 = 490
expect(api.current.cartItems.map((item: any) => item.subtotal)).toEqual([430, 60])
expect(api.current.totalItems).toBe(2)
expect(api.current.totalPrice).toBe(490)
expect(api.current.data.totalItems).toBe(2)
expect(api.current.data.totalAmount).toBe(490)
})
it('CARTQ-19: reconcile keeps a line whose slot is still valid', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(stored()).toEqual([makeLine(1, 2, 2, 1849)])
expect(invalidate).not.toHaveBeenCalled()
})
it('CARTQ-20: reconcile moves an invalid slot to the nearest by delivery time', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 9999)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
mount(<ReconcileProbe />, queryClient)
// SKU 2 is served by slots 1849/1850/1851/1852; 1851 has the earliest
// deliveryTime (now - 2h), so it is the "nearest".
await waitFor(() => expect(stored()[0].slotId).toBe(1851))
expect(invalidate).toHaveBeenCalledWith({ queryKey: ['local-cart-regular'] })
expect(stored()[0]).toMatchObject({ id: 1, skuId: 2, quantity: 2 })
})
it('CARTQ-21: reconcile keeps a line whose product has no slots at all', async () => {
seedCentralStores()
// P_NO_SLOT (id 10) exists in productAvailability but is in no delivery slot.
seedCart(REGULAR_KEY, [makeLine(1, 10, 2, 7)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(stored()).toEqual([makeLine(1, 10, 2, 7)])
expect(invalidate).not.toHaveBeenCalled()
})
it('CARTQ-22: reconcile does nothing while the slot store is not loaded', async () => {
// No `seedCentralStores()` -> isSlotsLoaded false and an empty productSlotsMap.
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 9999)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
const setItem = jest.spyOn(StorageServiceCasual, 'setItem')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(setItem).not.toHaveBeenCalled()
expect(invalidate).not.toHaveBeenCalled()
expect(stored()).toEqual([makeLine(1, 2, 2, 9999)])
})
it('CARTQ-23: reconcile writes nothing when every line is already valid', async () => {
seedCentralStores()
// SKU 2 is served by slots 1849/1850/1851/1852 and SKU 5 by 1849/1852, so
// both of these lines are already valid.
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 1, 1852)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
const setItem = jest.spyOn(StorageServiceCasual, 'setItem')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(setItem).not.toHaveBeenCalled()
expect(invalidate).not.toHaveBeenCalled()
})
it('CARTQ-24: stashRegionCarts snapshots sku, slot and quantity for both carts', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 4, 1850)])
seedCart(FLASH_KEY, [makeLine(1, 8, 3, 0)])
await stashRegionCarts(1)
expect(stored('region_carts_1')).toEqual({
regular: [
{ skuId: 2, slotId: 1849, quantity: 2 },
{ skuId: 5, slotId: 1850, quantity: 4 },
],
flash: [{ skuId: 8, slotId: 0, quantity: 3 }],
})
})
it('CARTQ-25: restoreRegionCarts reissues ids and defaults missing/invalid quantities to 1', async () => {
__set(
'region_carts_2',
JSON.stringify({
regular: [
{ skuId: 2, slotId: 1849, quantity: 3 },
{ skuId: 5, slotId: 1850, quantity: 0 },
],
flash: [{ skuId: 8, slotId: 0 }],
})
)
await restoreRegionCarts(2)
const regular = stored(REGULAR_KEY)
expect(regular.map((item) => item.id)).toEqual([1, 2])
expect(regular.map((item) => [item.skuId, item.slotId, item.quantity])).toEqual([
[2, 1849, 3],
[5, 1850, 1],
])
expect(regular.every((item) => typeof item.addedAt === 'string')).toBe(true)
const flash = stored(FLASH_KEY)
expect(flash).toHaveLength(1)
expect(flash[0]).toMatchObject({ id: 1, skuId: 8, slotId: 0, quantity: 1 })
})
it('CARTQ-26: a corrupt region snapshot restores both carts to empty', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
seedCart(FLASH_KEY, [makeLine(1, 8, 3, 0)])
__set('region_carts_3', '{not json')
await restoreRegionCarts(3)
expect(stored(REGULAR_KEY)).toEqual([])
expect(stored(FLASH_KEY)).toEqual([])
})
it('CARTQ-27: stash -> clear -> restore round-trips a region switch', async () => {
const regular = [makeLine(1, 2, 2, 1849), makeLine(2, 5, 1, 1850)]
const flash = [makeLine(1, 8, 3, 0)]
seedCart(REGULAR_KEY, regular)
seedCart(FLASH_KEY, flash)
await stashRegionCarts(1)
await clearLocalCart('regular')
await clearLocalCart('flash')
expect(stored(REGULAR_KEY)).toEqual([])
expect(stored(FLASH_KEY)).toEqual([])
await restoreRegionCarts(1)
expect(stored(REGULAR_KEY).map((item) => [item.id, item.skuId, item.slotId, item.quantity])).toEqual([
[1, 2, 1849, 2],
[2, 5, 1850, 1],
])
expect(stored(FLASH_KEY).map((item) => [item.id, item.skuId, item.slotId, item.quantity])).toEqual([
[1, 8, 0, 3],
])
})
})