freshyo/apps/user-ui/tests/home-page/home.test.tsx
2026-09-26 00:46:08 +05:30

611 lines
20 KiB
TypeScript

/**
* Integration tests for app/(drawer)/(tabs)/home/index.tsx
*
* API responses are mocked at the network layer:
* - common.essentialConsts -> tests/__fixtures__/essentialConsts.json
* - assets CDN -> tests/mocks/mock-*-response.json
*
* The tree includes CentralStoreInitializer (the real one from app/_layout.tsx)
* so the slot/availability/product stores are populated the same way the app
* populates them. Without it productSlotsMap is empty and the out-of-stock and
* cart paths cannot be exercised.
*
* Runner: `bun run test` (or `bun run test:watch`) from apps/user-ui.
*/
import React from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
fireEvent,
render,
screen,
waitFor,
within,
} from '@testing-library/react-native'
import { RefreshProvider } from 'common-ui'
import dayjs from 'dayjs'
// Mocked router: this file renders router consumers without a router. The real
// router is exercised in tests/home-page/navigation.test.tsx instead.
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import Dashboard from '@/app/(drawer)/(tabs)/home/index'
import CentralStoreInitializer from '@/src/components/CentralStoreInitializer'
import { useNavigationStore } from '@/src/store/navigationStore'
import { trpc, trpcClient } from '@/src/trpc-client'
import productsResponse from '../mocks/mock-products-response.json'
import storesResponse from '../mocks/mock-stores-response.json'
import { routerMock } from '../mocks/router'
import {
EXPIRED_DIALOG_SLOT_ID,
EXPIRED_HOME_SLOT_ID,
PRODUCTS_URL,
mockSlots,
outOfStockIds,
resetStorage,
setupApiMocks,
} from '../mocks/api'
// The tag grid renders at most this many items before its "Show More" button
// expands it (see the products.slice(0, 6) in TagScene).
const TAG_GRID_PREVIEW = 6
// The main list loads products in pages of 21 (see visibleCount).
const PRODUCT_PAGE_SIZE = 21
// useAllProducts drops combo-only SKUs before the page ever sees them.
const products = productsResponse.products.filter((p) => !p.isComboOnly)
const knownProductIds = new Set(products.map((p) => p.id))
const tags = productsResponse.tags
// Availability flag OR no upcoming slot; shared with the other test files via
// tests/mocks/api.ts so the expectation has a single definition.
const expectedOutOfStock = outOfStockIds
/** Products a tag points at that exist in the (combo-filtered) cache. */
const productIdsForTag = (tag: (typeof tags)[number]) =>
tag.productIds.filter((id) => knownProductIds.has(id))
/**
* The order the page renders a tag's grid in: the admin-curated order with
* out-of-stock items pushed to the end (see productsByTagId in the page).
*/
const orderedProductIdsForTag = (tag: (typeof tags)[number]) => {
const ids = productIdsForTag(tag)
return [
...ids.filter((id) => !expectedOutOfStock.has(id)),
...ids.filter((id) => expectedOutOfStock.has(id)),
]
}
const idFromTestID = (testID: string | undefined, prefix: string) =>
Number(String(testID).slice(prefix.length))
function renderHome() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
})
return render(
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
<RefreshProvider queryClient={queryClient}>
<CentralStoreInitializer>
<Dashboard />
</CentralStoreInitializer>
</RefreshProvider>
</QueryClientProvider>
</trpc.Provider>
)
}
/** Renders and waits for the first tag tab, i.e. the tag strip is live. */
async function renderLoadedHome() {
const result = renderHome()
await waitFor(() => {
expect(screen.getByTestId(`tag-tab-${tags[0].id}`)).toBeTruthy()
})
return result
}
/** Selects a tag and expands its grid past the preview. */
function expandTag(tagId: number) {
fireEvent.press(screen.getByTestId(`tag-tab-${tagId}`))
const expand = screen.queryByTestId(`tag-show-more-${tagId}`)
if (expand) fireEvent.press(expand)
}
/** Adds a product from the tag grid: add icon -> first open slot -> confirm. */
function addToCartFromTagGrid(productId: number) {
fireEvent.press(
within(screen.getByTestId(`tag-product-${productId}`)).getByTestId(
'add-to-cart-icon'
)
)
const slot = mockSlots.slots.find(
(s) =>
s.products.some((p) => p.id === productId) &&
dayjs(s.freezeTime).isAfter(dayjs())
)
if (!slot) throw new Error(`[tests] no open slot for product ${productId}`)
fireEvent.press(
screen.getByTestId(
`slot-${dayjs(slot.deliveryTime).format('YYYY-MM-DD-HH-mm')}`
)
)
fireEvent.press(screen.getByTestId('add-to-cart-confirm'))
}
// Mirrors the backend (scaffoldSlotsWithProducts): a slot is offerable only
// while both its freeze and delivery times are in the future.
const isUpcomingSlot = (slot: { deliveryTime: string; freezeTime: string }) =>
dayjs(slot.deliveryTime).isAfter(dayjs()) && dayjs(slot.freezeTime).isAfter(dayjs())
describe('Home page', () => {
let api: ReturnType<typeof setupApiMocks>
beforeEach(async () => {
api = setupApiMocks()
await resetStorage()
// zustand stores are module singletons and are not covered by clearMocks.
useNavigationStore.setState({
isNavigatedFromHome: false,
selectedStoreId: null,
})
})
it('requests the products cache url derived from common.essentialConsts', async () => {
renderHome()
await waitFor(() => {
expect(
api.fetchMock.mock.calls.some(([url]) =>
String(url).includes('common.essentialConsts')
)
).toBe(true)
})
await waitFor(() => {
expect(api.axiosGet).toHaveBeenCalledWith(PRODUCTS_URL)
})
})
it('shows a tab for every tag', async () => {
await renderLoadedHome()
for (const tag of tags) {
const tab = screen.getByTestId(`tag-tab-${tag.id}`)
expect(within(tab).getByText(tag.tagName)).toBeVisible()
}
})
it('shows every product of every tag, expanding each grid once', async () => {
await renderLoadedHome()
for (const tag of tags) {
fireEvent.press(screen.getByTestId(`tag-tab-${tag.id}`))
const expected = orderedProductIdsForTag(tag)
expect(expected.length).toBeGreaterThan(0)
for (const id of expected.slice(0, TAG_GRID_PREVIEW)) {
expect(screen.getByTestId(`tag-product-${id}`)).toBeVisible()
}
if (expected.length <= TAG_GRID_PREVIEW) continue
// Items past the preview are withheld until the grid is expanded.
expect(
screen.queryByTestId(`tag-product-${expected[TAG_GRID_PREVIEW]}`)
).toBeNull()
fireEvent.press(screen.getByTestId(`tag-show-more-${tag.id}`))
for (const id of expected) {
expect(screen.getByTestId(`tag-product-${id}`)).toBeVisible()
}
}
})
it('renders a tag with its out-of-stock items last', async () => {
await renderLoadedHome()
let tagsWithBothGroups = 0
for (const tag of tags) {
expandTag(tag.id)
const rendered = screen
.getAllByTestId(/^tag-product-/)
.map((node) => idFromTestID(node.props.testID, 'tag-product-'))
const declared = productIdsForTag(tag)
expect(rendered.length).toBe(declared.length)
const inStockRendered = rendered.filter(
(id) => !expectedOutOfStock.has(id)
)
const outOfStockRendered = rendered.filter((id) =>
expectedOutOfStock.has(id)
)
const declaredInStock = declared.filter(
(id) => !expectedOutOfStock.has(id)
)
const declaredOutOfStock = declared.filter((id) =>
expectedOutOfStock.has(id)
)
if (declaredInStock.length > 0 && declaredOutOfStock.length > 0) {
tagsWithBothGroups += 1
}
// No in-stock item may appear after an out-of-stock item.
const firstOutOfStock = rendered.findIndex((id) =>
expectedOutOfStock.has(id)
)
if (firstOutOfStock !== -1) {
expect(
rendered.slice(firstOutOfStock).every((id) => expectedOutOfStock.has(id))
).toBe(true)
}
// Within each group the admin-curated order is preserved.
expect(inStockRendered).toEqual(declaredInStock)
expect(outOfStockRendered).toEqual(declaredOutOfStock)
}
// Guarantees the ordering property above was actually exercised.
expect(tagsWithBothGroups).toBeGreaterThan(0)
})
it('shows the upcoming slots in delivery order', async () => {
await renderLoadedHome()
const expected = mockSlots.slots
.filter(isUpcomingSlot)
.sort((a, b) => {
const byDelivery = dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime))
return byDelivery !== 0
? byDelivery
: dayjs(a.freezeTime).diff(dayjs(b.freezeTime))
})
// The section only renders the first 5 of the upcoming slots.
expect(expected.length).toBeGreaterThan(5)
await waitFor(() => {
expect(screen.getAllByTestId(/^slot-card-/).length).toBeGreaterThan(0)
})
const rendered = screen
.getAllByTestId(/^slot-card-/)
.map((node) => idFromTestID(node.props.testID, 'slot-card-'))
expect(rendered).toEqual(expected.slice(0, 5).map((s) => s.id))
for (const slot of expected.slice(5)) {
expect(screen.queryByTestId(`slot-card-${slot.id}`)).toBeNull()
}
})
it('hides a slot whose freeze time has passed', async () => {
await renderLoadedHome()
const upcoming = mockSlots.slots.filter(isUpcomingSlot)
const hidden = mockSlots.slots.filter((slot) => !isUpcomingSlot(slot))
expect(hidden.map((slot) => slot.id)).toContain(EXPIRED_HOME_SLOT_ID)
// Sanity: the hidden slot really is a future delivery, so only its freeze
// time can be responsible for hiding it.
const homeSlot = mockSlots.slots.find((s) => s.id === EXPIRED_HOME_SLOT_ID)!
expect(dayjs(homeSlot.deliveryTime).isAfter(dayjs())).toBe(true)
expect(dayjs(homeSlot.freezeTime).isAfter(dayjs())).toBe(false)
await waitFor(() => {
expect(screen.getAllByTestId(/^slot-card-/).length).toBeGreaterThan(0)
})
expect(screen.queryByTestId(`slot-card-${EXPIRED_HOME_SLOT_ID}`)).toBeNull()
const rendered = screen
.getAllByTestId(/^slot-card-/)
.map((node) => idFromTestID(node.props.testID, 'slot-card-'))
expect(rendered).not.toContain(EXPIRED_HOME_SLOT_ID)
expect(rendered).toEqual(upcoming.slice(0, 5).map((s) => s.id))
})
it('hides a slot whose freeze time has passed in the add-to-cart dialog', async () => {
await renderLoadedHome()
const [productId] = mockSlots.slots.find(
(s) => s.id === EXPIRED_DIALOG_SLOT_ID
)!.products.map((p) => p.id)
const dialogSlot = mockSlots.slots.find(
(s) => s.id === EXPIRED_DIALOG_SLOT_ID
)!
expect(dayjs(dialogSlot.deliveryTime).isAfter(dayjs())).toBe(true)
expect(dayjs(dialogSlot.freezeTime).isAfter(dayjs())).toBe(false)
const tag = tags.find((t) => productIdsForTag(t).includes(productId))
expect(tag).toBeDefined()
expandTag(tag!.id)
fireEvent.press(
within(screen.getByTestId(`tag-product-${productId}`)).getByTestId(
'add-to-cart-icon'
)
)
// The expired slot's option is not offered...
expect(
screen.queryByTestId(
`slot-${dayjs(dialogSlot.deliveryTime).format('YYYY-MM-DD-HH-mm')}`
)
).toBeNull()
// ...while a real, still-open slot is, so the dialog remains usable.
const openSlot = mockSlots.slots
.filter(
(s) =>
s.id !== EXPIRED_DIALOG_SLOT_ID &&
s.products.some((p) => p.id === productId)
)
.find((s) => dayjs(s.freezeTime).isAfter(dayjs()))
expect(openSlot).toBeDefined()
fireEvent.press(
screen.getByTestId(
`slot-${dayjs(openSlot!.deliveryTime).format('YYYY-MM-DD-HH-mm')}`
)
)
fireEvent.press(screen.getByTestId('add-to-cart-confirm'))
await waitFor(() => {
expect(screen.getByText(/1 Item/)).toBeVisible()
})
})
it('shows the load-all button until every product is loaded', async () => {
await renderLoadedHome()
expect(screen.getByTestId('products-show-more')).toBeVisible()
let presses = 0
while (screen.queryByTestId('products-show-more')) {
fireEvent.press(screen.getByTestId('products-show-more'))
presses += 1
if (presses > products.length) {
throw new Error('products-show-more never disappeared')
}
}
expect(screen.queryByTestId('products-show-more')).toBeNull()
expect(presses).toBe(
Math.ceil((products.length - PRODUCT_PAGE_SIZE) / PRODUCT_PAGE_SIZE)
)
})
it('marks exactly the unavailable products out of stock in every tag', async () => {
await renderLoadedHome()
for (const tag of tags) {
expandTag(tag.id)
const ids = productIdsForTag(tag)
expect(ids.length).toBeGreaterThan(0)
for (const id of ids) {
const card = screen.getByTestId(`tag-product-${id}`)
const badge = within(card).queryByTestId('out-of-stock-badge')
if (expectedOutOfStock.has(id)) {
expect(badge).not.toBeNull()
} else {
expect(badge).toBeNull()
}
}
}
})
it('lists the main product list with unavailable items last', async () => {
await renderLoadedHome()
// displayedProducts keeps cache order within each group and only moves
// unavailable items to the end, so this is the expected render order.
const expectedOrder = [
...products.filter((p) => !expectedOutOfStock.has(p.id)).map((p) => p.id),
...products.filter((p) => expectedOutOfStock.has(p.id)).map((p) => p.id),
]
const rendered = screen
.getAllByTestId(/^product-item-/)
.map((node) => idFromTestID(node.props.testID, 'product-item-'))
expect(rendered.length).toBeGreaterThan(0)
// FlatList virtualizes, so only a head of the list is mounted. Whatever is
// mounted must be that head, in that order.
expect(rendered).toEqual(expectedOrder.slice(0, rendered.length))
// A missing sort would put an unavailable product at the very front.
expect(rendered.some((id) => expectedOutOfStock.has(id))).toBe(false)
expect(expectedOutOfStock.size).toBeGreaterThan(0)
expect(expectedOutOfStock.has(products[0].id)).toBe(true)
})
// The main list cannot verify badges for unavailable products: they sort last
// and FlatList virtualizes, so those rows never mount. The tag grids carry
// that check; the ordering itself is covered by the test above.
it('adds items to the cart', async () => {
await renderLoadedHome()
expect(screen.getByText('No Items In Cart')).toBeVisible()
expect(screen.getByTestId('go-to-cart')).toBeVisible()
const tag = tags.find(
(t) => productIdsForTag(t).filter((id) => !expectedOutOfStock.has(id)).length >= 2
)
expect(tag).toBeDefined()
const inStock = productIdsForTag(tag!)
.filter((id) => !expectedOutOfStock.has(id))
.slice(0, 2)
expandTag(tag!.id)
for (const [index, id] of inStock.entries()) {
addToCartFromTagGrid(id)
const count = index + 1
await waitFor(() => {
expect(
screen.getByText(new RegExp(`${count} ${count === 1 ? 'Item' : 'Items'}`))
).toBeVisible()
})
}
// The first product's card now shows a quantity stepper, not the add icon.
expect(
within(screen.getByTestId(`tag-product-${inStock[0]}`)).queryByTestId(
'add-to-cart-icon'
)
).toBeNull()
})
it('updates and removes a cart item through the card quantity stepper', async () => {
await renderLoadedHome()
const tag = tags.find(
(t) => productIdsForTag(t).filter((id) => !expectedOutOfStock.has(id)).length >= 1
)
expect(tag).toBeDefined()
const [productId] = productIdsForTag(tag!).filter(
(id) => !expectedOutOfStock.has(id)
)
expandTag(tag!.id)
const card = () => screen.getByTestId(`tag-product-${productId}`)
addToCartFromTagGrid(productId)
await waitFor(() => expect(screen.getByText(/1 Item/)).toBeVisible())
expect(within(card()).getByTestId('mini-quantifier-value')).toHaveTextContent('1')
// Pressing increment on the card does not change the cart inline: the card
// opens the dialog in update mode, preloaded with the current quantity (the
// pressed delta is discarded by ProductCard).
fireEvent.press(within(card()).getByTestId('mini-quantifier-increment'))
expect(screen.getByText('Update Item')).toBeVisible()
expect(screen.getByTestId('quantifier-value')).toHaveTextContent('1')
// The dialog is where the quantity actually changes.
fireEvent.press(screen.getByTestId('quantifier-increment'))
expect(screen.getByTestId('quantifier-value')).toHaveTextContent('2')
fireEvent.press(screen.getByTestId('add-to-cart-confirm'))
// The floating bar counts cart lines, not units, so a single product at
// quantity 2 still reads "1 Item" - assert the per-card quantity instead.
await waitFor(() =>
expect(within(card()).getByTestId('mini-quantifier-value')).toHaveTextContent('2')
)
expect(screen.getByText(/1 Item/)).toBeVisible()
// Decrementing on the card reopens the update dialog; removal happens via
// the dialog's delete button, which drops the item back to zero.
fireEvent.press(within(card()).getByTestId('mini-quantifier-decrement'))
expect(screen.getByText('Update Item')).toBeVisible()
fireEvent.press(screen.getByTestId('remove-from-cart'))
await waitFor(() => expect(screen.getByText('No Items In Cart')).toBeVisible())
expect(within(card()).getByTestId('add-to-cart-icon')).toBeVisible()
})
it('shows the store list and navigates when a store is tapped', async () => {
await renderLoadedHome()
const store = storesResponse.stores[0]
const row = screen.getByTestId(`store-item-${store.id}`)
expect(
within(row).getByText(store.name.replace(/^The\s+/i, ''))
).toBeVisible()
fireEvent.press(row)
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/stores')
const navigation = useNavigationStore.getState()
expect(navigation.isNavigatedFromHome).toBe(true)
expect(navigation.selectedStoreId).toBe(store.id)
})
it('opens the product detail page from a tag grid card', async () => {
await renderLoadedHome()
const tag = tags[0]
const [productId] = productIdsForTag(tag)
fireEvent.press(screen.getByTestId(`tag-tab-${tag.id}`))
fireEvent.press(
within(screen.getByTestId(`tag-product-${productId}`)).getByTestId(
'product-card'
)
)
expect(routerMock.push).toHaveBeenCalledWith(
`/(drawer)/(tabs)/home/product-detail/${productId}`
)
})
it('opens the product detail page from the main list', async () => {
await renderLoadedHome()
const [productId] = products.filter(
(p) => !expectedOutOfStock.has(p.id)
).map((p) => p.id)
fireEvent.press(
within(screen.getByTestId(`product-item-${productId}`)).getByTestId(
'product-card'
)
)
expect(routerMock.push).toHaveBeenCalledWith(
`/(drawer)/(tabs)/home/product-detail/${productId}`
)
})
it('opens the slot detail page when a slot card is tapped', async () => {
await renderLoadedHome()
const slot = mockSlots.slots.filter(isUpcomingSlot)[0]
fireEvent.press(screen.getByTestId(`slot-card-${slot.id}`))
expect(routerMock.push).toHaveBeenCalledWith(
`/(drawer)/(tabs)/home/slot-view?slotId=${slot.id}`
)
})
it('opens search from the search bar', async () => {
await renderLoadedHome()
fireEvent.press(screen.getByTestId('home-search'))
expect(routerMock.push).toHaveBeenCalledWith(
'/(drawer)/(tabs)/home/search-results'
)
})
it('opens the cart from the floating bar', async () => {
await renderLoadedHome()
fireEvent.press(screen.getByTestId('go-to-cart'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/cart')
})
})