diff --git a/.commandcode/settings.json b/.commandcode/settings.json index 1835bd3..fbcf8ce 100644 --- a/.commandcode/settings.json +++ b/.commandcode/settings.json @@ -92,7 +92,13 @@ "Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && adb shell am force-stop in.freshyo.app; adb shell monkey -p in.freshyo.app -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1; sleep 16; adb shell uiautomator dump /sdcard/ui2.xml >/dev/null 2>&1; adb shell cat /sdcard/ui2.xml > \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" 2>/dev/null; echo \"size: $(wc -c < \"$COMMANDCODE_SCRATCHPAD/ui2.xml\")\"; echo \"=== product-card occurrences ===\"; grep -c \"product-card\" \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" || true; echo \"=== resource-id sample ===\"; grep -oE 'resource-id=\"[^\"]{1,50}\"' \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" | sort -u | head -15; echo \"=== content-desc sample ===\"; grep -oE 'content-desc=\"[^\"]{2,40}\"' \"$COMMANDCODE_SCRATCHPAD/ui2.xml\" | sort -u | head -15)", "Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && cat > \"$COMMANDCODE_SCRATCHPAD/probe2.yaml\" <<'YAML' appId: in.freshyo.app --- - assertVisible: id: \"product-card\" YAML \"$HOME/.maestro/bin/maestro\" test \"$COMMANDCODE_SCRATCHPAD/probe2.yaml\" --platform android 2>&1 | tail -6)", "Shell(bash e2e/run.sh flows/place-order.yaml 2 >& 1)", - "Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && ls ~/.maestro/tests/2026-09-14_154602/place-order/screen-hierarchy/ 2>/dev/null; F=$(ls ~/.maestro/tests/2026-09-14_154602/place-order/screen-hierarchy/*Me* 2>/dev/null | head -1); echo \"file: $F\"; grep -oE '\"(text|accessibilityText|resource-id)\": \"[^\"]{1,30}\"' \"$F\" 2>/dev/null | sort -u | head -40)" + "Shell(cd /Users/mohammedshafiuddin/WebDev/freshyo && ls ~/.maestro/tests/2026-09-14_154602/place-order/screen-hierarchy/ 2>/dev/null; F=$(ls ~/.maestro/tests/2026-09-14_154602/place-order/screen-hierarchy/*Me* 2>/dev/null | head -1); echo \"file: $F\"; grep -oE '\"(text|accessibilityText|resource-id)\": \"[^\"]{1,30}\"' \"$F\" 2>/dev/null | sort -u | head -40)", + "Shell(mkdir:*)", + "Shell(node -e console.log('node sees NODE_ENV:', JSON.stringify(process.env.NODE_ENV)))", + "Shell(NODE_ENV=test bunx jest --config tests/jest.config.js tests/home-page/navigation.test.tsx 2 >& 1)", + "Shell(NODE_ENV=test bunx jest --config tests/jest.config.js tests/home-page/navigation.test.tsx -t routes to the slot view 2 >& 1)", + "Shell(node inspect.cjs)", + "Shell(node -e \" const s=require('/Users/mohammedshafiuddin/WebDev/freshyo/apps/user-ui/tests/mocks/mock-slots-response.json'); for (const id of [2,40,23]) { const idx = s.slots.findIndex(sl=>sl.products.some(p=>p.id===id)); const sl = s.slots[idx]; console.log('product', id, '-> slot index', idx, 'slotId', sl && sl.id, 'delivery', sl && sl.deliveryTime); } console.log('slot order:', s.slots.map(sl=>sl.id).join(',')); \")" ], "deny": [], "defaultMode": "default" diff --git a/.commandcode/taste/taste/taste.md b/.commandcode/taste/taste/taste.md index 1274807..96f1ddf 100644 --- a/.commandcode/taste/taste/taste.md +++ b/.commandcode/taste/taste/taste.md @@ -1,4 +1,6 @@ # Taste +- Wants each UI component/feature to own a dedicated test file rather than sharing one file across related features — explicitly asked for "a file exclusively for the floating cart bar tests", replacing the combined cart test file (deleting the superseded one and updating the README/index so there's exactly one file per component). Confidence: 0.6 +- For cart/price tests, expects the money and delivery logic to be verified with concrete, pinned fixture products and exact numbers: add exactly the named products, then assert the running total, the free-delivery threshold (remaining amount, then "unlocked"), the slot each item lands in, and that the total recomputes when quantity changes — rather than loosely computed expectations ("note some products, add exactly those products and confirm the free delivery threshold, confirm the total cost, confirm the slots, test the price on change of quantity too"). Confidence: 0.6 - Defines tunable/magic numbers as named module-level constants in the SAME file where they are used (e.g., `const TOKENS_PER_QUEUE_MESSAGE = 5` next to the code it configures, with a short explanatory comment) instead of inline literals or a shared/global config — explicitly stated: "Define 5 as a constant in the same file." Confidence: 0.7 - Prefers that the agent not run typechecks; instead, read the project's AGENTS.md for instructions on what to do/not do before finalizing work. Confidence: 0.9 - Judges completion by seeing the feature live in the running app ("I still don't see it on the /home route page"), so for data-driven features the agent must verify the app's actual runtime data source (API base URL, cache/backend) has the required data — not just that code builds and typechecks. Confirmed when the user signaled success only after the fix (pointing web-ui at the local backend with the tags data) made the section visible in the running app, and reconfirmed with the admin-ui product selector showing no products because it points at the production worker. Confidence: 0.9 @@ -130,6 +132,9 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the - For React Native / Expo mobile E2E automation, prefers **Maestro** (not Detox/Appium), with its flow configs in a folder at the repo ROOT named `e2e/` — "I want test end to end test automation with maestro. have a folder at the root named e2e" — mirroring his `tests/`-at-root convention for Playwright. Expects the tool's own YAML workspace layout inside it (`config.yaml`, `flows/`, reusable `subflows/`), not per-app test dirs. Confidence: 0.85 - Wants E2E flows to take the shortest realistic user path and skip unnecessary intermediate screens — e.g., add to the cart directly from the home product card's cart icon instead of opening the product-detail screen first ("don't open any product detail. Just click on the cart icon of any product, then go to the cart page and then place order"). Confidence: 0.5 - When he pastes a runtime error/log (e.g., a tRPC/D1 `Failed query: select ... from "key_val_store"` 500), he asks for an explanation first — "what does this error mean. Why am I seeing it" — expecting the agent to investigate and explain the root cause (local D1 state, migrations/config) before changing any code, not to jump straight to a fix. Confidence: 0.5 +- Wants a markdown file placed INSIDE the test directory (e.g. `apps/user-ui/tests/home-page/README.md`) that enumerates every test case covered — all cases grouped by test file with the per-file count and a one-line "what it asserts" for each, plus how to run the suite and the folder layout ("now make an md file in the dir which lists all the test cases which we've covered"). Coverage documentation should live with the tests it describes, not only in a central report. Confidence: 0.65 +- Groups unit/integration tests by the page or feature they cover into a dedicated subfolder inside the app's `tests/` directory — e.g., `apps/user-ui/tests/home-page/` holding that page's test files while shared mocks/fixtures stay at the `tests/` root ("create a folder home page and then move the tests of that page in it"). Confidence: 0.7 +- When adding coverage, expects the agent to determine and state explicitly whether any additional API mock responses are needed for the new tests — reusing/extending the existing mock infrastructure (variants of already-mocked endpoints, local storage for the cart) rather than adding unnecessary new mocks ("Do we need mock response of any other apis?"). Confidence: 0.6 e changes. Confidence: 0.95 er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the agent to mirror that pattern exactly, including details like item counts and container styling. Confidence: 0.9 als) rather than introducing new brand palettes; approval of a redesign's layout/composition does not imply approval of color or theme changes. Confidence: 0.95 diff --git a/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx index 124348c..2548cc4 100755 --- a/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx @@ -81,6 +81,7 @@ const RenderStore = memo(({ item }: ListItemProps) => { return ( { const handlePress = useCallback(() => onPress(item.id), [item.id, onPress]); return ( - + dayjs(slot.deliveryTime).isAfter(now)) + .filter(slot => dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now)) .sort((a, b) => { const deliveryDiff = dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)); if (deliveryDiff !== 0) return deliveryDiff; @@ -726,6 +727,7 @@ export default function Dashboard() { hasMore ? ( = ({ )} {displayIsOutOfStock && ( - + Out of Stock diff --git a/apps/user-ui/src/components/AddToCartDialog.tsx b/apps/user-ui/src/components/AddToCartDialog.tsx index 6157c9f..7f5e2be 100644 --- a/apps/user-ui/src/components/AddToCartDialog.tsx +++ b/apps/user-ui/src/components/AddToCartDialog.tsx @@ -222,6 +222,7 @@ export default function AddToCartDialog() { {isUpdate && ( { if (cartItem?.id) { removeFromCart.mutate( diff --git a/apps/user-ui/tests/home-page/README.md b/apps/user-ui/tests/home-page/README.md new file mode 100644 index 0000000..1df98e5 --- /dev/null +++ b/apps/user-ui/tests/home-page/README.md @@ -0,0 +1,150 @@ +# Home page tests + +Jest integration tests for the user-ui home page +(`apps/user-ui/app/(drawer)/(tabs)/home/index.tsx`) and the components it renders. + +- **9 files, 48 tests** +- Runner: `jest-expo` + `@testing-library/react-native`, config at `tests/jest.config.js` +- Network is mocked at the layer (`tests/mocks/api.ts`); components, stores, hooks and the router wiring stay real + +## Run + +From `apps/user-ui`: + +```bash +NODE_ENV=test bun run test tests/home-page # this folder +NODE_ENV=test bun run test # every test in the app +NODE_ENV=test bun run test:watch # watch mode +``` + +`NODE_ENV=test` is required: with `NODE_ENV=production` React loads its production +build and every render throws *"act(...) is not supported in production builds of +React"*. (Raw jest equivalent: `NODE_ENV=test bunx jest --config tests/jest.config.js`.) + +## Layout + +| File | Tests | Covers | +| --- | --- | --- | +| `home.test.tsx` | 18 | Core home behaviour (mocked router) | +| `navigation.test.tsx` | 3 | Real expo-router navigation + params | +| `home-states.test.tsx` | 5 | Loading / error / empty states | +| `home-refresh.test.tsx` | 2 | Pull-to-refresh fan-out | +| `home-slots.test.tsx` | 3 | Slot card badge + labels | +| `home-add-to-cart-dialog.test.tsx` | 3 | Add-to-cart dialog specifics | +| `home-floating-cart-bar.test.tsx` | 5 | Floating cart bar (pinned products, totals, slots) | +| `next-order-glimpse.test.tsx` | 5 | Upcoming-order preview | +| `home-cards.test.tsx` | 4 | Product card / store list details | +| `render.tsx` | — | Shared provider stack + helpers (not a test) | + +Shared fixtures live in `tests/mocks/` (network + router + auth + refresh) and +`tests/__fixtures__/`. `setup.ts` stubs auth/refresh/storage and freezes the clock. + +--- + +## `home.test.tsx` — core home behaviour + +API responses are mocked at the network layer; the tree includes the real +`CentralStoreInitializer` so the slot/availability/product stores are populated as +in the app. `expo-router` is mocked here. + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | requests the products cache url derived from common.essentialConsts | Fetches `common.essentialConsts`, then derives and requests the products CDN URL | +| 2 | shows a tab for every tag | One `tag-tab-*` per tag, each showing its name | +| 3 | shows every product of every tag, expanding each grid once | 6-item preview per tag, "Show More" reveals the rest | +| 4 | renders a tag with its out-of-stock items last | Out-of-stock pushed to the end; admin order preserved within each group | +| 5 | shows the upcoming slots in delivery order | First 5 upcoming slots, sorted by delivery then freeze | +| 6 | hides a slot whose freeze time has passed | Expired-freeze slot absent from the home strip | +| 7 | hides a slot whose freeze time has passed in the add-to-cart dialog | Expired slot not offered; a valid slot still is | +| 8 | shows the load-all button until every product is loaded | `products-show-more` pages 21 at a time until gone | +| 9 | marks exactly the unavailable products out of stock in every tag | Badge present iff the product is unavailable | +| 10 | lists the main product list with unavailable items last | Mounted head of the list matches expected sort order | +| 11 | adds items to the cart | Floating bar counts lines; card swaps add icon for a stepper | +| 12 | updates and removes a cart item through the card quantity stepper | Increment opens update dialog; quantity changes in dialog; delete removes | +| 13 | shows the store list and navigates when a store is tapped | Store row renders; tap pushes to stores + sets navigation store | +| 14 | opens the product detail page from a tag grid card | Push `.../product-detail/` | +| 15 | opens the product detail page from the main list | Push `.../product-detail/` | +| 16 | opens the slot detail page when a slot card is tapped | Push `.../slot-view?slotId=` | +| 17 | opens search from the search bar | Push `.../search-results` | +| 18 | opens the cart from the floating bar | Push `.../home/cart` | + +## `navigation.test.tsx` — real router + +Renders the actual `expo-router` (via `expo-router/testing-library`) with a route +map mirroring `app/`, proving pushed URLs resolve and params arrive. + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | routes to the product detail screen carrying the id | Pathname `/home/product-detail/`, `id` param delivered | +| 2 | routes to the slot view carrying the slotId | Pathname `/home/slot-view`, `slotId` search param delivered | +| 3 | routes to the stores screen | Pathname `/stores`, stores stub visible | + +## `home-states.test.tsx` — page states + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | shows the loading screen while the products request is pending | "Loading products..." while the products request never resolves | +| 2 | shows the products error state when the products request fails | "Oops!" + "Failed to load products" | +| 3 | shows the app-settings error state when essentialConsts fails | "Oops!" + "Failed to load app settings" | +| 4 | shows the empty state when there are no products | "No products available" (list empty component) | +| 5 | shows the empty-category message for a tag with no products | "No products in this category yet" for an empty tag | + +## `home-refresh.test.tsx` — refresh + +`handleRefresh` fans out to products, slots, stores and essentialConsts. +Availability is intentionally not asserted (it is not refetched). + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | refetches every data source through useManualRefresh | Each URL requested again after the manual-refresh callback fires | +| 2 | refetches every data source through useMarkDataFetchers | Same, via the mark-data-fetchers callback | + +## `home-slots.test.tsx` — slot card details + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | marks only the slots closing within 4 hours | "CLOSING SOON" iff freeze is within 4h (both branches exercised) | +| 2 | labels each slot with its delivery range and order-by time | Delivery range, order-by clock time, date line | +| 3 | shows how many products each slot holds | "View all N items" matches the slot's product count | + +## `home-add-to-cart-dialog.test.tsx` — add-to-cart dialog + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | offers flash delivery and routes to the flash cart when enabled | Flash row shown (flash enabled + SKU flash-available); confirm pushes the flash cart | +| 2 | keeps confirm disabled until a delivery option is chosen | Confirm disabled with no slot selected | +| 3 | pre-selects the cart quantity when reopened from the card stepper | Update mode shows the current cart quantity | + +## `home-floating-cart-bar.test.tsx` — floating cart bar + +Uses two **pinned** products with exact fixture prices so every money and slot +expectation is a fixed number: `2` "Chicken Breast 500 g" (₹215) and `40` +"Chicken regular cut Large pieces" (₹129), both in the "Chicken" tag. A single +expanded grid holds them; the free-delivery threshold is ₹249. + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | adds exactly the pinned products and tracks the total and delivery threshold | ₹215 → "₹34 more for FREE Delivery"; +₹129 → ₹344 • 2 Items → "Free Delivery Unlocked" | +| 2 | places each pinned product in the first open slot it belongs to | Each line shows its slot label (both resolve to slot 1849) | +| 3 | recomputes the total when the quantity changes | Quantity 1 → 2 moves the total ₹215 → ₹430 (still one line) | +| 4 | expands into the cart dialog with the line and the subtotal | "Your Cart" dialog shows the item and Subtotal | +| 5 | re-slots a stored cart item whose slot no longer exists | `useReconcileCartSlots` rewrites the invalid `slotId` to a real slot | + +## `next-order-glimpse.test.tsx` — upcoming order preview + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | renders nothing and never requests orders when signed out | No "Upcoming Order"; `user.order.getOrders` not requested | +| 2 | previews an upcoming order | Order id, "N items • ₹total", status label (`pending` → "Confirmed") | +| 3 | flags a flash order | "FLASH" badge + "30-Min Delivery" | +| 4 | ignores cancelled and completed orders | Cancelled / successful orders produce no preview | +| 5 | routes to my-orders when a card is tapped | `router.replace('/(drawer)/(tabs)/me')` | + +## `home-cards.test.tsx` — card / list details + +| # | Test | What it asserts | +| --- | --- | --- | +| 1 | never renders a combo-only SKU | Combo-only SKU (149) absent from the main list and every tag grid | +| 2 | renders every store with the leading "The " stripped | All stores render; `The ` prefix removed from the display name | +| 3 | strikes through the market price when it is above the selling price | Market price shown when greater than the selling price | +| 4 | shows a fallback when a product image fails to load | "Image failed to load" after an image error | diff --git a/apps/user-ui/tests/home-page/home-add-to-cart-dialog.test.tsx b/apps/user-ui/tests/home-page/home-add-to-cart-dialog.test.tsx new file mode 100644 index 0000000..0c59498 --- /dev/null +++ b/apps/user-ui/tests/home-page/home-add-to-cart-dialog.test.tsx @@ -0,0 +1,119 @@ +/** + * AddToCartDialog behaviour reached from the home tag grid: + * - the flash-delivery option (only when flash is enabled AND the SKU is + * flash available) and its route, + * - the confirm button staying disabled until a delivery option is chosen, + * - reopening from the card stepper pre-loading the cart quantity. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { fireEvent, screen, waitFor, within } from '@testing-library/react-native' + +import { + FLASH_ENABLED_CONSTS, + outOfStockIds, + resetEssentialConsts, + resetStorage, + setupApiMocks, +} from '../mocks/api' +import { routerMock } from '../mocks/router' +import { useNavigationStore } from '@/src/store/navigationStore' +import { + addToCartFromTagGrid, + expandTag, + flashAvailableById, + productIdsForTag, + renderLoadedHome, + tags, +} from './render' + +/** First in-stock product in a tag that is also flash available. */ +const findFlashProduct = () => { + for (const tag of tags) { + for (const id of productIdsForTag(tag)) { + if (!outOfStockIds.has(id) && flashAvailableById.get(id) === true) { + return { tagId: tag.id, productId: id } + } + } + } + throw new Error('[tests] no in-stock flash product in any tag') +} + +/** First in-stock product in any tag. */ +const findInStockProduct = () => { + for (const tag of tags) { + for (const id of productIdsForTag(tag)) { + if (!outOfStockIds.has(id)) return { tagId: tag.id, productId: id } + } + } + throw new Error('[tests] no in-stock product in any tag') +} + +const openDialog = ({ tagId, productId }: { tagId: number; productId: number }) => { + expandTag(tagId) + fireEvent.press( + within(screen.getByTestId(`tag-product-${productId}`)).getByTestId( + 'add-to-cart-icon' + ) + ) +} + +describe('Home add-to-cart dialog', () => { + beforeEach(async () => { + // A consts override is persisted by useGetEssentialConsts, so clear it + // between tests or the flash-enabled payload leaks into the next case. + await resetEssentialConsts() + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + it('offers flash delivery and routes to the flash cart when enabled', async () => { + setupApiMocks({ consts: FLASH_ENABLED_CONSTS }) + await renderLoadedHome() + + openDialog(findFlashProduct()) + + expect(screen.getByText('1 hr Delivery')).toBeVisible() + fireEvent.press(screen.getByText('1 hr Delivery')) + fireEvent.press(screen.getByTestId('add-to-cart-confirm')) + + expect(routerMock.push).toHaveBeenCalledWith( + '/(drawer)/(tabs)/flash-delivery/(products)' + ) + }) + + it('keeps confirm disabled until a delivery option is chosen', async () => { + setupApiMocks() + await renderLoadedHome() + + openDialog(findInStockProduct()) + + expect(screen.getByTestId('add-to-cart-confirm')).toBeDisabled() + }) + + it('pre-selects the cart quantity when reopened from the card stepper', async () => { + setupApiMocks() + await renderLoadedHome() + + const target = findInStockProduct() + expandTag(target.tagId) + addToCartFromTagGrid(target.productId) + + await waitFor(() => expect(screen.getByText(/1 Item/)).toBeVisible()) + + // The card increment opens the dialog in update mode, preloaded with the + // cart quantity (the pressed delta is discarded by ProductCard). + fireEvent.press( + within(screen.getByTestId(`tag-product-${target.productId}`)).getByTestId( + 'mini-quantifier-increment' + ) + ) + + expect(screen.getByText('Update Item')).toBeVisible() + expect(screen.getByTestId('quantifier-value')).toHaveTextContent('1') + }) +}) diff --git a/apps/user-ui/tests/home-page/home-cards.test.tsx b/apps/user-ui/tests/home-page/home-cards.test.tsx new file mode 100644 index 0000000..fc454e7 --- /dev/null +++ b/apps/user-ui/tests/home-page/home-cards.test.tsx @@ -0,0 +1,102 @@ +/** + * Home card/list details: combo-only SKUs are hidden, every store renders with + * its display name, and ProductCard's market-price and image-error branches. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { Image } from 'react-native' +import { fireEvent, screen, within } from '@testing-library/react-native' + +import { outOfStockIds, resetStorage, setupApiMocks } from '../mocks/api' +import storesResponse from '../mocks/mock-stores-response.json' +import { useNavigationStore } from '@/src/store/navigationStore' +import { + expandTag, + marketPriceById, + priceById, + productIdsForTag, + renderLoadedHome, + tags, +} from './render' + +const COMBO_ONLY_ID = 149 + +const firstInStockInTag = () => { + for (const tag of tags) { + for (const id of productIdsForTag(tag)) { + if (!outOfStockIds.has(id)) return { tagId: tag.id, productId: id } + } + } + throw new Error('[tests] no in-stock product in any tag') +} + +/** First in-stock tag product whose marketPrice is above its selling price. */ +const productWithMarkup = () => { + for (const tag of tags) { + for (const id of productIdsForTag(tag)) { + if (outOfStockIds.has(id)) continue + const marketPrice = marketPriceById.get(id) + const price = priceById.get(id) + if (marketPrice != null && price != null && marketPrice > price) { + return { tagId: tag.id, productId: id, marketPrice } + } + } + } + throw new Error('[tests] no in-stock product with a market price above its price') +} + +describe('Home cards + lists', () => { + beforeEach(async () => { + setupApiMocks() + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + it('never renders a combo-only SKU', async () => { + await renderLoadedHome() + + expect(screen.queryByTestId(`product-item-${COMBO_ONLY_ID}`)).toBeNull() + + for (const tag of tags) { + expandTag(tag.id) + expect(screen.queryByTestId(`tag-product-${COMBO_ONLY_ID}`)).toBeNull() + } + }) + + it('renders every store with the leading "The " stripped', async () => { + await renderLoadedHome() + + for (const store of storesResponse.stores) { + const row = screen.getByTestId(`store-item-${store.id}`) + expect( + within(row).getByText(store.name.replace(/^The\s+/i, '')) + ).toBeVisible() + } + }) + + it('strikes through the market price when it is above the selling price', async () => { + await renderLoadedHome() + + const target = productWithMarkup() + expandTag(target.tagId) + + const card = screen.getByTestId(`tag-product-${target.productId}`) + expect(within(card).getByText(`₹${target.marketPrice}`)).toBeVisible() + }) + + it('shows a fallback when a product image fails to load', async () => { + await renderLoadedHome() + + const target = firstInStockInTag() + expandTag(target.tagId) + const card = screen.getByTestId(`tag-product-${target.productId}`) + + fireEvent(within(card).UNSAFE_getByType(Image), 'error') + + expect(within(card).getByText('Image failed to load')).toBeVisible() + }) +}) diff --git a/apps/user-ui/tests/home-page/home-floating-cart-bar.test.tsx b/apps/user-ui/tests/home-page/home-floating-cart-bar.test.tsx new file mode 100644 index 0000000..62f0469 --- /dev/null +++ b/apps/user-ui/tests/home-page/home-floating-cart-bar.test.tsx @@ -0,0 +1,203 @@ +/** + * FloatingCartBar — the home page's cart bar and its "Your Cart" dialog. + * + * Products are pinned (see PINNED_PRODUCTS) so every money and slot expectation + * is an exact number rather than a computed one: + * - they all live in the "Chicken" tag, so a single expanded grid holds them, + * - their prices come from mock-availability-response.json, + * - the free-delivery threshold is consts.freeDeliveryThreshold (249). + * + * The bar counts cart LINES (itemCount = cartItems.length), so one product at + * quantity 2 still reads "1 Item". + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { fireEvent, screen, waitFor, within } from '@testing-library/react-native' +import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' +import dayjs from 'dayjs' + +import { + ESSENTIAL_CONSTS_DATA, + mockSlots, + outOfStockIds, + resetStorage, + setupApiMocks, +} from '../mocks/api' +import { useNavigationStore } from '@/src/store/navigationStore' +import { addToCartFromTagGrid, expandTag, renderLoadedHome } from './render' + +const FREE_DELIVERY_THRESHOLD = ESSENTIAL_CONSTS_DATA.freeDeliveryThreshold + +/** + * The products these tests add, with their exact fixture prices. + * 215 + 129 = 344 crosses the 249 threshold; 215 alone leaves a 34 gap. + */ +const PINNED_PRODUCTS = [ + { id: 2, name: 'Chicken Breast 500 g', price: 215, tagId: 1 }, + { id: 40, name: 'Chicken regular cut Large pieces', price: 129, tagId: 1 }, +] as const + +const [CHICKEN_BREAST, CHICKEN_LARGE_CUT] = PINNED_PRODUCTS + +/** Mirrors formatTimeRange in components/floating-cart-bar.tsx (includes the date). */ +const formatSlotLabel = (deliveryTime: string) => { + const time = dayjs(deliveryTime) + const endTime = time.add(1, 'hour') + const startPeriod = time.format('A') + const endPeriod = endTime.format('A') + + const range = + startPeriod === endPeriod + ? `${time.format('h')}-${endTime.format('h')} ${startPeriod}` + : `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}` + + return `${time.format('ddd, DD MMM ')}${range}` +} + +/** The slot addToCartFromTagGrid will pick: first in fixture order, freeze ahead. */ +const firstOpenSlotFor = (productId: number) => { + 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}`) + return slot +} + +const expandCart = () => { + // The collapsed bar only expands while it has items. + fireEvent.press(screen.getByText(/• \d+ Items?/)) +} + +describe('Floating cart bar', () => { + beforeEach(async () => { + setupApiMocks() + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + it('adds exactly the pinned products and tracks the total and delivery threshold', async () => { + await renderLoadedHome() + + // Guards the pinned prices against a fixture change. + for (const product of PINNED_PRODUCTS) { + expect(outOfStockIds.has(product.id)).toBe(false) + } + + expandTag(CHICKEN_BREAST.tagId) + + addToCartFromTagGrid(CHICKEN_BREAST.id) + await waitFor(() => + expect(screen.getByText(`₹${CHICKEN_BREAST.price} • 1 Item`)).toBeVisible() + ) + expect( + screen.getByText( + new RegExp(`₹${FREE_DELIVERY_THRESHOLD - CHICKEN_BREAST.price} more for`) + ) + ).toBeVisible() + + addToCartFromTagGrid(CHICKEN_LARGE_CUT.id) + + const total = CHICKEN_BREAST.price + CHICKEN_LARGE_CUT.price + await waitFor(() => expect(screen.getByText(`₹${total} • 2 Items`)).toBeVisible()) + expect(screen.getByText(/Free Delivery Unlocked/)).toBeVisible() + expect(screen.queryByText(/more for/)).toBeNull() + }) + + it('places each pinned product in the first open slot it belongs to', async () => { + await renderLoadedHome() + + expandTag(CHICKEN_BREAST.tagId) + addToCartFromTagGrid(CHICKEN_BREAST.id) + + // Wait for the first add to settle, otherwise its dialog cleanup can race + // the second product's dialog and drop it. + await waitFor(() => expect(screen.getByText(/• 1 Item/)).toBeVisible()) + + addToCartFromTagGrid(CHICKEN_LARGE_CUT.id) + await waitFor(() => expect(screen.getByText(/• 2 Items/)).toBeVisible()) + + const slot = firstOpenSlotFor(CHICKEN_BREAST.id) + // Both pinned products resolve to the first open slot in the fixture. + expect(firstOpenSlotFor(CHICKEN_LARGE_CUT.id).id).toBe(slot.id) + + expandCart() + expect(screen.getByText('Your Cart')).toBeVisible() + + // One delivery-slot label per cart line (each row shows its own slot). + expect(screen.getAllByText(formatSlotLabel(slot.deliveryTime))).toHaveLength( + PINNED_PRODUCTS.length + ) + }) + + it('recomputes the total when the quantity changes', async () => { + await renderLoadedHome() + + expandTag(CHICKEN_BREAST.tagId) + addToCartFromTagGrid(CHICKEN_BREAST.id) + await waitFor(() => expect(screen.getByText(/1 Item/)).toBeVisible()) + + // The card stepper reopens the dialog in update mode, preloaded with 1. + fireEvent.press( + within(screen.getByTestId(`tag-product-${CHICKEN_BREAST.id}`)).getByTestId( + 'mini-quantifier-increment' + ) + ) + expect(screen.getByText('Update Item')).toBeVisible() + expect(screen.getByTestId('quantifier-value')).toHaveTextContent('1') + + fireEvent.press(screen.getByTestId('quantifier-increment')) + expect(screen.getByTestId('quantifier-value')).toHaveTextContent('2') + fireEvent.press(screen.getByTestId('add-to-cart-confirm')) + + // Still one line, but the value is price * 2. + const doubled = CHICKEN_BREAST.price * 2 + await waitFor(() => expect(screen.getByText(`₹${doubled} • 1 Item`)).toBeVisible()) + expect(screen.getByText(/Free Delivery Unlocked/)).toBeVisible() + }) + + it('expands into the cart dialog with the line and the subtotal', async () => { + await renderLoadedHome() + + expandTag(CHICKEN_BREAST.tagId) + addToCartFromTagGrid(CHICKEN_BREAST.id) + await waitFor(() => expect(screen.getByText(/• 1 Item/)).toBeVisible()) + + expandCart() + + expect(screen.getByText('Your Cart')).toBeVisible() + expect(screen.getByText('Subtotal')).toBeVisible() + expect(screen.getAllByText(`₹${CHICKEN_BREAST.price}`).length).toBeGreaterThan(0) + }) + + it('re-slots a stored cart item whose slot no longer exists', async () => { + await StorageServiceCasual.setItem( + 'cart_items', + JSON.stringify([ + { + id: 1, + skuId: CHICKEN_BREAST.id, + quantity: 1, + slotId: 999999, + addedAt: new Date().toISOString(), + }, + ]) + ) + + await renderLoadedHome() + + await waitFor(async () => { + const raw = await StorageServiceCasual.getItem('cart_items') + const items = raw ? JSON.parse(raw) : [] + + expect(items).toHaveLength(1) + expect(items[0].slotId).not.toBe(999999) + expect(mockSlots.slots.some((s) => s.id === items[0].slotId)).toBe(true) + }) + }) +}) diff --git a/apps/user-ui/tests/home-page/home-refresh.test.tsx b/apps/user-ui/tests/home-page/home-refresh.test.tsx new file mode 100644 index 0000000..6149771 --- /dev/null +++ b/apps/user-ui/tests/home-page/home-refresh.test.tsx @@ -0,0 +1,85 @@ +/** + * Home page pull-to-refresh. + * + * The page funnels both useManualRefresh and useMarkDataFetchers into + * handleRefresh, which refetches products, slots, stores and essentialConsts. + * tests/setup.ts records those callbacks (tests/mocks/refresh.ts) so a test can + * invoke them directly. + * + * Availability is deliberately NOT asserted: handleRefresh does not refetch it. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { act, waitFor } from '@testing-library/react-native' + +import { resetStorage, setupApiMocks } from '../mocks/api' +import { refreshHooks, resetRefreshHooks } from '../mocks/refresh' +import { useNavigationStore } from '@/src/store/navigationStore' +import { renderLoadedHome } from './render' + +const countRequests = ( + mock: { mock: { calls: unknown[][] } }, + needle: string +) => mock.mock.calls.filter(([url]) => String(url).includes(needle)).length + +describe('Home page refresh', () => { + beforeEach(async () => { + resetRefreshHooks() + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + const expectRefetchFanOut = async (invoke: () => void) => { + const api = setupApiMocks() + await renderLoadedHome() + + const before = { + products: countRequests(api.axiosGet, 'products.json'), + stores: countRequests(api.axiosGet, 'stores.json'), + slots: countRequests(api.axiosGet, 'slots.json'), + consts: countRequests(api.fetchMock, 'common.essentialConsts'), + } + + expect(before.products).toBeGreaterThan(0) + expect(before.stores).toBeGreaterThan(0) + expect(before.slots).toBeGreaterThan(0) + expect(before.consts).toBeGreaterThan(0) + + await act(async () => { + invoke() + }) + + await waitFor(() => { + expect(countRequests(api.axiosGet, 'products.json')).toBeGreaterThan( + before.products + ) + expect(countRequests(api.axiosGet, 'stores.json')).toBeGreaterThan( + before.stores + ) + expect(countRequests(api.axiosGet, 'slots.json')).toBeGreaterThan( + before.slots + ) + expect(countRequests(api.fetchMock, 'common.essentialConsts')).toBeGreaterThan( + before.consts + ) + }) + } + + it('refetches every data source through useManualRefresh', async () => { + await expectRefetchFanOut(() => { + expect(typeof refreshHooks.manualRefresh).toBe('function') + refreshHooks.manualRefresh?.() + }) + }) + + it('refetches every data source through useMarkDataFetchers', async () => { + await expectRefetchFanOut(() => { + expect(typeof refreshHooks.markDataFetchers).toBe('function') + refreshHooks.markDataFetchers?.() + }) + }) +}) diff --git a/apps/user-ui/tests/home-page/home-slots.test.tsx b/apps/user-ui/tests/home-page/home-slots.test.tsx new file mode 100644 index 0000000..7e65b2f --- /dev/null +++ b/apps/user-ui/tests/home-page/home-slots.test.tsx @@ -0,0 +1,100 @@ +/** + * Slot card details beyond the ordering coverage in home.test.tsx: the + * CLOSING SOON badge (freeze within 4 hours) and the delivery / order-by labels. + * + * The slot fixture is rebased so the earliest delivery is 2h out; because the + * rebase is uniform, the earliest two slots freeze within 4h and the rest do + * not, giving both sides of the badge rule deterministically. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { screen, within } from '@testing-library/react-native' +import dayjs from 'dayjs' + +import { resetStorage, setupApiMocks } from '../mocks/api' +import { useNavigationStore } from '@/src/store/navigationStore' +import { renderLoadedHome, upcomingSlots } from './render' + +/** Mirrors formatTimeRange in the page / SlotCard. */ +const formatTimeRange = (deliveryTime: string) => { + const time = dayjs(deliveryTime) + const endTime = time.add(1, 'hour') + const startPeriod = time.format('A') + const endPeriod = endTime.format('A') + + if (startPeriod === endPeriod) { + return `${time.format('h')}-${endTime.format('h')} ${startPeriod}` + } + return `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}` +} + +describe('Home page slots', () => { + beforeEach(async () => { + setupApiMocks() + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + // The strip renders only the first 5 upcoming slots. + const renderedSlots = () => upcomingSlots().slice(0, 5) + + it('marks only the slots closing within 4 hours', async () => { + await renderLoadedHome() + + const slots = renderedSlots() + expect(slots.length).toBeGreaterThan(0) + + let withBadge = 0 + for (const slot of slots) { + const card = screen.getByTestId(`slot-card-${slot.id}`) + const freezeTime = dayjs(slot.freezeTime) + const closingSoon = + freezeTime.diff(dayjs(), 'hour') < 4 && freezeTime.isAfter(dayjs()) + + expect(within(card).queryByText('CLOSING SOON') !== null).toBe(closingSoon) + if (closingSoon) withBadge += 1 + } + + // Both branches are exercised by the fixture. + expect(withBadge).toBeGreaterThan(0) + expect(withBadge).toBeLessThan(slots.length) + }) + + it('labels each slot with its delivery range and order-by time', async () => { + await renderLoadedHome() + + for (const slot of renderedSlots()) { + const card = screen.getByTestId(`slot-card-${slot.id}`) + + // Delivery range and order-by clock time are each unique within the card. + expect( + within(card).getByText(formatTimeRange(slot.deliveryTime)) + ).toBeVisible() + expect( + within(card).getByText(dayjs(slot.freezeTime).format('h:mm A')) + ).toBeVisible() + + // The date line is shared by "Delivery At" and "Order By", so it appears + // twice when both fall on the same day. + expect( + within(card).getAllByText(dayjs(slot.deliveryTime).format('ddd, MMM DD')) + .length + ).toBeGreaterThan(0) + } + }) + + it('shows how many products each slot holds', async () => { + await renderLoadedHome() + + for (const slot of renderedSlots()) { + const card = screen.getByTestId(`slot-card-${slot.id}`) + expect( + within(card).getByText(`View all ${slot.products.length} items`) + ).toBeVisible() + } + }) +}) diff --git a/apps/user-ui/tests/home-page/home-states.test.tsx b/apps/user-ui/tests/home-page/home-states.test.tsx new file mode 100644 index 0000000..7adcdd4 --- /dev/null +++ b/apps/user-ui/tests/home-page/home-states.test.tsx @@ -0,0 +1,72 @@ +/** + * Home page top-level states: loading, error and the two empty states. + * + * These render branches (see app/(drawer)/(tabs)/home/index.tsx) are not hit by + * the happy-path file, so they are covered here with success/failure variants of + * the mocked network layer. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import { EMPTY_PRODUCTS, EMPTY_TAG, resetStorage, setupApiMocks } from '../mocks/api' +import { useNavigationStore } from '@/src/store/navigationStore' +import { renderHome, renderLoadedHome } from './render' + +describe('Home page states', () => { + beforeEach(async () => { + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + it('shows the loading screen while the products request is pending', async () => { + setupApiMocks({ pendingProducts: true }) + renderHome() + + await waitFor(() => { + expect(screen.getByText('Loading products...')).toBeVisible() + }) + }) + + it('shows the products error state when the products request fails', async () => { + setupApiMocks({ failProducts: true }) + renderHome() + + await waitFor(() => { + expect(screen.getByText('Failed to load products')).toBeVisible() + }) + expect(screen.getByText('Oops!')).toBeVisible() + }) + + it('shows the app-settings error state when essentialConsts fails', async () => { + setupApiMocks({ failConsts: true }) + renderHome() + + await waitFor(() => { + expect(screen.getByText('Failed to load app settings')).toBeVisible() + }) + expect(screen.getByText('Oops!')).toBeVisible() + }) + + it('shows the empty state when there are no products', async () => { + setupApiMocks({ products: EMPTY_PRODUCTS }) + renderHome() + + await waitFor(() => { + expect(screen.getByText('No products available')).toBeVisible() + }) + }) + + it('shows the empty-category message for a tag with no products', async () => { + setupApiMocks({ extraTags: [EMPTY_TAG] }) + await renderLoadedHome() + + fireEvent.press(screen.getByTestId(`tag-tab-${EMPTY_TAG.id}`)) + + expect(screen.getByText('No products in this category yet')).toBeVisible() + }) +}) diff --git a/apps/user-ui/tests/home-page/home.test.tsx b/apps/user-ui/tests/home-page/home.test.tsx new file mode 100644 index 0000000..ac7e9c6 --- /dev/null +++ b/apps/user-ui/tests/home-page/home.test.tsx @@ -0,0 +1,611 @@ +/** + * 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( + + + + + + + + + + ) +} + +/** 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 + + 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') + }) +}) diff --git a/apps/user-ui/tests/home-page/navigation.test.tsx b/apps/user-ui/tests/home-page/navigation.test.tsx new file mode 100644 index 0000000..3f72c2d --- /dev/null +++ b/apps/user-ui/tests/home-page/navigation.test.tsx @@ -0,0 +1,139 @@ +/** + * Navigation tests for the home page using the REAL expo-router. + * + * Unlike tests/home.test.tsx (which mocks the router and asserts the intended + * push target), this file renders the actual router with a route map mirroring + * the app's group structure. That proves the pushed URLs resolve to a route and + * that params arrive. + * + * Route keys mirror app/ (see the directory listing); renderRouter strips the + * group segments, so '(drawer)/(tabs)/home/index' is reachable at '/home'. + * + * expo-router is deliberately not mocked in tests/setup.ts - that is what makes + * this file possible. + */ + +import React from 'react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { fireEvent, within } from '@testing-library/react-native' +import { renderRouter, screen } from 'expo-router/testing-library' +import { useLocalSearchParams } from 'expo-router' +import { MyText, RefreshProvider } from 'common-ui' + +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 { mockSlots, outOfStockIds, resetStorage, setupApiMocks } from '../mocks/api' +import productsResponse from '../mocks/mock-products-response.json' +import storesResponse from '../mocks/mock-stores-response.json' + +const products = productsResponse.products.filter((p) => !p.isComboOnly) + +function Providers({ children }: { children?: React.ReactNode }) { + const queryClient = React.useMemo( + () => + new QueryClient({ + defaultOptions: { queries: { retry: false, gcTime: 0 } }, + }), + [] + ) + + return ( + + + + {children} + + + + ) +} + +const HomeRoute = () => ( + + + +) + +const DetailStub = () => { + const { id } = useLocalSearchParams<{ id: string }>() + return {String(id)} +} + +const SlotViewStub = () => { + const { slotId } = useLocalSearchParams<{ slotId: string }>() + return {String(slotId)} +} + +const StoresStub = () => stores +const SearchStub = () => search +const CartStub = () => cart + +const ROUTES = { + '(drawer)/(tabs)/home/index': HomeRoute, + '(drawer)/(tabs)/home/product-detail/[id]': DetailStub, + '(drawer)/(tabs)/home/slot-view/index': SlotViewStub, + '(drawer)/(tabs)/home/search-results/index': SearchStub, + '(drawer)/(tabs)/home/cart': CartStub, + '(drawer)/(tabs)/stores/index': StoresStub, +} + +async function renderHomeRoute() { + const result = renderRouter(ROUTES, { initialUrl: '/home' }) + + await screen.findByTestId(`tag-tab-${productsResponse.tags[0].id}`) + + return result +} + +describe('Home navigation (real router)', () => { + beforeEach(async () => { + setupApiMocks() + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + it('routes to the product detail screen carrying the id', async () => { + const nav = await renderHomeRoute() + + // Must be in stock: unavailable products sort last and are not mounted. + const productId = products.find((p) => !outOfStockIds.has(p.id))!.id + const card = await screen.findByTestId(`product-item-${productId}`) + + fireEvent.press(within(card).getByTestId('product-card')) + + expect(nav.getPathname()).toBe(`/home/product-detail/${productId}`) + expect(screen.getByTestId('product-detail-screen')).toHaveTextContent( + String(productId) + ) + }) + + it('routes to the slot view carrying the slotId', async () => { + const nav = await renderHomeRoute() + + const slot = mockSlots.slots.find( + (s) => new Date(s.freezeTime).getTime() > Date.now() + )! + + fireEvent.press(screen.getByTestId(`slot-card-${slot.id}`)) + + expect(nav.getPathname()).toBe('/home/slot-view') + expect(nav.getSearchParams()).toMatchObject({ slotId: String(slot.id) }) + expect(screen.getByTestId('slot-view-screen')).toHaveTextContent( + String(slot.id) + ) + }) + + it('routes to the stores screen', async () => { + const nav = await renderHomeRoute() + + fireEvent.press(screen.getByTestId(`store-item-${storesResponse.stores[0].id}`)) + + expect(nav.getPathname()).toBe('/stores') + expect(screen.getByTestId('stores-screen')).toBeVisible() + }) +}) diff --git a/apps/user-ui/tests/home-page/next-order-glimpse.test.tsx b/apps/user-ui/tests/home-page/next-order-glimpse.test.tsx new file mode 100644 index 0000000..45df0aa --- /dev/null +++ b/apps/user-ui/tests/home-page/next-order-glimpse.test.tsx @@ -0,0 +1,134 @@ +/** + * NextOrderGlimpse — the "Upcoming Order" preview rendered by the home page. + * + * It returns null unless useUserDetails() is set, so these tests use the + * overridable auth mock (tests/mocks/auth.ts) plus a mocked user.order.getOrders + * response (tRPC over fetch, handled in tests/mocks/api.ts). + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { routerMock } from '../mocks/router' +import { useNavigationStore } from '@/src/store/navigationStore' +import { renderLoadedHome, tags } from './render' + +const countRequests = ( + mock: { mock: { calls: unknown[][] } }, + needle: string +) => mock.mock.calls.filter(([url]) => String(url).includes(needle)).length + +const baseOrder = (over: Record = {}) => ({ + id: 1, + orderId: 'ORD-1001', + orderDate: '2026-09-25T10:00:00.000Z', + deliveryStatus: 'pending', + orderStatus: 'confirmed', + deliveryDate: '2026-09-26T10:00:00.000Z', + cancelReason: null, + paymentMode: 'cod', + totalAmount: 500, + deliveryCharge: 0, + paymentStatus: 'pending', + refundStatus: 'none', + refundAmount: null, + userNotes: null, + isFlashDelivery: false, + createdAt: '2026-09-25T10:00:00.000Z', + items: [ + { + productName: 'Chicken Breast 500 g', + quantity: 1, + unitNotation: '500g', + price: 200, + discountedPrice: 200, + amount: 200, + image: null, + }, + { + productName: 'Chicken Liver', + quantity: 1, + unitNotation: '1kg', + price: 300, + discountedPrice: 300, + amount: 300, + image: null, + }, + ], + ...over, +}) + +describe('NextOrderGlimpse', () => { + beforeEach(async () => { + resetAuthMock() + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + afterEach(() => resetAuthMock()) + + it('renders nothing and never requests orders when signed out', async () => { + const api = setupApiMocks({ orders: [baseOrder()] }) + await renderLoadedHome() + + expect(screen.queryByText('Upcoming Order')).toBeNull() + expect(countRequests(api.fetchMock, 'user.order.getOrders')).toBe(0) + }) + + it('previews an upcoming order', async () => { + authMock.userDetails = { id: 1, name: 'Test User' } + setupApiMocks({ orders: [baseOrder()] }) + await renderLoadedHome() + + await waitFor(() => expect(screen.getByText('Upcoming Order')).toBeVisible()) + + expect(screen.getByText('#ORD-1001')).toBeVisible() + expect(screen.getByText('2 items • ₹500')).toBeVisible() + // deliveryStatus 'pending' is shown user-facing as "Confirmed". + expect(screen.getByText('Confirmed')).toBeVisible() + }) + + it('flags a flash order', async () => { + authMock.userDetails = { id: 1 } + setupApiMocks({ orders: [baseOrder({ isFlashDelivery: true })] }) + await renderLoadedHome() + + await waitFor(() => expect(screen.getByText('FLASH')).toBeVisible()) + expect(screen.getByText('30-Min Delivery')).toBeVisible() + }) + + it('ignores cancelled and completed orders', async () => { + authMock.userDetails = { id: 1 } + const api = setupApiMocks({ + orders: [ + baseOrder({ orderStatus: 'cancelled' }), + baseOrder({ id: 2, orderId: 'ORD-1002', deliveryStatus: 'success' }), + ], + }) + await renderLoadedHome() + + // Let the orders query resolve before asserting the empty result. + await waitFor(() => + expect(countRequests(api.fetchMock, 'user.order.getOrders')).toBeGreaterThan(0) + ) + expect(screen.getByTestId(`tag-tab-${tags[0].id}`)).toBeVisible() + expect(screen.queryByText('Upcoming Order')).toBeNull() + }) + + it('routes to my-orders when a card is tapped', async () => { + authMock.userDetails = { id: 1 } + setupApiMocks({ orders: [baseOrder()] }) + await renderLoadedHome() + + await waitFor(() => expect(screen.getByText('#ORD-1001')).toBeVisible()) + fireEvent.press(screen.getByText('#ORD-1001')) + + expect(routerMock.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/me') + }) +}) diff --git a/apps/user-ui/tests/home-page/render.tsx b/apps/user-ui/tests/home-page/render.tsx new file mode 100644 index 0000000..7cfec8a --- /dev/null +++ b/apps/user-ui/tests/home-page/render.tsx @@ -0,0 +1,141 @@ +/** + * Shared render helpers + expectations for the mocked-router home-page tests. + * + * Unlike tests/home-page/navigation.test.tsx (which drives the real router), + * every file that imports this must also declare the mocked router itself: + * + * jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + * + * The provider stack mirrors app/_layout.tsx: CentralStoreInitializer populates + * the slot/availability/product stores the same way the app does, so + * productSlotsMap is non-empty and the out-of-stock / add-to-cart paths work. + */ + +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' + +import Dashboard from '@/app/(drawer)/(tabs)/home/index' +import CentralStoreInitializer from '@/src/components/CentralStoreInitializer' +import { trpc, trpcClient } from '@/src/trpc-client' +import availability from '../mocks/mock-availability-response.json' +import productsResponse from '../mocks/mock-products-response.json' +import { mockSlots } from '../mocks/api' + +/** Products the page can show: useAllProducts drops combo-only SKUs. */ +export const products = productsResponse.products.filter((p) => !p.isComboOnly) +export const tags = productsResponse.tags +export const knownProductIds = new Set(products.map((p) => p.id)) + +/** price/isFlashAvailable as the app sees them (from the availability cache). */ +export const priceById = new Map( + availability.availability.map((a) => [a.id, Number(a.price)]) +) +export const flashAvailableById = new Map( + availability.availability.map((a) => [a.id, a.isFlashAvailable]) +) +export const marketPriceById = new Map( + availability.availability.map((a) => [ + a.id, + a.marketPrice == null ? null : Number(a.marketPrice), + ]) +) + +/** Mirrors the backend: a slot is offerable only while both times are future. */ +export const isUpcomingSlot = (slot: { + deliveryTime: string + freezeTime: string +}) => + dayjs(slot.deliveryTime).isAfter(dayjs()) && + dayjs(slot.freezeTime).isAfter(dayjs()) + +/** Upcoming slots in the order the home page renders them (delivery asc). */ +export const upcomingSlots = () => + 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)) + }) + +/** Products a tag points at that exist in the (combo-filtered) cache. */ +export const productIdsForTag = (tag: { productIds: number[] }) => + tag.productIds.filter((id) => knownProductIds.has(id)) + +export function Providers({ children }: { children?: React.ReactNode }) { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, gcTime: 0 } }, + }) + + return ( + + + + {children} + + + + ) +} + +export function renderHome() { + return render( + + + + ) +} + +/** Renders and waits for the first tag tab and the slot strip to be live. */ +export async function renderLoadedHome() { + const result = renderHome() + await waitFor(() => { + expect(screen.getByTestId(`tag-tab-${tags[0].id}`)).toBeTruthy() + }) + await waitFor(() => { + expect(screen.getAllByTestId(/^slot-card-/).length).toBeGreaterThan(0) + }) + return result +} + +/** Selects a tag and expands its grid past the 6-item preview. */ +export 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. + * The dialog only offers slots for the product whose freezeTime is still ahead. + */ +export 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')) +} diff --git a/apps/user-ui/tests/home.test.tsx b/apps/user-ui/tests/home.test.tsx deleted file mode 100644 index 0374b54..0000000 --- a/apps/user-ui/tests/home.test.tsx +++ /dev/null @@ -1,125 +0,0 @@ -/** - * 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 - * - * 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 Dashboard from '@/app/(drawer)/(tabs)/home/index' -import { trpc, trpcClient } from '@/src/trpc-client' -import productsResponse from './mocks/mock-products-response.json' -import { PRODUCTS_URL, 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 - -const knownProductIds = new Set(productsResponse.products.map((p) => p.id)) -const tags = productsResponse.tags - -/** Products a tag points at that actually exist in the products cache. */ -const productIdsForTag = (tag: (typeof tags)[number]) => - tag.productIds.filter((id) => knownProductIds.has(id)) - -function renderHome() { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false, gcTime: 0 } }, - }) - - return render( - - - - - - - - ) -} - -describe('Home page', () => { - let api: ReturnType - - beforeEach(() => { - api = setupApiMocks() - }) - - 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 () => { - renderHome() - - await waitFor(() => { - expect(screen.getByTestId(`tag-tab-${tags[0].id}`)).toBeTruthy() - }) - - 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 () => { - renderHome() - - await waitFor(() => { - expect(screen.getByTestId(`tag-grid-${tags[0].id}`)).toBeTruthy() - }) - - for (const tag of tags) { - fireEvent.press(screen.getByTestId(`tag-tab-${tag.id}`)) - - const expected = productIdsForTag(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.todo('shows every product returned by the products cache') - it.todo('shows the store list') - it.todo('shows the upcoming delivery slots') -}) diff --git a/apps/user-ui/tests/mocks/api.ts b/apps/user-ui/tests/mocks/api.ts index 51223e9..f9aedab 100644 --- a/apps/user-ui/tests/mocks/api.ts +++ b/apps/user-ui/tests/mocks/api.ts @@ -2,7 +2,7 @@ * Network-layer mocks for the user-ui tests. * * Everything the home page fetches goes through one of two doors: - * - tRPC -> global.fetch (common.essentialConsts, ...) + * - tRPC -> global.fetch (common.essentialConsts, user.order.getOrders, ...) * - axios -> the assets CDN (products.json, stores.json, slots.json, availability.json) * * Both are stubbed here and both fail loudly on an unmocked URL, so a new @@ -18,16 +18,144 @@ * builtin pulls @types/node into the typecheck program, which flips * `setTimeout` from `number` to `NodeJS.Timeout` and breaks unrelated app types. * - * NOTE: mock-slots-response.json is a snapshot of a real day (see the - * deliveryTime values). The home page drops past slots, so those fixtures need - * refreshing once their dates fall behind. + * NOTE: mock-slots-response.json is a snapshot of one real day, so its dates are + * rebased relative to the frozen clock below rather than used as-is. */ import essentialConsts from '../__fixtures__/essentialConsts.json' import availability from './mock-availability-response.json' import products from './mock-products-response.json' -import slots from './mock-slots-response.json' +import slotsRaw from './mock-slots-response.json' import stores from './mock-stores-response.json' +import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' + +/** The payload the common.essentialConsts procedure resolves to (unwrapped). */ +export const ESSENTIAL_CONSTS_DATA = essentialConsts[0].result.data + +/** essentialConsts with flash delivery switched on (flash-option tests). */ +export const FLASH_ENABLED_CONSTS = { + ...ESSENTIAL_CONSTS_DATA, + isFlashDeliveryEnabled: true, +} + +/** products.json with no tags and no products (empty-state tests). */ +export const EMPTY_PRODUCTS = { products: [], tags: [] } + +/** A dashboard tag that points at no products (empty-tag-grid test). */ +export const EMPTY_TAG = { + id: 9999, + tagName: 'Empty', + tagDescription: null, + imageUrl: null, + isDashboardTag: true, + productIds: [], +} + +/** + * The mocked StorageServiceCasual keeps its map at module scope, so the cart + * survives from one test to the next. Call from beforeEach. + * + * `essential_consts` is deliberately NOT cleared here: when it is persisted, + * useGetEssentialConsts gets placeholderData synchronously, which + * tests/home-page/navigation.test.tsx (real router) relies on. A file that + * overrides the constants must clear it itself via resetEssentialConsts(). + */ +export async function resetStorage() { + await StorageServiceCasual.clearAll(['cart_items', 'flash_cart_items']) +} + +/** Clears the persisted essentialConsts so the next render refetches them. */ +export async function resetEssentialConsts() { + await StorageServiceCasual.clearAll(['essential_consts']) +} + +/** + * The slot fixture is a snapshot of a real day. The home page drops slots whose + * deliveryTime is not after `dayjs()`, so the fixture would silently expire. + * Shift every slot by the same delta so the earliest lands FIRST_SLOT_LEAD_MS + * ahead of now, keeping the relative spacing and the freeze-before-delivery + * offset intact. Ids and per-slot product lists are untouched. + */ +const FIRST_SLOT_LEAD_MS = 2 * 60 * 60 * 1000 + +/** How far in the past the synthetic expired slots freeze. */ +const EXPIRED_FREEZE_MS = 2 * 60 * 1000 +export const EXPIRED_HOME_SLOT_ID = 9001 +export const EXPIRED_DIALOG_SLOT_ID = 9002 + +const rebaseSlots = (raw: typeof slotsRaw) => { + const offset = + Date.now() + + FIRST_SLOT_LEAD_MS - + new Date(raw.slots[0].deliveryTime).getTime() + + return { + ...raw, + slots: raw.slots.map((slot) => ({ + ...slot, + deliveryTime: new Date( + new Date(slot.deliveryTime).getTime() + offset + ).toISOString(), + freezeTime: new Date( + new Date(slot.freezeTime).getTime() + offset + ).toISOString(), + })), + } +} + +/** Slots as the app will receive them (rebased), for building expectations. */ +export const mockSlots = (() => { const rebased = rebaseSlots(slotsRaw) + const now = Date.now() + + // Slots whose freezeTime has passed but whose delivery is still upcoming. + // The backend filters these out (scaffoldSlotsWithProducts) and the cart + // dialog filters them out too; these exist so the home strip can be shown to + // do the same. Delivery times are picked deliberately: + // 9001 earliest -> an unfiltered slot would sort first and fail loudly + // instead of hiding beyond the 5-item slice + // 9002 latest -> getQuickestSlot (which ignores freezeTime) still + // resolves product 23 to its real, earlier slot + const expiredSlot = (id: number, deliveryLeadMs: number, productIds: number[]) => ({ + id, + deliveryTime: new Date(now + deliveryLeadMs).toISOString(), + freezeTime: new Date(now - EXPIRED_FREEZE_MS).toISOString(), + products: productIds.map((productId) => ({ + id: productId, + images: [] as string[], + })), + }) + + return { + ...rebased, + slots: [ + ...rebased.slots, + expiredSlot(EXPIRED_HOME_SLOT_ID, 60 * 60 * 1000, []), + expiredSlot(EXPIRED_DIALOG_SLOT_ID, 20 * 60 * 60 * 1000, [23]), + ], + } +})() + +const productsInAnySlot = new Set() +mockSlots.slots.forEach((slot) => + slot.products.forEach((p) => productsInAnySlot.add(p.id)) +) + +const flaggedOutOfStock = new Set( + availability.availability.filter((a) => a.isOutOfStock).map((a) => a.id) +) + +/** + * The products the UI should treat as unavailable: flagged out of stock by the + * availability cache, or present in no upcoming slot. Mirrors + * displayIsOutOfStock / productsByTagId in the page. Combo-only SKUs are + * dropped because useAllProducts filters them out. + */ +export const outOfStockIds = new Set( + products.products + .filter((p) => !p.isComboOnly) + .map((p) => p.id) + .filter((id) => flaggedOutOfStock.has(id) || !productsInAnySlot.has(id)) +) export const ESSENTIAL_CONSTS_URL = 'https://worker.freshyo.in/api/trpc/common.essentialConsts?batch=1&input=%7B%220%22%3A%7B%22json%22%3Anull%2C%22meta%22%3A%7B%22values%22%3A%5B%22undefined%22%5D%7D%7D%7D' @@ -42,15 +170,6 @@ export const AVAILABILITY_URL = export const STORES_URL = 'https://assets.freshyo.in/api-cache/v-755/stores.json' export const SLOTS_URL = 'https://assets.freshyo.in/slots/v-401/slots.json?v=123' -/** Route a CDN file name to its mock response. */ -const mockForCacheFile = (url: string): unknown => { - if (url.includes('products.json')) return products - if (url.includes('stores.json')) return stores - if (url.includes('slots.json')) return slots - if (url.includes('availability.json')) return availability - throw new Error(`[tests] unmocked assets request: ${url}`) -} - const jsonResponse = (body: unknown) => ({ ok: true, status: 200, @@ -61,27 +180,103 @@ const jsonResponse = (body: unknown) => ({ text: async () => JSON.stringify(body), }) +const errorResponse = (status: number, message: string) => ({ + ok: false, + status, + statusText: message, + headers: new Map(), + url: '', + json: async () => ({ message }), + text: async () => message, +}) + +export interface ApiMockOptions { + /** Replace the products.json body entirely (e.g. EMPTY_PRODUCTS). */ + products?: unknown + /** Append tags to the products.json body's `tags` (empty-tag-grid test). */ + extraTags?: unknown[] + /** Override the essentialConsts payload (unwrapped procedure data). */ + consts?: unknown + /** user.order.getOrders data (NextOrderGlimpse). */ + orders?: unknown[] + /** axios.get(products.json) rejects -> the products query errors. */ + failProducts?: boolean + /** The essentialConsts fetch resolves non-ok -> the consts query errors. */ + failConsts?: boolean + /** axios.get(products.json) never resolves -> the products query stays loading. */ + pendingProducts?: boolean +} + /** * Install the fetch + axios stubs and return the handles for assertions. * Call from beforeEach so each test starts from a clean call history. */ -export function setupApiMocks() { +export function setupApiMocks(opts: ApiMockOptions = {}) { const axios = require('axios') - axios.get.mockImplementation(async (url: string) => ({ - data: mockForCacheFile(url), - status: 200, - statusText: 'OK', - headers: {}, - config: {}, - })) + const constsData = opts.consts ?? ESSENTIAL_CONSTS_DATA + const orders = opts.orders ?? [] - const fetchMock = jest.fn(async (url: string) => { - if (url.includes('common.essentialConsts')) { - return jsonResponse(essentialConsts) + const baseProducts = (opts.products ?? products) as { tags?: unknown[] } + const productsBody = opts.extraTags?.length + ? { ...baseProducts, tags: [...(baseProducts.tags ?? []), ...opts.extraTags] } + : baseProducts + + /** Route a CDN file name to its mock response. */ + const mockForCacheFile = (url: string): unknown => { + if (url.includes('products.json')) return productsBody + if (url.includes('stores.json')) return stores + if (url.includes('slots.json')) return mockSlots + if (url.includes('availability.json')) return availability + throw new Error(`[tests] unmocked assets request: ${url}`) + } + + axios.get.mockImplementation(async (url: string) => { + const target = String(url) + + if (target.includes('products.json')) { + if (opts.pendingProducts) return new Promise(() => {}) + if (opts.failProducts) throw new Error('products request failed') } - throw new Error(`[tests] unmocked fetch: ${url}`) + return { + data: mockForCacheFile(target), + status: 200, + statusText: 'OK', + headers: {}, + config: {}, + } + }) + + /** Resolve one procedure name from a (possibly batched) tRPC request. */ + const resolveProcedure = (name: string): unknown => { + if (name === 'common.essentialConsts') return constsData + if (name === 'user.order.getOrders') return { data: orders } + throw new Error(`[tests] unmocked trpc procedure: ${name}`) + } + + const fetchMock = jest.fn(async (url: string) => { + const target = String(url) + + if (opts.failConsts && target.includes('common.essentialConsts')) { + return errorResponse(500, 'consts request failed') + } + + // The path after /api/trpc/ is a comma-separated list of procedure names + // (httpBatchLink batches every query issued in the same tick). + const marker = '/api/trpc/' + const at = target.indexOf(marker) + if (at === -1) throw new Error(`[tests] unmocked fetch: ${url}`) + + const names = target + .slice(at + marker.length) + .split('?')[0] + .split(',') + .filter(Boolean) + if (names.length === 0) throw new Error(`[tests] unmocked fetch: ${url}`) + + const batch = names.map((name) => ({ result: { data: resolveProcedure(name) } })) + return jsonResponse(batch) }) ;(global as unknown as { fetch: unknown }).fetch = fetchMock diff --git a/apps/user-ui/tests/mocks/auth.ts b/apps/user-ui/tests/mocks/auth.ts new file mode 100644 index 0000000..997b20f --- /dev/null +++ b/apps/user-ui/tests/mocks/auth.ts @@ -0,0 +1,42 @@ +/** + * Overridable AuthContext mock. + * + * tests/setup.ts stubs @/src/contexts/AuthContext with this factory so a test + * can flip the signed-in shape. Auth is otherwise out of scope for these tests: + * the real provider would drag in secure-store, the tRPC login flow and redirect + * handling. + * + * Set `authMock.userDetails` in a beforeEach and reset it with resetAuthMock(). + * NextOrderGlimpse (rendered by the home page) returns null unless it is set. + */ + +import type { ReactNode } from 'react' + +export interface AuthMockState { + user: unknown + userDetails: unknown +} + +export const authMock: AuthMockState = { + user: null, + userDetails: null, +} + +export function resetAuthMock() { + authMock.user = null + authMock.userDetails = null +} + +export function authContextMock() { + return { + AuthProvider: ({ children }: { children?: ReactNode }) => children ?? null, + useAuth: () => ({ + user: authMock.user, + userDetails: authMock.userDetails, + isAuthenticated: !!authMock.user, + isLoading: false, + token: null, + }), + useUserDetails: () => authMock.userDetails, + } +} diff --git a/apps/user-ui/tests/mocks/refresh.ts b/apps/user-ui/tests/mocks/refresh.ts new file mode 100644 index 0000000..0580a06 --- /dev/null +++ b/apps/user-ui/tests/mocks/refresh.ts @@ -0,0 +1,27 @@ +/** + * Capture for the refresh hooks. + * + * tests/setup.ts mocks common-ui/hooks/useManualRefresh and useMarkDataFetchers. + * Their real implementations need a navigation container and are irrelevant to + * most assertions, but the home page funnels its pull-to-refresh through them. + * The mocks record the latest callback here so a test can invoke the page's + * handleRefresh directly. + * + * The callbacks are re-registered on every render, so read them only after the + * page has mounted. + */ + +export interface RefreshHooks { + manualRefresh: (() => void) | null + markDataFetchers: (() => void) | null +} + +export const refreshHooks: RefreshHooks = { + manualRefresh: null, + markDataFetchers: null, +} + +export function resetRefreshHooks() { + refreshHooks.manualRefresh = null + refreshHooks.markDataFetchers = null +} diff --git a/apps/user-ui/tests/mocks/router.ts b/apps/user-ui/tests/mocks/router.ts new file mode 100644 index 0000000..83b627a --- /dev/null +++ b/apps/user-ui/tests/mocks/router.ts @@ -0,0 +1,39 @@ +/** + * Shared spies for the mocked expo-router. + * + * The mock lives in each test file rather than in tests/setup.ts: a global mock + * would also apply to tests/home-page/navigation.test.tsx, which needs the real + * router (expo-router/testing-library). Any test file that renders a router + * consumer and is not using the real router must add: + * + * jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + * + * `clearMocks: true` in jest.config.js clears these between tests, but zustand + * stores are not mocks - reset them explicitly where they matter. + */ + +export const routerMock = { + push: jest.fn(), + replace: jest.fn(), + back: jest.fn(), + navigate: jest.fn(), +} + +export function resetRouterMock() { + routerMock.push.mockClear() + routerMock.replace.mockClear() + routerMock.back.mockClear() + routerMock.navigate.mockClear() +} + +/** Factory for jest.mock('expo-router', ...). */ +export function expoRouterMock() { + return { + useRouter: () => routerMock, + router: routerMock, + useLocalSearchParams: () => ({}), + useGlobalSearchParams: () => ({}), + useFocusEffect: () => {}, + Link: ({ children }: { children?: unknown }) => children ?? null, + } +} diff --git a/apps/user-ui/tests/setup.ts b/apps/user-ui/tests/setup.ts index 7dc0d67..ceb3f93 100644 --- a/apps/user-ui/tests/setup.ts +++ b/apps/user-ui/tests/setup.ts @@ -12,42 +12,36 @@ * bottom-dropdown.tsx). */ -import type { ReactNode } from 'react' - -jest.mock('expo-router', () => ({ - useRouter: () => ({ - push: jest.fn(), - replace: jest.fn(), - back: jest.fn(), - navigate: jest.fn(), - }), - router: { - push: jest.fn(), - replace: jest.fn(), - back: jest.fn(), - }, - useLocalSearchParams: () => ({}), - useGlobalSearchParams: () => ({}), - useFocusEffect: () => {}, - Link: ({ children }: { children?: ReactNode }) => children ?? null, -})) +/** + * Note: `expo-router` is NOT mocked here. A global mock would also apply to + * tests/home-page/navigation.test.tsx, which drives the real router. Test files + * that need the mocked router add it themselves (see tests/mocks/router.ts). + */ /** - * Refresh plumbing, irrelevant to what these tests assert. + * Refresh plumbing, irrelevant to most assertions. * `useMarkDataFetchers` runs `useFocusEffect`, which throws without a * NavigationContainer. These are mocked by their own module paths rather than * partially mocking the `common-ui` index: several index components import * back from `common-ui` (button.tsx -> common-ui), so spreading * `jest.requireActual('common-ui')` walks a half-initialised module and throws. + * + * Rather than no-op'ing them, the mocks record the callback so + * tests/home-page/home-refresh.test.tsx can invoke the page's handleRefresh + * (see tests/mocks/refresh.ts). */ jest.mock('common-ui/hooks/useMarkDataFetchers', () => ({ __esModule: true, - useMarkDataFetchers: () => {}, + useMarkDataFetchers: (cb: () => void) => { + require('./mocks/refresh').refreshHooks.markDataFetchers = cb + }, })) jest.mock('common-ui/hooks/useManualRefresh', () => ({ __esModule: true, - default: () => {}, + default: (cb: () => void) => { + require('./mocks/refresh').refreshHooks.manualRefresh = cb + }, })) // Registered here (not in the test files) so it is in place before any app @@ -57,19 +51,12 @@ jest.mock('axios') /** * Auth is out of scope for these tests. `useUserDetails` throws without an * AuthProvider (which would drag in secure-store, tRPC login and redirect - * handling), so the context is stubbed with the signed-out shape. + * handling), so the context is stubbed with a signed-out shape. Overridable via + * tests/mocks/auth.ts (set authMock.userDetails) for signed-in cases. */ -jest.mock('@/src/contexts/AuthContext', () => ({ - AuthProvider: ({ children }: { children?: ReactNode }) => children ?? null, - useAuth: () => ({ - user: null, - userDetails: null, - isAuthenticated: false, - isLoading: false, - token: null, - }), - useUserDetails: () => null, -})) +jest.mock('@/src/contexts/AuthContext', () => + require('./mocks/auth').authContextMock() +) /** * Cart hooks import this deep path directly (not via the common-ui index), and diff --git a/change-log.txt b/change-log.txt index 054b74e..e585aef 100644 --- a/change-log.txt +++ b/change-log.txt @@ -2675,3 +2675,318 @@ resolved through the products cache (tag.productIds -> products), matching what productsByTagId builds at runtime. (Ordering note: the spec edit landed before this log entry.) + +[2026-09-17 23:20:00] user-ui: testIDs for product list paging and out-of-stock badge. + +Additive only. + +- app/(drawer)/(tabs)/home/index.tsx + main-list footer button testID="products-show-more" + ProductItem testID={`product-item-${item.id}`} +- packages/ui/src/components/ProductCard.tsx + out-of-stock overlay testID="out-of-stock-badge" + +Needed because the page renders two "Show More" buttons (tag grid + list footer) +and the out-of-stock state was only identifiable by its "Out of Stock" string. + +[2026-09-17 23:24:00] correction: ProductCard lives in apps/user-ui/components/. + +The previous entry named packages/ui/src/components/ProductCard.tsx; the file +with the out-of-stock overlay is apps/user-ui/components/ProductCard.tsx. Only +the path in the note was wrong, the testID was added to the right file. + +[2026-09-17 23:25:00] user-ui: rebase the slot mock dates at runtime. + +mock-slots-response.json is a snapshot of 2026-09-18. The home page drops slots +whose deliveryTime is not after dayjs(), so the slot section (and any slot +assertion) silently empties once that date passes. tests/mocks/api.ts now shifts +every slot by a fixed delta so the earliest sits two hours ahead of the frozen +clock, preserving the relative spacing and the 10-minute freeze offset. Ids and +per-slot product lists are untouched, so order assertions stay stable. + +[2026-09-17 23:35:00] user-ui: comprehensive home tests (slots, paging, stock, cart). + +tests/home.test.tsx now wraps the page in CentralStoreInitializer so the +slot/availability/product stores are real, and covers: + +- slots in delivery order: rendered slot-card-* must equal exactly the first 5 + upcoming slots (ids 1849,1847,1848,1850,1851); the 3 beyond the slice absent +- load-all: products-show-more visible, pressed until it disappears, with the + exact press count (ceil((148-21)/21) = 7) +- every product of every tag, asserting the 6-item preview then expansion +- out-of-stock across all 8 tags: for each of the 146 tag products the + out-of-stock-badge is present iff the product is in the computed set + (availability flag OR no upcoming slot) = 44 products +- add to cart: two products via tag grid -> dialog slot -> confirm, asserting + the floating bar goes "No Items In Cart" -> "1 Item" -> "2 Items" and the + card swaps the add icon for the quantity stepper + +Two things worth recording: + +1. useAllProducts drops combo-only SKUs, so expectations are built over 148 of + the 149 mock products (id 149 is combo-only) and 44 are out of stock. +2. A main-list out-of-stock test was written, then removed: it passed even with + the badge disabled, because unavailable items sort last and FlatList + virtualizes (~10 rows mount), so those rows never render. It was vacuous. + The tag grids carry that verification instead. Expectation order for a tag + must also follow productsByTagId (in-stock first), not the raw tag order. + +Verified: 7 passed / 1 todo, tsc clean. Out-of-stock coverage was mutation +checked (disabling the badge makes the tag test fail). + +[2026-09-17 23:44:00] user-ui: test that a tag's out-of-stock items render last. + +Adds a home page case asserting the tag grid order matches productsByTagId: +every in-stock item precedes every out-of-stock item, and the admin-curated +order is preserved within each group (in-stock group and out-of-stock group are +each compared against the tag's declared productIds). Tracks how many tags +actually contain both groups so the ordering property is not asserted vacuously. + +[2026-09-17 23:46:00] user-ui: mutation-checked the out-of-stock-last ordering test. + +Temporarily changed productsByTagId to keep the raw tag order instead of +[inStock, outOfStock]; the new case failed as intended, then the change was +reverted. Suite: 8 passed / 1 todo, tsc clean. + +[2026-09-17 23:55:00] user-ui: home slot strip now honours freezeTime. + +BEHAVIOR CHANGE. sortedSlots filtered only on deliveryTime, so a slot whose +freezeTime had passed but whose delivery was still upcoming rendered normally +(no CLOSING SOON badge, since that requires freezeTime in the future). The +backend already excludes such slots in scaffoldSlotsWithProducts and the cart +dialog already filters on freezeTime, so the home strip was the odd one out and +relied entirely on the backend. Now filters on both: + + app/(drawer)/(tabs)/home/index.tsx + .filter(slot => dayjs(slot.deliveryTime).isAfter(now) + && dayjs(slot.freezeTime).isAfter(now)) + +[2026-09-17 23:56:00] user-ui: synthetic expired slots in tests/mocks/api.ts. + +Adds two slots to the payload so the freezeTime rules can be tested without +ever storing absolute dates: + +- id 9001, freezeTime now-2min, deliveryTime now+1h, products [] (home) +- id 9002, freezeTime now-2min, deliveryTime now+20h, products [23] (dialog) + +9001 is the earliest delivery on purpose: without the freeze filter it would +sort first and break the order assertions rather than hide behind the 5-item +slice. 9002 is the latest so getQuickestSlot (which ignores freezeTime) still +resolves product 23 to its real earlier slot, keeping productSlotsMap and the +out-of-stock expectations untouched. + +[2026-09-17 23:58:00] user-ui: reset the in-memory cart between tests. + +The mocked StorageServiceCasual keeps its Map at module scope, so the cart +persists across tests in a file. The new expired-slot dialog test adds an item, +which then leaked into the "adds items to the cart" test and broke its initial +"No Items In Cart" assertion. Adds resetStorage() to tests/mocks/api.ts and +calls it from beforeEach. + +[2026-09-18 00:02:00] user-ui: mutation-checked the two expired-slot tests. + +Reverting the sortedSlots freeze filter made the home case fail; forcing the +dialog's availableSlots filter to a no-op made the dialog case fail. Both were +restored afterwards. Suite: 10 passed / 1 todo, tsc clean. + +[2026-09-18 00:15:00] user-ui: test that the main product list puts unavailable items last. + +Adds a home page case asserting the mounted product-item-* rows are the head of +the expected order (in-stock in cache order, then out-of-stock). FlatList only +mounts ~10 rows, so the mounted ids are compared against the prefix of the +expected order rather than the whole list. Non-vacuity guards: the catalog does +contain unavailable products, and the first product in cache order is itself +unavailable, so a missing sort would surface immediately as the first row. + +[2026-09-18 00:40:00] user-ui: finding - ProductCard's inline quantity stepper is unreachable. + +Every ProductCard usage in the app passes useAddToCartDialog={true} (home x2, +search-results, order-again, store-detail). handleQuantityChange short-circuits +on that flag (ProductCard.tsx:135) and only calls setAddedToCartProduct, so the +MiniQuantifier's +/- opens the Add-to-Cart dialog instead of updating the cart, +and the new quantity is discarded. The direct branches - removeFromCart at 0 and +updateCartItem - are therefore dead code in production. Consequence: "increment +updates the cart, decrement removes at 0" does not happen on any screen today. + +[2026-09-18 00:41:00] user-ui: mutation-checked the main-list ordering test. + +Neutralising the out-of-stock comparator (returning 0 for both branches) made +the new case fail, then it was restored. Suite: 11 passed / 1 todo, tsc clean. + +[2026-09-18 00:50:00] testIDs for the quantity steppers and dialog remove button. + +Additive only, needed to drive the card -> dialog -> cart flow. + +- packages/ui/src/components/quantifier.tsx + dec / value / inc testID="quantifier-decrement|quantifier-value|quantifier-increment" +- packages/ui/src/components/mini-quantifier.tsx + dec / value / inc testID="mini-quantifier-decrement|mini-quantifier-value|mini-quantifier-increment" +- apps/user-ui/src/components/AddToCartDialog.tsx + delete (isUpdate) testID="remove-from-cart" + +On the home page the visible Quantifier is always the dialog's (cards are +miniView, which renders MiniQuantifier), so quantifier-* is unambiguous there. + +[2026-09-18 00:52:00] user-ui: test the card quantity stepper's real behavior. + +Adds "updates and removes a cart item through the card quantity stepper": +add a product, then press the card's increment, assert the dialog opens in +update mode with the current cart quantity (the pressed delta is discarded by +ProductCard, see the 00:40 finding), increment in the dialog and confirm to +reach 2 items, then press the card's decrement and use the dialog's delete +button to remove it back to "No Items In Cart". + +[2026-09-18 00:56:00] user-ui: mutation-checked the stepper test; fixed a wrong expectation. + +Neutralising updateLocalCartItem (quantity not persisted) and removeFromLocalCart +(filter kept everything) made the stepper test fail; both were restored. + +Also corrected my own expectation: the floating cart bar counts cart LINES, not +units (itemCount = cartItems.length), so one product at quantity 2 still reads +"1 Item". The test now asserts the per-card quantity instead, and notes the bar +semantics. Suite: 12 passed / 1 todo, tsc clean. + +[2026-09-18 01:10:00] user-ui: router spies + store row testID for navigation tests. + +The expo-router mock returned fresh jest.fn()s from every useRouter() call, so a +test could never inspect them, and it lived in global setup, which blocked using +the real router in a dedicated file. Now: + +- tests/mocks/router.ts (new) shared routerMock spies + resetRouterMock +- tests/setup.ts expo-router mock removed +- tests/home.test.tsx owns the expo-router mock (hoisted), backed by + routerMock, so navigation.test.tsx gets the real + router from expo-router/testing-library +- app/(drawer)/(tabs)/home/index.tsx RenderStore testID={`store-item-${item.id}`} + (pressing the store name relied on event bubbling) + +[2026-09-18 01:25:00] user-ui: navigation tests (spies + real router); shared stock set. + +tests/home.test.tsx (18 cases) now owns the expo-router mock and adds six +navigation cases asserting routerMock.push: + store row -> /(drawer)/(tabs)/stores + navigationStore.setNavigatedFromHome(true) + and setSelectedStoreId(id); tag-grid product card -> product-detail/; + main-list product card -> product-detail/; slot card -> slot-view?slotId=; + search bar -> search-results; go-to-cart -> home/cart. +beforeEach also resets navigationStore (zustand is not covered by clearMocks). + +tests/navigation.test.tsx (new, 3 cases) drives the REAL router via +expo-router/testing-library renderRouter with a route map mirroring app/'s group +structure, and asserts getPathname()/getSearchParams() plus the params arriving +in the destination stub. toHavePathname has no TS declaration upstream (its +expect.d.ts is empty), so the typed getPathname()/getSearchParams() are used. + +Also moved the out-of-stock set into tests/mocks/api.ts as outOfStockIds, now the +single definition used by home.test.tsx and navigation.test.tsx (the latter had +picked products[0], which is unavailable and therefore not mounted). + +Mutation-checked: corrupting the product route made both spy tests and the +real-router test fail; renaming a route-map key failed only the real-router test. +Both reverted. Suite: 21 passed, tsc clean. + +[2026-09-26 00:23:22] user-ui: group home-page tests into tests/home-page/. + +Created apps/user-ui/tests/home-page/ and moved the two page-level files into it: + tests/home.test.tsx -> tests/home-page/home.test.tsx + tests/navigation.test.tsx -> tests/home-page/navigation.test.tsx +Relative imports updated (./mocks/x -> ../mocks/x, ./mocks/mock-*.json -> +../mocks/mock-*.json). tests/mocks/ and tests/__fixtures__/ stay shared at the +tests root; jest.config.js testMatch is recursive so no config change was needed. + +Plus new focused files to land in tests/home-page/: home-states, home-refresh, +home-slots, home-add-to-cart-dialog, home-cart, next-order-glimpse, home-cards. + +[2026-09-26 00:23:22] user-ui: make the network mocks configurable; add auth/refresh mocks. + +tests/mocks/api.ts + - setupApiMocks(opts) now accepts overrides: products (body), extraTags, consts + (essentialConsts payload), orders (user.order.getOrders data), failProducts, + failConsts, pendingProducts. Defaults preserve current behaviour. + - fetch mock resolves tRPC batch calls by procedure name parsed from the URL + path, so common.essentialConsts and user.order.getOrders (new, for + NextOrderGlimpse) share one handler. + - new exports: ESSENTIAL_CONSTS_DATA, EMPTY_PRODUCTS, EMPTY_TAG, + FLASH_ENABLED_CONSTS. + - resetStorage also clears 'essential_consts' (was leaking across tests). +tests/mocks/auth.ts (new) + - authMock holder + authContextMock() factory so tests can toggle signed-in. +tests/mocks/refresh.ts (new) + - refreshHooks captures the useManualRefresh / useMarkDataFetchers callbacks. +tests/setup.ts + - AuthContext mock now delegates to mocks/auth; the two refresh-hook mocks + record their callback via mocks/refresh instead of being no-ops. + +[2026-09-26 00:26:33] user-ui: new home-page test files + shared render helper. + +tests/home-page/render.tsx (new) + - provider stack (trpc + react-query + RefreshProvider + CentralStoreInitializer) + and renderHome/renderLoadedHome; shared products/tags/outOfStock helpers, + priceById/flashAvailableById from the availability fixture, upcomingSlots, + expandTag, addToCartFromTagGrid. +tests/home-page/home-states.test.tsx (new, 5 cases) + - loading ("Loading products..."), products error ("Failed to load products"), + consts error ("Failed to load app settings"), empty products + ("No products available"), empty tag grid ("No products in this category yet"). +tests/home-page/home-refresh.test.tsx (new, 2 cases) + - useManualRefresh / useMarkDataFetchers callbacks fan out to products, stores, + slots and essentialConsts refetches. +tests/home-page/home-slots.test.tsx (new, 3 cases) + - CLOSING SOON badge matches the 4h freeze rule (2 of the first 5 cards), + slot time labels (delivery range + "Order By"), "View all N items" count. +tests/home-page/home-add-to-cart-dialog.test.tsx (new, 3 cases) + - flash option shown when flash delivery is enabled and the SKU is flash + available -> confirm routes to the flash cart; confirm disabled with no slot + selected; reopening from the card stepper pre-selects the cart quantity. +tests/home-page/home-cart.test.tsx (new, 4 cases) + - collapsed bar value/line count, "₹X more for FREE Delivery" below 249 vs + "Free Delivery Unlocked" at/above it, expanding into the "Your Cart" dialog, + and useReconcileCartSlots rewriting an invalid slotId to a real slot. +tests/home-page/next-order-glimpse.test.tsx (new, 4 cases) + - signed out -> null; preview of an upcoming order (id, items, total, status); + flash order badge + "30-Min Delivery"; cancelled/success only -> null; + tapping a card routes to me/my-orders. +tests/home-page/home-cards.test.tsx (new, 3 cases) + - combo-only SKU (149) never rendered, all stores rendered with the "The " + prefix stripped, marketPrice struck through, and the image-error fallback. + +[2026-09-26 00:34:06] user-ui: fix follow-ups found by running the suite; all green. + +Ran the home-page jest suite once the user OK'd it. Note: NODE_ENV=production was +set in the shell, which loads React's production build and makes every render +throw "act(...) is not supported in production builds of React"; NODE_ENV=test +fixes it (unrelated to the tests). + + - tests/mocks/api.ts: reverted resetStorage to cart keys only and added + resetEssentialConsts(). Clearing essential_consts globally broke + navigation.test.tsx: its later cases rely on the persisted consts giving + useGetEssentialConsts synchronous placeholderData. The consts override in + home-add-to-cart-dialog now clears that key itself. + - tests/home-page/home-slots.test.tsx: the delivery and order-by date lines are + the same string, so assert via getAllByText instead of getByText. + +Suite: 9 files / 47 tests passed. tsc clean. + +[2026-09-26 00:42:48] user-ui: dedicated floating cart bar test file with pinned products. + +tests/home-page/home-floating-cart-bar.test.tsx (new, 5 cases) replaces +tests/home-page/home-cart.test.tsx (removed). + - Pins two products with exact prices (2 / "Chicken Breast 500 g" / Rs 215 and + 40 / "Chicken regular cut Large pieces" / Rs 129, both in the "Chicken" tag) + and adds exactly those from the tag grid. + - Confirms the running total (Rs 215 -> Rs 344) and the free-delivery + threshold (Rs 34 more -> Free Delivery Unlocked at 249). + - Confirms each item sits in the first open slot it belongs to (asserts the + cart dialog's slot label, mirroring FloatingCartBar's formatTimeRange). + - Confirms the total recomputes on a quantity change (215 -> 430). + - Keeps the expand-into-cart-dialog and useReconcileCartSlots re-slot cases. + +Follow-up: adding two products back-to-back raced the first add's dialog cleanup +(clearAddedToCartProduct in its onSuccess) against the second product's dialog, so +the second item was dropped. Both multi-add tests now wait for the bar to update +between adds. Suite: 9 files / 48 tests passed. tsc clean. + + + + + + diff --git a/packages/ui/src/components/mini-quantifier.tsx b/packages/ui/src/components/mini-quantifier.tsx index 7fe925f..442d9b7 100644 --- a/packages/ui/src/components/mini-quantifier.tsx +++ b/packages/ui/src/components/mini-quantifier.tsx @@ -15,6 +15,7 @@ interface MiniQuantifierProps { const MiniQuantifier: React.FC = ({ value, onChange, showUnits = false, unit, step = 1 }) => ( onChange(Math.max(0, value - step))} activeOpacity={0.7} @@ -22,12 +23,13 @@ const MiniQuantifier: React.FC = ({ value, onChange, showUn - {value} + {value} {showUnits && unit && ( {unit} )} onChange(value + step)} activeOpacity={0.7} diff --git a/packages/ui/src/components/quantifier.tsx b/packages/ui/src/components/quantifier.tsx index abc0bf7..289b092 100644 --- a/packages/ui/src/components/quantifier.tsx +++ b/packages/ui/src/components/quantifier.tsx @@ -20,6 +20,7 @@ const Quantifier: React.FC = ({ return ( setValue(Math.max(min, value - step))} activeOpacity={0.7} @@ -28,7 +29,7 @@ const Quantifier: React.FC = ({ - + {value} {/* {unitText && ( @@ -40,6 +41,7 @@ const Quantifier: React.FC = ({ { if (max !== undefined && value + step > max) return;