1529 lines
56 KiB
TypeScript
1529 lines
56 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
/**
|
|
* Catalogue section 6 — Home (`tests/pages/home.test.tsx`, HOME-01..112).
|
|
*
|
|
* Products / availability / slots / stores come from the versioned CDN documents
|
|
* (`seedBoot`); the consts + orders come from the tRPC procedure registry. The
|
|
* home page mounts the real `AddToCartDialog` and `FloatingCartBar`, so the
|
|
* dialog rows are driven through `useCartStore` and the bar rows through the
|
|
* `cart_items` / `flash_cart_items` storage keys.
|
|
*
|
|
* Auth is mocked (deterministic) so the next-order glimpse can be switched
|
|
* between signed-out (renders nothing) and signed-in without the real provider's
|
|
* async bootstrap.
|
|
*/
|
|
import * as React from 'react'
|
|
import {
|
|
Alert,
|
|
DeviceEventEmitter,
|
|
Image,
|
|
Linking,
|
|
SectionList,
|
|
StyleSheet,
|
|
} from 'react-native'
|
|
import { act, fireEvent, waitFor, within } from '@testing-library/react-native'
|
|
import dayjs from 'dayjs'
|
|
import { QueryClient } from '@tanstack/react-query'
|
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
|
|
|
import Home from '@/app/(drawer)/(tabs)/home/index'
|
|
import FloatingCartBar from '@/components/floating-cart-bar'
|
|
|
|
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 { useNavigationStore } from '@/src/store/navigationStore'
|
|
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'
|
|
import { StorageServiceCasual, tw } from 'common-ui'
|
|
|
|
import { flush, renderWithProviders, seedBoot, seedSelectedAddress } from '../helpers/test-utils'
|
|
import { resetAllMocks } from '../helpers/reset'
|
|
import {
|
|
procedureQueryCalls,
|
|
setProcedure,
|
|
} from '../mocks/trpc-client'
|
|
import {
|
|
jsonCallsFor,
|
|
setJsonError,
|
|
setJsonPending,
|
|
setJsonResponse,
|
|
} from '../mocks/fetch-json'
|
|
import { __set, __snapshot } from '../mocks/secure-store-mock'
|
|
import { router } from '../mocks/expo-router-mock'
|
|
import { __setAuthState } from '../mocks/auth-context'
|
|
import {
|
|
A1,
|
|
AUTH_USER,
|
|
AVAILABILITY,
|
|
CART_FLASH,
|
|
CART_REG,
|
|
CONSTS_FLASH_OFF,
|
|
P_CHICKEN,
|
|
SLOTS,
|
|
SLOTS_RESPONSE,
|
|
PRODUCTS,
|
|
TAGS,
|
|
TEST_JWT,
|
|
O1,
|
|
availabilityCacheUrl,
|
|
productsCacheUrl,
|
|
slotsCacheUrl,
|
|
storesCacheUrl,
|
|
} from '../fixtures'
|
|
|
|
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
|
|
|
|
/** 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])
|
|
},
|
|
}
|
|
})
|
|
|
|
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
|
|
|
jest.setTimeout(30000)
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Helpers */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
function storedCart(key = 'cart_items'): any[] {
|
|
const raw = __snapshot()[key]
|
|
return raw ? JSON.parse(raw) : []
|
|
}
|
|
|
|
/** Turn a list of nodes into their numeric `<prefix><id>` testIDs. */
|
|
function idsFrom(nodes: any[], prefix: string): number[] {
|
|
return nodes.map((node) => Number(String(node.props.testID).replace(prefix, '')))
|
|
}
|
|
|
|
/**
|
|
* The product ids the main list currently maps. Read from the SectionList's
|
|
* `sections` prop (the visible window), because a plain render only mounts the
|
|
* first `initialNumToRender` rows.
|
|
*/
|
|
function mainListIds(utils: any): number[] {
|
|
const sections = utils.UNSAFE_getByType(SectionList).props.sections as any[]
|
|
return (sections[0].data as any[]).flat().map((product: any) => product.id)
|
|
}
|
|
|
|
async function renderHome(options: { queryClient?: any } = {}) {
|
|
const utils = renderWithProviders(<Home />, {
|
|
auth: false,
|
|
queryClient: createCartQueryClient(),
|
|
...options,
|
|
})
|
|
await flush(3)
|
|
return utils
|
|
}
|
|
|
|
/** Queue a product for the add-to-cart dialog, then let it settle. */
|
|
async function openDialog(product: any, cart?: string) {
|
|
if (cart) __set('cart_items', cart)
|
|
const utils = await renderHome()
|
|
await act(async () => {
|
|
useCartStore.getState().setAddedToCartProduct({ productId: product.id, product })
|
|
})
|
|
await flush(2)
|
|
return utils
|
|
}
|
|
|
|
/** Render just the floating bar (Home only mounts the regular variant). */
|
|
async function renderBar(props: Record<string, any> = {}, queryClient?: any) {
|
|
const utils = renderWithProviders(<FloatingCartBar {...props} />, {
|
|
auth: false,
|
|
queryClient: queryClient ?? createCartQueryClient(),
|
|
})
|
|
await flush(2)
|
|
return utils
|
|
}
|
|
|
|
const productsResponse = (products: any[], tags = TAGS) => ({
|
|
products,
|
|
count: products.length,
|
|
tags,
|
|
})
|
|
|
|
/** Replace the slots CDN document (the strip reads `slots.json?v=123`). */
|
|
function setSlots(slots: any[]) {
|
|
const productAvailability = slots.flatMap((slot) =>
|
|
slot.products.map((product: any) => ({ id: product.id }))
|
|
)
|
|
setJsonResponse(`${slotsCacheUrl()}?v=123`, {
|
|
slots,
|
|
productAvailability,
|
|
count: slots.length,
|
|
})
|
|
}
|
|
|
|
/** Re-fire the screen focus through `useMarkDataFetchers`. */
|
|
async function emitFocus() {
|
|
await act(async () => {
|
|
Array.from(mockFocusCallbacks).forEach((callback) => callback())
|
|
})
|
|
}
|
|
|
|
/** Emit the global manual-refresh event the home screen subscribes to. */
|
|
async function emitManualRefresh() {
|
|
await act(async () => {
|
|
DeviceEventEmitter.emit(REFRESH_EVENT)
|
|
})
|
|
await flush(2)
|
|
}
|
|
|
|
/** The dialog labels each slot row with its delivery minute. */
|
|
const slotTestId = (slot: { deliveryTime: string }) =>
|
|
`slot-${dayjs(slot.deliveryTime).format('YYYY-MM-DD-HH-mm')}`
|
|
|
|
const CART_LINE_ADDED_AT = '2024-01-01T00:00:00.000Z'
|
|
|
|
const cartLine = (id: number, skuId: number, quantity: number, slotId: number) =>
|
|
JSON.stringify([{ id, skuId, quantity, slotId, addedAt: CART_LINE_ADDED_AT }])
|
|
|
|
const productByIdFrom = (id: number) => PRODUCTS.find((product) => product.id === id)
|
|
|
|
/**
|
|
* Same as the shared harness client except mutations use `gcTime: 0` so their
|
|
* 5-minute GC timers don't keep the process alive.
|
|
*/
|
|
function createCartQueryClient(): QueryClient {
|
|
return new QueryClient({
|
|
defaultOptions: {
|
|
queries: {
|
|
retry: false,
|
|
gcTime: Infinity,
|
|
staleTime: Infinity,
|
|
refetchOnWindowFocus: false,
|
|
},
|
|
mutations: { retry: false, gcTime: 0 },
|
|
},
|
|
})
|
|
}
|
|
|
|
/** Exposes the shared navigation-target store to the test body. */
|
|
function NavTargetProbe({ api }: { api: { current: string | null } }) {
|
|
api.current = useNavigationTarget().navigationTarget
|
|
return null
|
|
}
|
|
|
|
function signedIn() {
|
|
__setAuthState({
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
user: AUTH_USER,
|
|
userDetails: AUTH_USER,
|
|
token: TEST_JWT,
|
|
})
|
|
}
|
|
|
|
function setOrders(orders: any[]) {
|
|
setProcedure('user.order.getOrders', {
|
|
data: { data: orders, pagination: { totalPages: 1, total: orders.length, page: 1, pageSize: 50 } },
|
|
})
|
|
}
|
|
|
|
const tagWithProducts = (ids: number[], tagId = 1) => ({
|
|
...TAGS[0],
|
|
id: tagId,
|
|
productIds: ids,
|
|
})
|
|
|
|
/** Every merged catalogue id, used for big-list cases. */
|
|
function makeManyProducts(count: number) {
|
|
return Array.from({ length: count }, (_, index) => ({
|
|
...PRODUCTS[0],
|
|
id: index + 1,
|
|
name: `Product ${index + 1}`,
|
|
}))
|
|
}
|
|
|
|
describe('Home (HOME)', () => {
|
|
beforeEach(() => {
|
|
resetAllMocks()
|
|
mockFocusCallbacks.clear()
|
|
__setAuthState({
|
|
isAuthenticated: false,
|
|
isLoading: false,
|
|
user: null,
|
|
userDetails: null,
|
|
token: null,
|
|
})
|
|
seedBoot()
|
|
})
|
|
|
|
afterEach(() => {
|
|
jest.restoreAllMocks()
|
|
})
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 6.1 Loading, errors and empty states */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
it('HOME-01: products query pending shows the loading copy', async () => {
|
|
setJsonPending(productsCacheUrl())
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText('Loading products...')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-02: a rejected products request shows the error state', async () => {
|
|
setJsonError(productsCacheUrl(), new Error('offline'))
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText('Oops!')).toBeTruthy()
|
|
expect(getByText('Failed to load products')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-03: a rejected consts request shows the settings error', async () => {
|
|
setProcedure('common.essentialConsts', { mode: 'error', error: new Error('boom') })
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText('Oops!')).toBeTruthy()
|
|
expect(getByText('Failed to load app settings')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-04: no products/tags shows the empty state and no tag strip', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse([], []))
|
|
const { getByText, queryByTestId } = await renderHome()
|
|
|
|
expect(getByText('No products available')).toBeTruthy()
|
|
expect(queryByTestId('tag-tab-1')).toBeNull()
|
|
})
|
|
|
|
it('HOME-05: an active tag with an empty productIds shows the category empty copy', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([], 3)]))
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText('No products in this category yet')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-06: an empty products fetch still renders stores and slots', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse([], []))
|
|
const { getByText, getByTestId } = await renderHome()
|
|
|
|
expect(getByText('Our Stores')).toBeTruthy()
|
|
expect(getByTestId('slot-card-1849')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-07: while slots are loading the page renders without a slot strip', async () => {
|
|
setJsonPending(`${slotsCacheUrl()}?v=123`)
|
|
const { getByTestId, queryByText } = await renderHome()
|
|
|
|
expect(getByTestId('home-search')).toBeTruthy()
|
|
expect(queryByText('Upcoming Delivery Slots')).toBeNull()
|
|
})
|
|
|
|
it('HOME-08: a failing stores request omits the store section without a page error', async () => {
|
|
setJsonError(storesCacheUrl(), new Error('stores down'))
|
|
const { getByTestId, queryByText } = await renderHome()
|
|
|
|
expect(getByTestId('home-search')).toBeTruthy()
|
|
expect(queryByText('Our Stores')).toBeNull()
|
|
})
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 6.2 Tags and product grid */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
it('HOME-09: one tab per tag in API order and the first tag is active', async () => {
|
|
const { getByTestId, queryByTestId } = await renderHome()
|
|
|
|
expect(getByTestId('tag-tab-1')).toBeTruthy()
|
|
expect(getByTestId('tag-tab-2')).toBeTruthy()
|
|
expect(getByTestId('tag-tab-3')).toBeTruthy()
|
|
// Only the active (first) tag's grid is mounted.
|
|
expect(getByTestId('tag-grid-1')).toBeTruthy()
|
|
expect(queryByTestId('tag-grid-2')).toBeNull()
|
|
})
|
|
|
|
it('HOME-10: a tag with 8 products shows the first 6 and a Show More button', async () => {
|
|
const ids = [2, 5, 6, 7, 8, 9, 10, 150]
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts(ids)]))
|
|
const { getAllByTestId, getByTestId } = await renderHome()
|
|
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(6)
|
|
expect(getByTestId('tag-show-more-1')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-11: tapping the second tag switches the grid', async () => {
|
|
const { getByTestId, queryByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByTestId('tag-tab-2'))
|
|
|
|
expect(getByTestId('tag-grid-2')).toBeTruthy()
|
|
expect(queryByTestId('tag-grid-1')).toBeNull()
|
|
})
|
|
|
|
it('HOME-12: tapping Show More expands the tag and hides the button', async () => {
|
|
const ids = [2, 5, 6, 7, 8, 9, 10, 150]
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts(ids)]))
|
|
const { getAllByTestId, getByTestId, queryByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByTestId('tag-show-more-1'))
|
|
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(8)
|
|
expect(queryByTestId('tag-show-more-1')).toBeNull()
|
|
})
|
|
|
|
it('HOME-13: a tag with exactly 6 products has no Show More', async () => {
|
|
const ids = [2, 5, 6, 7, 8, 9]
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts(ids)]))
|
|
const { getAllByTestId, queryByTestId } = await renderHome()
|
|
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(6)
|
|
expect(queryByTestId('tag-show-more-1')).toBeNull()
|
|
})
|
|
|
|
it('HOME-14: a tag with 7 products shows Show More and expands to 7', async () => {
|
|
const ids = [2, 5, 6, 7, 8, 9, 10]
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts(ids)]))
|
|
const { getAllByTestId, getByTestId } = await renderHome()
|
|
|
|
expect(getByTestId('tag-show-more-1')).toBeTruthy()
|
|
fireEvent.press(getByTestId('tag-show-more-1'))
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(7)
|
|
})
|
|
|
|
it('HOME-15: the tag grid follows the admin productIds order', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([5, 2])]))
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(idsFrom(getAllByTestId(/^tag-product-/), 'tag-product-')).toEqual([5, 2])
|
|
})
|
|
|
|
it('HOME-16: duplicate ids in a tag productIds are rendered once (current: map keeps them)', async () => {
|
|
// Current gap: productsByTagId maps productIds without de-duplicating, so a
|
|
// repeated id renders the card twice. Pinned until the map deduplicates.
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([2, 2, 5])]))
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(getAllByTestId('tag-product-2')).toHaveLength(2)
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(3)
|
|
})
|
|
|
|
it('HOME-17: an unknown id in a tag productIds is skipped', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([2, 999])]))
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(1)
|
|
})
|
|
|
|
it('HOME-18: out-of-stock products are pushed to the end of the tag', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [tagWithProducts([6, 2, 9])]))
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(idsFrom(getAllByTestId(/^tag-product-/), 'tag-product-')).toEqual([2, 6, 9])
|
|
})
|
|
|
|
it('HOME-19: with slots not loaded a slotless product is not marked out of stock', async () => {
|
|
useCentralSlotStore.setState({ isSlotsLoaded: false })
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const card = getByTestId('product-item-10')
|
|
expect(within(card).queryByTestId('out-of-stock-badge')).toBeNull()
|
|
})
|
|
|
|
it('HOME-20: with slots loaded a slotless product is marked out of stock and moved last', async () => {
|
|
const { getAllByTestId, getByTestId } = await renderHome()
|
|
|
|
expect(within(getByTestId('product-item-10')).getByTestId('out-of-stock-badge')).toBeTruthy()
|
|
// It sorts after every in-stock item (2, 5, 8).
|
|
const order = idsFrom(getAllByTestId(/^product-item-/), 'product-item-')
|
|
expect(order.indexOf(10)).toBeGreaterThan(order.indexOf(8))
|
|
})
|
|
|
|
it('HOME-21: the isOutOfStock availability flag marks a product out of stock even with slots', async () => {
|
|
const current = useCentralSlotStore.getState().productSlotsMap
|
|
useCentralSlotStore.setState({
|
|
productSlotsMap: {
|
|
...current,
|
|
6: { ...current[6], slots: [SLOTS[0], SLOTS[1]], isOutOfStock: true },
|
|
},
|
|
} as any)
|
|
const { getByTestId } = await renderHome()
|
|
|
|
expect(within(getByTestId('product-item-6')).getByTestId('out-of-stock-badge')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-22: a product without a numeric id is omitted from the main list', async () => {
|
|
setJsonResponse(
|
|
productsCacheUrl(),
|
|
productsResponse([...PRODUCTS, { id: 'bad', name: 'Bad Item' } as any])
|
|
)
|
|
const { getByTestId, queryByText } = await renderHome()
|
|
|
|
expect(getByTestId('home-search')).toBeTruthy()
|
|
expect(queryByText('Bad Item')).toBeNull()
|
|
})
|
|
|
|
it('HOME-23: removing the active tag after a refresh does not crash (current: no fallback)', async () => {
|
|
// Current gap: `activeTagId` keeps the removed id, so TagScene renders the
|
|
// empty-category copy for the gone tag instead of falling back to the first
|
|
// tag's products.
|
|
const { getByTestId, getByText, queryByTestId, queryClient } = await renderHome()
|
|
|
|
fireEvent.press(getByTestId('tag-tab-3'))
|
|
expect(getByTestId('tag-grid-3')).toBeTruthy()
|
|
|
|
setJsonResponse(productsCacheUrl(), productsResponse(PRODUCTS, [TAGS[0], TAGS[1]]))
|
|
await act(async () => {
|
|
await queryClient.invalidateQueries()
|
|
})
|
|
await flush(2)
|
|
|
|
expect(queryByTestId('tag-tab-3')).toBeNull()
|
|
// The removed tag's scene is still the active one (no fallback).
|
|
expect(getByTestId('tag-grid-3')).toBeTruthy()
|
|
expect(getByText('No products in this category yet')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-24: expansion state is tracked per tag', async () => {
|
|
const ids = [2, 5, 6, 7, 8, 9, 10, 150]
|
|
setJsonResponse(
|
|
productsCacheUrl(),
|
|
productsResponse(PRODUCTS, [tagWithProducts(ids), TAGS[1]])
|
|
)
|
|
const { getAllByTestId, getByTestId, queryByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByTestId('tag-show-more-1'))
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(8)
|
|
|
|
fireEvent.press(getByTestId('tag-tab-2'))
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(1)
|
|
|
|
fireEvent.press(getByTestId('tag-tab-1'))
|
|
expect(getAllByTestId(/^tag-product-/)).toHaveLength(8)
|
|
expect(queryByTestId('tag-show-more-1')).toBeNull()
|
|
})
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 6.3 Main product list and pagination */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
it('HOME-25: 20 products render without Show More', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(makeManyProducts(20), []))
|
|
const { getAllByTestId, queryByTestId } = await renderHome()
|
|
|
|
expect(getAllByTestId(/^product-item-/)).toHaveLength(20)
|
|
expect(queryByTestId('products-show-more')).toBeNull()
|
|
})
|
|
|
|
it('HOME-26: 21 products render without Show More', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(makeManyProducts(21), []))
|
|
const { getAllByTestId, queryByTestId } = await renderHome()
|
|
|
|
expect(getAllByTestId(/^product-item-/)).toHaveLength(21)
|
|
expect(queryByTestId('products-show-more')).toBeNull()
|
|
})
|
|
|
|
it('HOME-27: 22 products render the first 21 plus Show More', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(makeManyProducts(22), []))
|
|
const utils = await renderHome()
|
|
|
|
expect(mainListIds(utils)).toHaveLength(21)
|
|
expect(utils.getByTestId('products-show-more')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-28: tapping Show More renders the 22nd card and hides the button', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(makeManyProducts(22), []))
|
|
const utils = await renderHome()
|
|
|
|
fireEvent.press(utils.getByTestId('products-show-more'))
|
|
|
|
expect(mainListIds(utils)).toHaveLength(22)
|
|
expect(utils.queryByTestId('products-show-more')).toBeNull()
|
|
})
|
|
|
|
it('HOME-29: 50 products page in 21-item batches to the full list', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(makeManyProducts(50), []))
|
|
const utils = await renderHome()
|
|
|
|
expect(mainListIds(utils)).toHaveLength(21)
|
|
|
|
fireEvent.press(utils.getByTestId('products-show-more'))
|
|
expect(mainListIds(utils)).toHaveLength(42)
|
|
|
|
fireEvent.press(utils.getByTestId('products-show-more'))
|
|
expect(mainListIds(utils)).toHaveLength(50)
|
|
expect(utils.queryByTestId('products-show-more')).toBeNull()
|
|
})
|
|
|
|
it('HOME-30: changed product data resets the visible count to 21', async () => {
|
|
setJsonResponse(productsCacheUrl(), productsResponse(makeManyProducts(50), []))
|
|
const utils = await renderHome()
|
|
|
|
fireEvent.press(utils.getByTestId('products-show-more'))
|
|
expect(mainListIds(utils)).toHaveLength(42)
|
|
|
|
// Re-register a changed document so the refetch returns a new object identity
|
|
// (React Query's structural sharing keeps an identical payload by reference).
|
|
setJsonResponse(productsCacheUrl(), productsResponse(makeManyProducts(30), []))
|
|
await act(async () => {
|
|
await utils.queryClient.invalidateQueries()
|
|
})
|
|
await flush(2)
|
|
|
|
expect(mainListIds(utils)).toHaveLength(21)
|
|
})
|
|
|
|
it('HOME-31: the main list puts out-of-stock products last, stable within groups', async () => {
|
|
const utils = await renderHome()
|
|
|
|
expect(mainListIds(utils)).toEqual([2, 5, 8, 6, 7, 9, 10, 150])
|
|
})
|
|
|
|
it('HOME-32: tapping a main-list card pushes the product detail route', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(within(getByTestId('product-item-2')).getByTestId('product-card'))
|
|
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/product-detail/2')
|
|
})
|
|
|
|
it('HOME-33: tapping a tag-grid card pushes the same product detail route', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(within(getByTestId('tag-product-2')).getByTestId('product-card'))
|
|
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/product-detail/2')
|
|
})
|
|
|
|
it('HOME-34: the card add icon queues the dialog product without adding directly', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(within(getByTestId('product-item-2')).getByTestId('add-to-cart-icon'))
|
|
|
|
expect(useCartStore.getState().addedToCartProduct?.productId).toBe(2)
|
|
expect(storedCart()).toEqual([])
|
|
})
|
|
|
|
it('HOME-35: a product already in the cart shows the MiniQuantifier instead of the add icon', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const card = within(getByTestId('product-item-2'))
|
|
expect(card.queryByTestId('add-to-cart-icon')).toBeNull()
|
|
expect(card.getByTestId('mini-quantifier-value')).toHaveTextContent('2')
|
|
})
|
|
|
|
it('HOME-36: the card stepper opens the add-to-cart dialog rather than mutating', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const { getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(within(getByTestId('product-item-2')).getByTestId('mini-quantifier-increment'))
|
|
|
|
expect(useCartStore.getState().addedToCartProduct?.productId).toBe(2)
|
|
expect(storedCart()[0].quantity).toBe(2)
|
|
})
|
|
|
|
it('HOME-37: an out-of-stock card shows the overlay (current: add icon still rendered)', async () => {
|
|
// Current gap: in miniView the add icon is rendered regardless of
|
|
// displayIsOutOfStock, so it is not hidden/disabled for out-of-stock cards.
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const card = within(getByTestId('product-item-6'))
|
|
expect(card.getByTestId('out-of-stock-badge')).toBeTruthy()
|
|
expect(card.getByTestId('add-to-cart-icon')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-38: an image load error shows the fallback copy', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const card = within(getByTestId('product-item-2'))
|
|
fireEvent(card.UNSAFE_getByType(Image), 'error')
|
|
|
|
expect(card.getByText('Image failed to load')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-39: a market price equal to the price is not struck through', async () => {
|
|
setJsonResponse(availabilityCacheUrl(), {
|
|
availability: AVAILABILITY.map((entry) =>
|
|
entry.id === 2 ? { ...entry, marketPrice: 215 } : entry
|
|
),
|
|
count: AVAILABILITY.length,
|
|
})
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const card = within(getByTestId('product-item-2'))
|
|
expect(card.getAllByText('₹215')).toHaveLength(1)
|
|
})
|
|
|
|
it('HOME-40: a combo product hides the quantity line', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
expect(within(getByTestId('product-item-150')).queryByText('1 combo')).toBeNull()
|
|
// Control: a regular product does show its unit notation.
|
|
expect(within(getByTestId('product-item-2')).getByText('500g')).toBeTruthy()
|
|
})
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 6.4 Slots, stores, search and refresh */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
it('HOME-41: only future slots render, sorted by delivery then freeze', async () => {
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(idsFrom(getAllByTestId(/^slot-card-/), 'slot-card-')).toEqual([1849, 1850, 1852])
|
|
})
|
|
|
|
it('HOME-42: a slot whose delivery has passed is hidden', async () => {
|
|
const now = Date.now()
|
|
setSlots([
|
|
{
|
|
id: 9001,
|
|
deliveryTime: new Date(now - 60 * 60 * 1000).toISOString(),
|
|
freezeTime: new Date(now + 60 * 60 * 1000).toISOString(),
|
|
products: [{ id: 2 }],
|
|
},
|
|
])
|
|
const { queryByTestId, queryByText } = await renderHome()
|
|
|
|
expect(queryByTestId('slot-card-9001')).toBeNull()
|
|
expect(queryByText('Upcoming Delivery Slots')).toBeNull()
|
|
})
|
|
|
|
it('HOME-43: a slot whose freeze has passed is hidden', async () => {
|
|
const now = Date.now()
|
|
setSlots([
|
|
{
|
|
id: 9002,
|
|
deliveryTime: new Date(now + 2 * 60 * 60 * 1000).toISOString(),
|
|
freezeTime: new Date(now - 60 * 60 * 1000).toISOString(),
|
|
products: [{ id: 2 }],
|
|
},
|
|
])
|
|
const { queryByTestId, queryByText } = await renderHome()
|
|
|
|
expect(queryByTestId('slot-card-9002')).toBeNull()
|
|
expect(queryByText('Upcoming Delivery Slots')).toBeNull()
|
|
})
|
|
|
|
it('HOME-44: more than five future slots render only the first five', async () => {
|
|
const now = Date.now()
|
|
const slots = Array.from({ length: 7 }, (_, index) => ({
|
|
id: 9100 + index,
|
|
deliveryTime: new Date(now + (index + 1) * 60 * 60 * 1000).toISOString(),
|
|
freezeTime: new Date(now + (index + 1) * 60 * 60 * 1000 - 30 * 60 * 1000).toISOString(),
|
|
products: [{ id: 2 }],
|
|
}))
|
|
setSlots(slots)
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(idsFrom(getAllByTestId(/^slot-card-/), 'slot-card-')).toEqual([
|
|
9100, 9101, 9102, 9103, 9104,
|
|
])
|
|
})
|
|
|
|
it('HOME-45: a freeze less than four hours away shows CLOSING SOON', async () => {
|
|
const { getAllByText } = await renderHome()
|
|
|
|
// Slots 1849 (+1h) and 1850 (+3h) are both inside the four-hour window.
|
|
expect(getAllByText('CLOSING SOON').length).toBeGreaterThan(0)
|
|
})
|
|
|
|
it('HOME-46: a freeze at or beyond four hours away does not show CLOSING SOON', async () => {
|
|
const now = Date.now()
|
|
setSlots([
|
|
{
|
|
id: 9003,
|
|
deliveryTime: new Date(now + 5 * 60 * 60 * 1000).toISOString(),
|
|
// A few minutes past four hours so the component's own `dayjs()` (a tick
|
|
// later) still diffs to 4 hours.
|
|
freezeTime: new Date(now + 4 * 60 * 60 * 1000 + 5 * 60 * 1000).toISOString(),
|
|
products: [{ id: 2 }],
|
|
},
|
|
])
|
|
const { getByTestId, queryByText } = await renderHome()
|
|
|
|
expect(getByTestId('slot-card-9003')).toBeTruthy()
|
|
expect(queryByText('CLOSING SOON')).toBeNull()
|
|
})
|
|
|
|
it('HOME-47: a slot card shows the delivery range and order-by time line', async () => {
|
|
const { getAllByText, getAllByTestId } = await renderHome()
|
|
|
|
expect(getAllByTestId(/^slot-card-/).length).toBe(3)
|
|
expect(getAllByText('Delivery At').length).toBe(3)
|
|
expect(getAllByText('Order By').length).toBe(3)
|
|
})
|
|
|
|
it('HOME-48: a slot card shows the product count', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
expect(within(getByTestId('slot-card-1849')).getByText('View all 2 items')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-49: tapping a slot card pushes the slot view route', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByTestId('slot-card-1849'))
|
|
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/slot-view?slotId=1849')
|
|
})
|
|
|
|
it('HOME-50: stores present render the Our Stores strip with every store', async () => {
|
|
const { getByText, getByTestId } = await renderHome()
|
|
|
|
expect(getByText('Our Stores')).toBeTruthy()
|
|
expect(getByTestId('store-item-1')).toBeTruthy()
|
|
expect(getByTestId('store-item-2')).toBeTruthy()
|
|
})
|
|
|
|
it("HOME-51: a leading 'The ' is stripped from a store name", async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
expect(within(getByTestId('store-item-1')).getByText('Freshyo Meat House')).toBeTruthy()
|
|
})
|
|
|
|
it("HOME-52: a lowercase leading 'the ' is stripped case-insensitively", async () => {
|
|
setJsonResponse(storesCacheUrl(), {
|
|
stores: [{ id: 3, name: 'the green store', signedImageUrl: null, productCount: 1, sampleProducts: [] }],
|
|
})
|
|
const { getByTestId } = await renderHome()
|
|
|
|
expect(within(getByTestId('store-item-3')).getByText('green store')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-53: a store without a signed image shows the storefront icon', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const icons = within(getByTestId('store-item-2')).UNSAFE_getAllByType(MaterialIcons)
|
|
expect(icons.some((icon) => icon.props.name === 'storefront')).toBe(true)
|
|
})
|
|
|
|
it('HOME-54: tapping a store sets the navigation flags and pushes /stores', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByTestId('store-item-1'))
|
|
|
|
expect(useNavigationStore.getState().isNavigatedFromHome).toBe(true)
|
|
expect(useNavigationStore.getState().selectedStoreId).toBe(1)
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/stores')
|
|
})
|
|
|
|
it('HOME-55: an empty stores response hides the store section', async () => {
|
|
setJsonResponse(storesCacheUrl(), { stores: [] })
|
|
const { queryByText } = await renderHome()
|
|
|
|
expect(queryByText('Our Stores')).toBeNull()
|
|
})
|
|
|
|
it('HOME-56: tapping the search bar pushes the search results route', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByTestId('home-search'))
|
|
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/search-results')
|
|
})
|
|
|
|
it('HOME-57: the search bar is read-only', async () => {
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const input = getByTestId('home-search-input')
|
|
fireEvent.changeText(input, 'chicken')
|
|
|
|
expect(input.props.value).toBe('')
|
|
})
|
|
|
|
it('HOME-58: pull to refresh refetches products, slots and stores', async () => {
|
|
const refetchProducts = jest.fn(async () => undefined)
|
|
const refetchSlots = jest.fn(async () => undefined)
|
|
useCentralProductStore.setState({ refetchProducts })
|
|
useCentralSlotStore.setState({ refetchSlots })
|
|
await renderHome()
|
|
|
|
const storesBefore = jsonCallsFor(storesCacheUrl()).length
|
|
await emitManualRefresh()
|
|
|
|
expect(refetchProducts).toHaveBeenCalled()
|
|
expect(refetchSlots).toHaveBeenCalled()
|
|
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore)
|
|
})
|
|
|
|
it('HOME-59: a rejected refresh request still runs the rest and clears the spinner', async () => {
|
|
const refetchProducts = jest.fn(async () => undefined)
|
|
const refetchSlots = jest.fn(async () => undefined)
|
|
useCentralProductStore.setState({ refetchProducts })
|
|
useCentralSlotStore.setState({ refetchSlots })
|
|
setJsonError(storesCacheUrl(), new Error('stores down'))
|
|
const utils = await renderHome()
|
|
|
|
await emitManualRefresh()
|
|
|
|
expect(refetchProducts).toHaveBeenCalled()
|
|
expect(refetchSlots).toHaveBeenCalled()
|
|
const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl
|
|
expect(refreshControl.props.refreshing).toBe(false)
|
|
})
|
|
|
|
it('HOME-60: a re-focus through useMarkDataFetchers runs the same refresh', async () => {
|
|
const refetchProducts = jest.fn(async () => undefined)
|
|
const refetchSlots = jest.fn(async () => undefined)
|
|
useCentralProductStore.setState({ refetchProducts })
|
|
useCentralSlotStore.setState({ refetchSlots })
|
|
await renderHome()
|
|
|
|
const storesBefore = jsonCallsFor(storesCacheUrl()).length
|
|
await emitFocus()
|
|
await flush(2)
|
|
|
|
expect(refetchProducts).toHaveBeenCalled()
|
|
expect(refetchSlots).toHaveBeenCalled()
|
|
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(storesBefore)
|
|
})
|
|
|
|
it('HOME-61: refreshing while already refreshing does not corrupt the spinner', async () => {
|
|
const refetchProducts = jest.fn(async () => undefined)
|
|
const refetchSlots = jest.fn(async () => undefined)
|
|
useCentralProductStore.setState({ refetchProducts })
|
|
useCentralSlotStore.setState({ refetchSlots })
|
|
const utils = await renderHome()
|
|
|
|
await emitManualRefresh()
|
|
await emitManualRefresh()
|
|
|
|
const refreshControl = utils.UNSAFE_getByType(SectionList).props.refreshControl
|
|
expect(refreshControl.props.refreshing).toBe(false)
|
|
expect(refetchProducts).toHaveBeenCalled()
|
|
})
|
|
|
|
it('HOME-62: the location bar shows the region and active address and opens the switcher', async () => {
|
|
__setAuthState({
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
user: AUTH_USER,
|
|
userDetails: AUTH_USER,
|
|
token: TEST_JWT,
|
|
})
|
|
seedSelectedAddress(A1.id)
|
|
// LocationBar reads `addressLine1`/`addressLine2`; the shared address
|
|
// fixtures use `line1`/`line2`, so shape the response the way it expects.
|
|
setProcedure('user.address.getUserAddresses', {
|
|
data: {
|
|
data: [
|
|
{
|
|
...A1,
|
|
addressLine1: '12 Main Road',
|
|
addressLine2: 'Near Temple',
|
|
},
|
|
],
|
|
},
|
|
})
|
|
const { getByTestId, getByText } = await renderHome()
|
|
|
|
expect(getByTestId('location-bar')).toBeTruthy()
|
|
expect(getByText('Mahabubnagar')).toBeTruthy()
|
|
expect(getByText('12 Main Road, Near Temple, Mahabubnagar')).toBeTruthy()
|
|
|
|
fireEvent.press(getByTestId('location-bar'))
|
|
|
|
expect(getByText('Delivery Address')).toBeTruthy()
|
|
})
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 6.5 Add-to-cart dialog and cart bar */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
it('HOME-63: with no queued product the dialog renders nothing', async () => {
|
|
const { queryByTestId } = await renderHome()
|
|
|
|
expect(queryByTestId('add-to-cart-confirm')).toBeNull()
|
|
})
|
|
|
|
it('HOME-64: opening for Chicken shows the heading, product line, quantity and slots', async () => {
|
|
const { getByText, getByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
expect(getByText('Select Delivery Slot')).toBeTruthy()
|
|
expect(getByText('Chicken Breast (500g)')).toBeTruthy()
|
|
expect(getByTestId('quantifier-value')).toHaveTextContent('1')
|
|
expect(getByTestId(slotTestId(SLOTS[0]))).toBeTruthy()
|
|
expect(getByTestId(slotTestId(SLOTS[1]))).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-65: a slot whose freeze has passed is not offered', async () => {
|
|
const { getByTestId, queryByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
expect(getByTestId(slotTestId(SLOTS[0]))).toBeTruthy()
|
|
// SLOTS[2] (id 1851) has a past freeze.
|
|
expect(queryByTestId(slotTestId(SLOTS[2]))).toBeNull()
|
|
})
|
|
|
|
it('HOME-66: a slot with a past delivery but future freeze is still offered', async () => {
|
|
const now = Date.now()
|
|
const slot = {
|
|
id: 9201,
|
|
deliveryTime: new Date(now - 60 * 60 * 1000).toISOString(),
|
|
freezeTime: new Date(now + 60 * 60 * 1000).toISOString(),
|
|
products: [{ id: 2 }],
|
|
}
|
|
setSlots([slot])
|
|
const { getByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
expect(getByTestId(slotTestId(slot))).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-67: no region slots and no flash shows the unavailable copy and a disabled confirm', async () => {
|
|
const combo = productByIdFrom(150)
|
|
const { getByText, getByTestId } = await openDialog(combo)
|
|
|
|
expect(getByText('Not available in your region right now.')).toBeTruthy()
|
|
expect(getByTestId('add-to-cart-confirm').props.accessibilityState.disabled).toBe(true)
|
|
})
|
|
|
|
it('HOME-68: a flash-eligible product with flash enabled shows the 1 hr Delivery row', async () => {
|
|
const { getByText } = await openDialog(productByIdFrom(8))
|
|
|
|
expect(getByText('1 hr Delivery')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-69: with flash disabled the 1 hr Delivery row is hidden', async () => {
|
|
setProcedure('common.essentialConsts', { data: CONSTS_FLASH_OFF })
|
|
const { queryByText } = await openDialog(productByIdFrom(8))
|
|
|
|
expect(queryByText('1 hr Delivery')).toBeNull()
|
|
})
|
|
|
|
it('HOME-70: with no slot selected the confirm button is disabled', async () => {
|
|
const { getByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
expect(getByTestId('add-to-cart-confirm').props.accessibilityState.disabled).toBe(true)
|
|
})
|
|
|
|
it('HOME-71: selecting a slot shows the check icon and enables confirm', async () => {
|
|
const { getByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
const row = getByTestId(slotTestId(SLOTS[0]))
|
|
fireEvent.press(row)
|
|
|
|
expect(getByTestId('add-to-cart-confirm').props.accessibilityState.disabled).toBe(false)
|
|
const icons = within(row).UNSAFE_getAllByType(MaterialIcons)
|
|
expect(icons.some((icon) => icon.props.name === 'check-circle')).toBe(true)
|
|
})
|
|
|
|
it('HOME-72: confirming a regular slot adds it to the cart and clears the dialog', async () => {
|
|
const { getByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
fireEvent.press(getByTestId(slotTestId(SLOTS[0])))
|
|
await act(async () => {
|
|
fireEvent.press(getByTestId('add-to-cart-confirm'))
|
|
})
|
|
|
|
await waitFor(() => expect(useCartStore.getState().addedToCartProduct).toBeNull())
|
|
expect(storedCart()).toEqual([
|
|
expect.objectContaining({ skuId: 2, quantity: 1, slotId: 1849 }),
|
|
])
|
|
})
|
|
|
|
it('HOME-73: selecting flash clears the slot and routes to flash delivery', async () => {
|
|
const { getByTestId } = await openDialog(productByIdFrom(8))
|
|
|
|
fireEvent.press(getByTestId('flash-delivery-option'))
|
|
await act(async () => {
|
|
fireEvent.press(getByTestId('add-to-cart-confirm'))
|
|
})
|
|
|
|
expect(useFlashCartStore.getState().addedFlashProduct?.productId).toBe(8)
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/flash-delivery/(products)')
|
|
expect(useCartStore.getState().addedToCartProduct).toBeNull()
|
|
})
|
|
|
|
it('HOME-74: a product already in the cart preselects the quantity and says Update Item', async () => {
|
|
const { getByText, getByTestId } = await openDialog(P_CHICKEN, CART_REG)
|
|
|
|
expect(getByTestId('quantifier-value')).toHaveTextContent('2')
|
|
expect(getByText('Update Item')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-75: a stored cart slot that is not a region slot leaves no slot selected', async () => {
|
|
// The line has to reach the cart *after* the bar mounted: on a cold start the
|
|
// bar's mount effect (empty deps) rewrites an unknown slot to the nearest
|
|
// region slot before the dialog ever opens. Storing it post-mount keeps the
|
|
// stale slot in the cart, which is what the dialog must reject.
|
|
const utils = await renderHome()
|
|
__set('cart_items', cartLine(1, 2, 2, 999))
|
|
await act(async () => {
|
|
await utils.queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] })
|
|
})
|
|
await flush(2)
|
|
expect(utils.getByText(/₹430/)).toBeTruthy()
|
|
|
|
await act(async () => {
|
|
useCartStore.getState().setAddedToCartProduct({ productId: P_CHICKEN.id, product: P_CHICKEN })
|
|
})
|
|
await flush(2)
|
|
|
|
expect(utils.getByTestId('add-to-cart-confirm').props.accessibilityState.disabled).toBe(true)
|
|
})
|
|
|
|
it('HOME-76: updating the quantity writes the cart and closes the dialog', async () => {
|
|
const { getByTestId } = await openDialog(P_CHICKEN, CART_REG)
|
|
|
|
fireEvent.press(getByTestId('quantifier-increment'))
|
|
await act(async () => {
|
|
fireEvent.press(getByTestId('add-to-cart-confirm'))
|
|
})
|
|
|
|
await waitFor(() => expect(useCartStore.getState().addedToCartProduct).toBeNull())
|
|
expect(storedCart()[0].quantity).toBe(3)
|
|
})
|
|
|
|
it('HOME-77: removing an existing line empties the cart and closes the dialog', async () => {
|
|
const { getByTestId } = await openDialog(P_CHICKEN, CART_REG)
|
|
|
|
await act(async () => {
|
|
fireEvent.press(getByTestId('remove-from-cart'))
|
|
})
|
|
|
|
await waitFor(() => expect(useCartStore.getState().addedToCartProduct).toBeNull())
|
|
expect(storedCart()).toEqual([])
|
|
})
|
|
|
|
it('HOME-78: the dialog quantity guard never goes below zero (current: min is 0)', async () => {
|
|
// Current gap: the dialog Quantifier keeps its default min of 0, so the
|
|
// quantity can reach 0 instead of clamping at 1.
|
|
const { getByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
fireEvent.press(getByTestId('quantifier-decrement'))
|
|
fireEvent.press(getByTestId('quantifier-decrement'))
|
|
|
|
expect(getByTestId('quantifier-value')).toHaveTextContent('0')
|
|
})
|
|
|
|
it('HOME-79: Cancel clears the queued product without mutating the cart', async () => {
|
|
const { getByText } = await openDialog(P_CHICKEN)
|
|
|
|
fireEvent.press(getByText('Cancel'))
|
|
|
|
expect(useCartStore.getState().addedToCartProduct).toBeNull()
|
|
expect(storedCart()).toEqual([])
|
|
})
|
|
|
|
it('HOME-80: a pending add shows Adding... and disables the confirm button', async () => {
|
|
const { getByText, getByTestId } = await openDialog(P_CHICKEN)
|
|
|
|
fireEvent.press(getByTestId(slotTestId(SLOTS[0])))
|
|
|
|
// Hold the storage read open so the mutation stays pending.
|
|
let release!: () => void
|
|
const gate = new Promise<void>((resolve) => {
|
|
release = resolve
|
|
})
|
|
const spy = jest
|
|
.spyOn(StorageServiceCasual, 'getItem')
|
|
.mockImplementation(() => gate as any)
|
|
|
|
await act(async () => {
|
|
fireEvent.press(getByTestId('add-to-cart-confirm'))
|
|
})
|
|
|
|
await waitFor(() => expect(getByText('Adding...')).toBeTruthy())
|
|
expect(getByTestId('add-to-cart-confirm').props.accessibilityState.disabled).toBe(true)
|
|
|
|
// Let the held mutation finish so no dangling work keeps jest alive.
|
|
spy.mockRestore()
|
|
release()
|
|
await flush(2)
|
|
})
|
|
|
|
it('HOME-81: the empty regular bar shows No Items In Cart and still routes to the cart', async () => {
|
|
const { getByText, getByTestId } = await renderHome()
|
|
|
|
expect(getByText('No Items In Cart')).toBeTruthy()
|
|
fireEvent.press(getByTestId('go-to-cart'))
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/cart')
|
|
})
|
|
|
|
it('HOME-82: the empty flash bar shows No Flash Items', async () => {
|
|
const { getByText } = await renderBar({ isFlashDelivery: true })
|
|
|
|
expect(getByText('No Flash Items')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-83: two ₹215 lines show ₹430 • 2 Items and a threshold line', async () => {
|
|
__set(
|
|
'cart_items',
|
|
JSON.stringify([
|
|
{ id: 1, skuId: 2, quantity: 1, slotId: 1849, addedAt: CART_LINE_ADDED_AT },
|
|
{ id: 2, skuId: 2, quantity: 1, slotId: 1849, addedAt: CART_LINE_ADDED_AT },
|
|
])
|
|
)
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText(/₹430 • 2 Items/)).toBeTruthy()
|
|
expect(getByText(/FREE Delivery|Free Delivery Unlocked/)).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-84: a single line uses the singular Item', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText(/1 Item/)).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-85: a total at or above the threshold unlocks free delivery', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText('Free Delivery Unlocked')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-86: the flash cart uses flash prices and the flash threshold', async () => {
|
|
__set('flash_cart_items', CART_FLASH)
|
|
const { getByText } = await renderBar({ isFlashDelivery: true })
|
|
|
|
expect(getByText(/₹75 • 1 Item/)).toBeTruthy()
|
|
expect(getByText(/124 more/)).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-87: tapping the collapsed bar with items opens the Your Cart sheet', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const { getByText } = await renderHome()
|
|
|
|
fireEvent.press(getByText(/1 Item/))
|
|
|
|
expect(getByText('Your Cart')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-88: tapping the collapsed bar with zero items does not expand', async () => {
|
|
const { getByText, queryByText } = await renderHome()
|
|
|
|
fireEvent.press(getByText('No Items In Cart'))
|
|
|
|
expect(queryByText('Your Cart')).toBeNull()
|
|
})
|
|
|
|
it('HOME-89: the go-to-cart button routes to the correct cart per variant', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const regular = await renderHome()
|
|
fireEvent.press(regular.getByTestId('go-to-cart'))
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/cart')
|
|
|
|
router.push.mockClear()
|
|
__set('flash_cart_items', CART_FLASH)
|
|
const flash = await renderBar({ isFlashDelivery: true })
|
|
fireEvent.press(flash.getByTestId('go-to-cart'))
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/flash-delivery/(cart)/cart')
|
|
})
|
|
|
|
it('HOME-90: the expanded sheet shows the count, progress, needed amount and subtotal', async () => {
|
|
__set('cart_items', cartLine(1, 2, 1, 1849))
|
|
const { getByText, getAllByText } = await renderHome()
|
|
|
|
fireEvent.press(getByText(/1 Item/))
|
|
|
|
expect(getByText('Your Cart')).toBeTruthy()
|
|
expect(getByText('1 Items')).toBeTruthy()
|
|
expect(getByText('Free Delivery Progress')).toBeTruthy()
|
|
expect(getByText('86%')).toBeTruthy()
|
|
expect(getByText('Needed')).toBeTruthy()
|
|
expect(getByText('+₹34')).toBeTruthy()
|
|
expect(getByText('Subtotal')).toBeTruthy()
|
|
expect(getAllByText('₹215').length).toBeGreaterThanOrEqual(1)
|
|
})
|
|
|
|
it('HOME-91: the line price follows the stored quantity until the mutation settles', async () => {
|
|
// Current behaviour: the rendered line total reads `item.quantity` (stored),
|
|
// while the MiniQuantifier's local quantity updates immediately.
|
|
__set('cart_items', CART_REG)
|
|
const { getByText, getAllByText, getAllByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByText(/1 Item/))
|
|
// The bar's MiniQuantifier is the last one in the tree (cards render first).
|
|
const increments = getAllByTestId('mini-quantifier-increment')
|
|
fireEvent.press(increments[increments.length - 1])
|
|
|
|
const values = getAllByTestId('mini-quantifier-value')
|
|
expect(values[values.length - 1]).toHaveTextContent('3')
|
|
expect(getAllByText('₹430').length).toBeGreaterThanOrEqual(1)
|
|
})
|
|
|
|
it('HOME-92: the mini quantifier updates and removes the cart line', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const { getByText, getAllByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByText(/1 Item/))
|
|
|
|
const last = (testID: string) => {
|
|
const nodes = getAllByTestId(testID)
|
|
return nodes[nodes.length - 1]
|
|
}
|
|
|
|
fireEvent.press(last('mini-quantifier-increment'))
|
|
await waitFor(() => expect(storedCart()[0].quantity).toBe(3))
|
|
|
|
fireEvent.press(last('mini-quantifier-decrement'))
|
|
await waitFor(() => expect(storedCart()[0].quantity).toBe(2))
|
|
fireEvent.press(last('mini-quantifier-decrement'))
|
|
await waitFor(() => expect(storedCart()[0].quantity).toBe(1))
|
|
fireEvent.press(last('mini-quantifier-decrement'))
|
|
await waitFor(() => expect(storedCart()).toEqual([]))
|
|
})
|
|
|
|
it('HOME-93: changing the slot dropdown re-adds with the new slot and alerts', async () => {
|
|
__set('cart_items', CART_REG)
|
|
const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
|
const { getByText, getByTestId } = await renderHome()
|
|
|
|
fireEvent.press(getByText(/1 Item/))
|
|
fireEvent.press(getByTestId('cart-slot-trigger'))
|
|
await flush(1)
|
|
fireEvent.press(getByTestId('cart-slot-dropdown-option-1850'))
|
|
|
|
await waitFor(() => expect(storedCart()[0].slotId).toBe(1850))
|
|
await waitFor(() => expect(alert).toHaveBeenCalledWith('Delivery Updated', expect.any(String)))
|
|
})
|
|
|
|
it('HOME-94: a stale slot is not corrected on mount (reconciliation needs slots at first render)', async () => {
|
|
// Current gap: the reconciliation effect keys off `slotsData`, which comes
|
|
// from the consts-gated slots query and is never available on the effect's
|
|
// single (empty-deps) run, so the stale slot survives. The remove + re-add
|
|
// branch is effectively unreachable until the effect depends on slotsData.
|
|
__set('cart_items', cartLine(1, 2, 2, 999))
|
|
const queryClient = createCartQueryClient()
|
|
queryClient.setQueryData(['local-cart-regular'], [
|
|
{ id: 1, skuId: 2, quantity: 2, slotId: 999, addedAt: CART_LINE_ADDED_AT },
|
|
])
|
|
queryClient.setQueryData(['slots', slotsCacheUrl()], SLOTS_RESPONSE)
|
|
|
|
renderWithProviders(<FloatingCartBar />, { auth: false, queryClient })
|
|
await flush(3)
|
|
|
|
expect(storedCart()[0].slotId).toBe(999)
|
|
})
|
|
|
|
it('HOME-95 (current): a stale slot at mount is reconciled to the nearest slot', async () => {
|
|
// With the real query client the reconciliation effect gets a mount run
|
|
// after the cart query settles, so the stale slot is rewritten to the
|
|
// nearest region slot (1849). The remove+add pair also doubles the quantity
|
|
// (app-side race) — pinned as the current contract.
|
|
__set('cart_items', cartLine(1, 2, 2, 999))
|
|
await renderHome()
|
|
|
|
await waitFor(() => expect(storedCart()[0].slotId).toBe(1849))
|
|
expect(storedCart()[0].quantity).toBe(4)
|
|
})
|
|
|
|
it('HOME-96: a long product name is truncated in the bar', async () => {
|
|
const longName = 'Super Extra Long Chicken Breast Family Pack'
|
|
const current = useCentralProductStore.getState().productsById
|
|
useCentralProductStore.setState({
|
|
productsById: { ...current, 2: { ...current[2], name: longName } },
|
|
})
|
|
__set('cart_items', CART_REG)
|
|
const { getByText } = await renderHome()
|
|
|
|
fireEvent.press(getByText(/1 Item/))
|
|
|
|
const truncated = longName.substring(0, 25) + '...'
|
|
expect(getByText(new RegExp(truncated.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-97: a combo product hides the unit suffix in the bar', async () => {
|
|
const current = useCentralProductStore.getState().productsById
|
|
useCentralProductStore.setState({
|
|
productsById: {
|
|
...current,
|
|
2: { ...current[2], name: 'Party Pack', unitNotation: '1 combo', productType: 'combo' },
|
|
},
|
|
})
|
|
__set('cart_items', cartLine(1, 2, 1, 1849))
|
|
const { getByText, queryByText } = await renderHome()
|
|
|
|
fireEvent.press(getByText(/1 Item/))
|
|
|
|
expect(getByText(/Party Pack/)).toBeTruthy()
|
|
expect(queryByText(/\( 1 combo\)/)).toBeNull()
|
|
})
|
|
|
|
it('HOME-98: with no consts the NaN threshold shows Free Delivery Unlocked (current)', async () => {
|
|
// Current gap: a missing threshold produces NaN, which is not > 0, so the
|
|
// bar falls through to the "unlocked" branch.
|
|
setProcedure('common.essentialConsts', { mode: 'error' })
|
|
__set('cart_items', CART_REG)
|
|
const { getByText } = await renderBar()
|
|
|
|
expect(getByText('Free Delivery Unlocked')).toBeTruthy()
|
|
})
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 6.6 Next order glimpse */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
it('HOME-99: signed out the glimpse renders nothing and orders are not fetched', async () => {
|
|
const { queryByTestId } = await renderHome()
|
|
|
|
expect(queryByTestId('next-order-glimpse')).toBeNull()
|
|
expect(procedureQueryCalls('user.order.getOrders')).toHaveLength(0)
|
|
})
|
|
|
|
it('HOME-100: signed in while orders load shows the spinner card', async () => {
|
|
signedIn()
|
|
setProcedure('user.order.getOrders', { mode: 'pending' })
|
|
const { getByTestId } = await renderHome()
|
|
|
|
expect(getByTestId('next-order-loading')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-101: an upcoming order shows the id, item count, total and status', async () => {
|
|
signedIn()
|
|
setOrders([{ ...O1, deliveryStatus: 'processing' }])
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText('#ORD-1001')).toBeTruthy()
|
|
expect(getByText('2 items • ₹445')).toBeTruthy()
|
|
expect(getByText('processing')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-102: confirmed and packaged statuses hide the status chip', async () => {
|
|
signedIn()
|
|
setOrders([
|
|
{ ...O1, id: 1001, deliveryStatus: 'pending' },
|
|
{ ...O1, id: 1002, orderId: 'ORD-1002', deliveryStatus: 'packaged' },
|
|
])
|
|
const { queryByText } = await renderHome()
|
|
|
|
expect(queryByText('Confirmed')).toBeNull()
|
|
expect(queryByText('packaged')).toBeNull()
|
|
})
|
|
|
|
it('HOME-103: a flash order shows the FLASH tag and 30-Min', async () => {
|
|
signedIn()
|
|
setOrders([{ ...O1, isFlashDelivery: true }])
|
|
const { getByText } = await renderHome()
|
|
|
|
expect(getByText('FLASH')).toBeTruthy()
|
|
expect(getByText('30-Min')).toBeTruthy()
|
|
})
|
|
|
|
it('HOME-104: a cancelled order is excluded', async () => {
|
|
signedIn()
|
|
setOrders([{ ...O1, orderStatus: 'cancelled', deliveryStatus: 'cancelled' }])
|
|
const { queryByTestId } = await renderHome()
|
|
|
|
expect(queryByTestId('next-order-glimpse')).toBeNull()
|
|
})
|
|
|
|
it('HOME-105: an order with a success delivery status is excluded', async () => {
|
|
signedIn()
|
|
setOrders([{ ...O1, deliveryStatus: 'success' }])
|
|
const { queryByTestId } = await renderHome()
|
|
|
|
expect(queryByTestId('next-order-glimpse')).toBeNull()
|
|
})
|
|
|
|
it('HOME-106: flash orders sort before scheduled orders', async () => {
|
|
signedIn()
|
|
setOrders([
|
|
{ ...O1, id: 1001, orderId: 'SCHEDULED' },
|
|
{ ...O1, id: 2001, orderId: 'FLASH', isFlashDelivery: true },
|
|
])
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(idsFrom(getAllByTestId(/^next-order-card-/), 'next-order-card-')).toEqual([
|
|
2001, 1001,
|
|
])
|
|
})
|
|
|
|
it('HOME-107: multiple flash orders sort newest createdAt first', async () => {
|
|
signedIn()
|
|
setOrders([
|
|
{ ...O1, id: 2001, orderId: 'FLASH-OLD', isFlashDelivery: true, createdAt: '2024-01-01T00:00:00.000Z' },
|
|
{ ...O1, id: 2002, orderId: 'FLASH-NEW', isFlashDelivery: true, createdAt: '2024-06-01T00:00:00.000Z' },
|
|
])
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(idsFrom(getAllByTestId(/^next-order-card-/), 'next-order-card-')).toEqual([
|
|
2002, 2001,
|
|
])
|
|
})
|
|
|
|
it('HOME-108: multiple scheduled orders sort earliest delivery first', async () => {
|
|
signedIn()
|
|
setOrders([
|
|
{ ...O1, id: 1001, orderId: 'LATE', deliveryDate: new Date(Date.now() + 5 * 60 * 60 * 1000).toISOString() },
|
|
{ ...O1, id: 1002, orderId: 'SOON', deliveryDate: new Date(Date.now() + 60 * 60 * 1000).toISOString() },
|
|
])
|
|
const { getAllByTestId } = await renderHome()
|
|
|
|
expect(idsFrom(getAllByTestId(/^next-order-card-/), 'next-order-card-')).toEqual([
|
|
1002, 1001,
|
|
])
|
|
})
|
|
|
|
it('HOME-109: no upcoming orders renders nothing', async () => {
|
|
signedIn()
|
|
setOrders([])
|
|
const { queryByTestId } = await renderHome()
|
|
|
|
expect(queryByTestId('next-order-glimpse')).toBeNull()
|
|
})
|
|
|
|
it('HOME-110: the support mobile renders and tapping it opens a tel: link', async () => {
|
|
signedIn()
|
|
setOrders([{ ...O1, deliveryStatus: 'processing' }])
|
|
const openURL = jest.spyOn(Linking, 'openURL').mockResolvedValue(true)
|
|
const { getByText, getByTestId } = await renderHome()
|
|
|
|
expect(getByText('Need help? Call 8688182552')).toBeTruthy()
|
|
fireEvent.press(getByTestId('next-order-support-call'))
|
|
expect(openURL).toHaveBeenCalledWith('tel:8688182552')
|
|
})
|
|
|
|
it('HOME-111: tapping an order card sets the target and replaces to the me tab', async () => {
|
|
signedIn()
|
|
setOrders([{ ...O1, deliveryStatus: 'processing' }])
|
|
const api: { current: string | null } = { current: null }
|
|
const { getByTestId } = renderWithProviders(
|
|
<>
|
|
<Home />
|
|
<NavTargetProbe api={api} />
|
|
</>,
|
|
{ auth: false, queryClient: createCartQueryClient() }
|
|
)
|
|
await flush(3)
|
|
|
|
fireEvent.press(getByTestId('next-order-card-1001'))
|
|
|
|
expect(api.current).toBe('/(drawer)/(tabs)/me/my-orders/1001')
|
|
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/me')
|
|
})
|
|
|
|
it('HOME-112: more than one order shows pagination dots and scroll updates the active dot', async () => {
|
|
signedIn()
|
|
setOrders([
|
|
{ ...O1, id: 1001, orderId: 'ONE' },
|
|
{ ...O1, id: 1002, orderId: 'TWO' },
|
|
])
|
|
const { getByTestId } = await renderHome()
|
|
|
|
const active = (StyleSheet.flatten(tw`bg-amber-500`) as any).backgroundColor
|
|
const dotColor = (id: string) =>
|
|
(StyleSheet.flatten(getByTestId(id).props.style) as any).backgroundColor
|
|
|
|
expect(dotColor('next-order-dot-0')).toBe(active)
|
|
expect(dotColor('next-order-dot-1')).not.toBe(active)
|
|
|
|
fireEvent.scroll(getByTestId('next-order-scroll'), {
|
|
nativeEvent: { contentOffset: { x: 100000 } },
|
|
})
|
|
|
|
expect(dotColor('next-order-dot-1')).toBe(active)
|
|
})
|
|
})
|