freshyo/apps/user-ui/tests/hooks/cart-storage.test.tsx
2026-10-02 13:32:27 +05:30

335 lines
11 KiB
TypeScript

/**
* Cart storage mechanics (hooks/cart-query-hooks.tsx) — the local cart is a
* JSON blob in StorageServiceCasual, so every write is read-modify-write.
*
* Covers the money-affecting edge cases the screen tests cannot reach: live
* repricing, zero quantities, unknown products, concurrent writes and
* useReconcileCartSlots' slot repair. Known bugs are pinned — see
* tests/KNOWN-GAPS.md.
*/
import React from 'react'
import { renderHook, waitFor } from '@testing-library/react-native'
import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual'
import {
useAddToCart,
useGetCart,
useReconcileCartSlots,
useUpdateCartItem,
clearLocalCart,
} from '@/hooks/cart-query-hooks'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { resetStorage } from '../mocks/api'
import { Providers } from '../helpers/render'
const SKU_IN_STOCK = 2 // Chicken Breast 500 g, price 215
const SKU_OTHER = 5 // Cucumber(Kheera), price 15
const SLOT_A = 1849
const SLOT_B = 1847
const product = (id: number, price: number, over: Record<string, unknown> = {}) => ({
id,
name: `Product ${id}`,
price,
marketPrice: price + 20,
flashPrice: null,
incrementStep: 1,
images: [],
productQuantity: 1,
unitNotation: 'pc',
isComboOnly: false,
...over,
})
const slotInfo = (slots: number[], over: Record<string, unknown> = {}) => ({
slots: slots.map((id) => ({
id,
deliveryTime: new Date(Date.now() + 3 * 3600_000).toISOString(),
freezeTime: new Date(Date.now() + 2 * 3600_000).toISOString(),
products: [],
})),
isOutOfStock: false,
isFlashAvailable: false,
isSuspended: false,
...over,
})
/** Point the central stores at a known product/slot universe. */
const setCentral = (
products: Record<number, unknown>,
slotMap: Record<number, unknown>,
isSlotsLoaded = true
) => {
useCentralProductStore.setState({
products: Object.values(products) as never,
productsById: products as never,
})
useCentralSlotStore.setState({
slots: [],
productSlotsMap: slotMap as never,
isSlotsLoaded,
})
}
const readCart = async (key = 'cart_items') => {
const raw = await StorageServiceCasual.getItem(key)
return raw ? JSON.parse(raw) : []
}
const seedCart = async (items: unknown[], key = 'cart_items') =>
StorageServiceCasual.setItem(key, JSON.stringify(items))
const line = (over: Record<string, unknown> = {}) => ({
id: 1,
skuId: SKU_IN_STOCK,
quantity: 1,
slotId: SLOT_A,
addedAt: new Date().toISOString(),
...over,
})
const wrapper = ({ children }: { children?: React.ReactNode }) => (
<Providers centralStores={false}>{children}</Providers>
)
const renderGetCart = (cartType: 'regular' | 'flash' = 'regular') =>
renderHook(() => useGetCart({}, cartType), { wrapper })
describe('cart storage', () => {
beforeEach(async () => {
await resetStorage()
useCentralProductStore.setState({ products: [], productsById: {} })
useCentralSlotStore.setState({ slots: [], productSlotsMap: {}, isSlotsLoaded: false })
})
it('prices a line from the live product record, not the price at add time', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A]) }
)
await seedCart([line()])
const first = renderGetCart()
await waitFor(() => expect(first.result.current.totalPrice).toBe(215))
first.unmount()
// The catalog reprices the SKU underneath the cart; storage is untouched.
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 300) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A]) }
)
expect(await readCart()).toEqual([expect.objectContaining({ quantity: 1 })])
const second = renderGetCart()
await waitFor(() => expect(second.result.current.totalPrice).toBe(300))
})
it('multiplies price by quantity', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A]) }
)
await seedCart([line({ quantity: 3 })])
const { result } = renderGetCart()
await waitFor(() => expect(result.current.totalPrice).toBe(645))
expect(result.current.cartItems).toHaveLength(1)
expect(result.current.totalItems).toBe(1)
})
/**
* KNOWN GAP: updateLocalCartItem writes the quantity through with no zero or
* negative guard, so a 0-qty line stays in storage and keeps counting as a
* cart row. The UI always routes deletion through removeFromCart, so this is
* only reachable from a direct call.
*/
it('persists a zero quantity with no guard', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A]) }
)
await seedCart([line()])
const { result } = renderHook(() => useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false }), {
wrapper,
})
await result.current.updateCartItemAsync(1, 0)
expect(await readCart()).toEqual([
expect.objectContaining({ id: 1, skuId: SKU_IN_STOCK, quantity: 0 }),
])
})
/**
* KNOWN GAP: useGetCart drops any line whose skuId is missing from
* productsById or productSlotsMap. A cart written while one product was
* absent from the cache renders fewer rows than storage holds, and the
* dropped lines are never surfaced to the user.
*/
it('drops lines whose product is missing from the central stores', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A]) }
)
await seedCart([line({ id: 1 }), line({ id: 2, skuId: SKU_OTHER })])
const { result } = renderGetCart()
await waitFor(() => expect(result.current.cartItems).toHaveLength(1))
expect(result.current.cartItems[0].skuId).toBe(SKU_IN_STOCK)
// The line is gone from the derived view but still on disk.
expect(await readCart()).toHaveLength(2)
})
it('ignores lines whose product has no slot entry', async () => {
setCentral({ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) }, {})
await seedCart([line()])
const { result } = renderGetCart()
await waitFor(() => expect(result.current.isLoading).toBe(false))
expect(result.current.cartItems).toHaveLength(0)
})
/**
* KNOWN GAP: addToLocalCart is read-modify-write with no locking, so two adds
* issued in the same tick both read the pre-add cart and the second write
* erases the first. Adding two different SKUs back-to-back yields one line.
*/
it('loses the first of two concurrent adds', async () => {
setCentral(
{
[SKU_IN_STOCK]: product(SKU_IN_STOCK, 215),
[SKU_OTHER]: product(SKU_OTHER, 15),
},
{
[SKU_IN_STOCK]: slotInfo([SLOT_A]),
[SKU_OTHER]: slotInfo([SLOT_A]),
}
)
const { result } = renderHook(
() => useAddToCart({ showSuccessAlert: false, showErrorAlert: false }),
{ wrapper }
)
// Neither is awaited before the second is fired: both read the empty cart.
const first = result.current.addToCartAsync(SKU_IN_STOCK, 1, SLOT_A)
const second = result.current.addToCartAsync(SKU_OTHER, 1, SLOT_A)
await Promise.all([first, second])
const stored = await readCart()
expect(stored).toHaveLength(1)
expect(stored[0].skuId).toBe(SKU_OTHER)
})
it('keeps the flash and regular carts in separate storage keys', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A]) }
)
await seedCart([line()], 'cart_items')
await seedCart([line({ id: 1, slotId: 0 })], 'flash_cart_items')
const regular = renderGetCart('regular')
const flash = renderGetCart('flash')
await waitFor(() => expect(regular.result.current.cartItems).toHaveLength(1))
await waitFor(() => expect(flash.result.current.cartItems).toHaveLength(1))
expect(regular.result.current.cartItems[0].slotId).toBe(SLOT_A)
expect(flash.result.current.cartItems[0].slotId).toBe(0)
await clearLocalCart('regular')
expect(await readCart('cart_items')).toEqual([])
expect(await readCart('flash_cart_items')).toHaveLength(1)
})
})
describe('useReconcileCartSlots', () => {
beforeEach(async () => {
await resetStorage()
})
it('re-points a line at the nearest slot when its stored slot is gone', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_B]) }
)
await seedCart([line({ slotId: 9999 })])
renderHook(() => useReconcileCartSlots(), { wrapper })
await waitFor(async () => expect(await readCart()).toHaveLength(1))
expect((await readCart())[0].slotId).toBe(SLOT_B)
})
it('leaves a line alone when its stored slot is still valid', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A, SLOT_B]) }
)
await seedCart([line({ slotId: SLOT_B })])
renderHook(() => useReconcileCartSlots(), { wrapper })
await waitFor(async () => expect(await readCart()).toHaveLength(1))
expect((await readCart())[0].slotId).toBe(SLOT_B)
})
/**
* A line whose product has no slots can't be re-pointed, but it must not be
* deleted: it stays on disk (and is hidden from the derived view) so the user
* can still act on it once slots return.
*/
it('keeps a line whose product has no slots instead of deleting it', async () => {
setCentral(
{
[SKU_IN_STOCK]: product(SKU_IN_STOCK, 215),
[SKU_OTHER]: product(SKU_OTHER, 15),
},
{
[SKU_IN_STOCK]: slotInfo([SLOT_B]),
[SKU_OTHER]: slotInfo([]),
}
)
await seedCart([line({ id: 1, slotId: 9999 }), line({ id: 2, skuId: SKU_OTHER, slotId: 9999 })])
renderHook(() => useReconcileCartSlots(), { wrapper })
await waitFor(async () => {
const stored = await readCart()
expect(stored.find((i: { id: number }) => i.id === 1).slotId).toBe(SLOT_B)
})
const stored = await readCart()
expect(stored).toHaveLength(2)
// SKU_OTHER is kept untouched rather than dropped from storage.
expect(stored.find((i: { id: number }) => i.id === 2).skuId).toBe(SKU_OTHER)
expect(stored.find((i: { id: number }) => i.id === 2).slotId).toBe(9999)
})
/**
* The reconciler re-runs whenever productSlotsMap changes, so a line left
* pointing at an expired slot is repaired on the next slot refresh.
*/
it('re-reconciles when the slots map changes', async () => {
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_B]) }
)
await seedCart([line({ slotId: 9999 })])
const { rerender } = renderHook(() => useReconcileCartSlots(), { wrapper })
await waitFor(async () => expect((await readCart())[0].slotId).toBe(SLOT_B))
// The cart is left pointing at a stale slot again, then slots change.
await seedCart([line({ id: 1, slotId: 7777 })])
setCentral(
{ [SKU_IN_STOCK]: product(SKU_IN_STOCK, 215) },
{ [SKU_IN_STOCK]: slotInfo([SLOT_A]) }
)
rerender(undefined)
await waitFor(async () => expect((await readCart())[0].slotId).toBe(SLOT_A))
})
})