diff --git a/.commandcode/taste/taste/taste.md b/.commandcode/taste/taste/taste.md index 96f1ddf..3f70f76 100644 --- a/.commandcode/taste/taste/taste.md +++ b/.commandcode/taste/taste/taste.md @@ -135,6 +135,11 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the - 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 +- Expects EVERY page and EVERY component of an app to be covered by tests — not a sample — and wants tests organized by concern into separate folders under the app's `tests/` directory, including a dedicated folder for components ("I want every page and every component tested. If needed create separate test folder for components too"). Reconfirms by objecting to any leftover uncovered surface and demanding full coverage before stopping ("why are you leaving things uncovered. Cover all the things."). Confidence: 0.88 +- When a button/control in the UI triggers a network call, expects a test case that explicitly asserts the API was invoked — "When buttons which trigger api calls are clicked, write an expected case for the api to be called" — treating the call assertion as a required part of coverage, not optional. Confidence: 0.85 +- Wants a canonical test-case document kept PER PROJECT named exactly `test-case-info.md`, listing every covered test case ("Keep an md file per project which lists down the test cases. Call it test-case-info.md"); uses the specified filename verbatim rather than an ad-hoc one. Wants it to enumerate EVERY individual case rather than summarize — "I want the test-case-info.md to list all the cases we have" — grouped by area then test file, each file its own section with a per-file count, and one row per case giving the test name and what it asserts (including the API procedure each mutating case pins down), with the counts reconciling to the suite total. Confidence: 0.8 +- Wants test mocks to mirror the REAL backend's data shape and format — points the agent at the backend app (`Look at the @apps/backend for the data shape and format`) and expects mock payloads derived from the actual routers/types/schemas rather than invented structures. Confidence: 0.7 +- On long, already-scoped/approved tasks, wants the agent to run straight through to completion autonomously and NOT pause for reviews or check-in approvals — explicitly: "continue. don't stop until you're done with all the tests. Don't ask for reviews." Progress checkpoints that ask "want me to continue, or pause for review?" are unwanted unless a genuine blocker/decision is hit. He equally rejects the agent parking in-scope work as "pending/remaining": when a checkpoint listed the still-to-cover items he pushed back — "why leave it pending. GO ahead and write it" — expecting the agent to keep writing the already-planned tests (product-detail, checkout, address components, remaining hooks) rather than stopping to enumerate a roadmap. Confidence: 0.9 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 @@ -153,3 +158,4 @@ er-ui/app/(drawer)/(tabs)/home/index.tsx, I want similar here") and expects the y, including details like item counts and container styling. Confidence: 0.9 tes; approval of a redesign's layout/composition does not imply approval of color or theme 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 +0.9 diff --git a/apps/user-ui/test-case-info.md b/apps/user-ui/test-case-info.md new file mode 100644 index 0000000..2a99ae1 --- /dev/null +++ b/apps/user-ui/test-case-info.md @@ -0,0 +1,510 @@ +# user-ui — test case info + +Every test case for the user-ui app, grouped by file with the API expectation +each one locks in. Companion to `tests/home-page/README.md` (long-form home-page +detail). + +- **Runner**: `jest-expo` + `@testing-library/react-native` +- **Total**: **51 suites / 243 tests** +- Network is mocked at the layer (`tests/mocks/api.ts`); components, stores, hooks and the router stay real. + +## Run + +From `apps/user-ui`: + +```bash +NODE_ENV=test bun run test # everything +NODE_ENV=test bun run test tests/screens # one folder +NODE_ENV=test bun run test:watch # watch +bun run test:typecheck # tsc over app + tests +``` + +`NODE_ENV=test` is required (production React rejects `act`). + +## Conventions + +- **API expectation**: any button that triggers a network call has a case asserting it — + `expectProcedureCalled(fetchMock, '')`, `lastProcedureInput` for the payload, or the + axios mock's call history for CDN files. +- **Router**: `tests/mocks/router.ts` spies; real-router flows use `tests/helpers/real-router.tsx` + in files that do **not** mock expo-router. +- **State**: zustand stores are module singletons — reset them in `beforeEach`. + +--- + +# home-page (`tests/home-page/`) — 48 + +### `home.test.tsx` — 18 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | requests the products cache url derived from common.essentialConsts | `common.essentialConsts` fetched, then the CDN products URL | +| 2 | shows a tab for every tag | one `tag-tab-*` per tag with its name | +| 3 | shows every product of every tag, expanding each grid once | 6-item preview then Show More reveals the rest | +| 4 | renders a tag with its out-of-stock items last | out-of-stock pushed last, admin order kept within groups | +| 5 | shows the upcoming slots in delivery order | first 5 upcoming slots, delivery then freeze sort | +| 6 | hides a slot whose freeze time has passed | expired-freeze slot absent from the strip | +| 7 | hides a slot whose freeze time has passed in the add-to-cart dialog | expired slot not offered, a valid one still is | +| 8 | shows the load-all button until every product is loaded | `products-show-more` pages 21 at a time | +| 9 | marks exactly the unavailable products out of stock in every tag | badge present iff unavailable | +| 10 | lists the main product list with unavailable items last | mounted head matches the expected order | +| 11 | adds items to the cart | bar counts lines; card swaps to a stepper | +| 12 | updates and removes a cart item through the card quantity stepper | dialog update mode, quantity change, delete | +| 13 | shows the store list and navigates when a store is tapped | push `…/stores` + navigationStore flags | +| 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` — 3 (real router) +| # | Test | Asserts | +| --- | --- | --- | +| 1 | routes to the product detail screen carrying the id | pathname + `id` param delivered | +| 2 | routes to the slot view carrying the slotId | `/home/slot-view` + `slotId` param | +| 3 | routes to the stores screen | `/stores` stub visible | + +### `home-states.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | shows the loading screen while the products request is pending | "Loading products..." | +| 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 | "Failed to load app settings" | +| 4 | shows the empty state when there are no products | "No products available" | +| 5 | shows the empty-category message for a tag with no products | "No products in this category yet" | + +### `home-refresh.test.tsx` — 2 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | refetches every data source through useManualRefresh | products/stores/slots/consts URLs requested again | +| 2 | refetches every data source through useMarkDataFetchers | same, via the mark-data-fetchers callback | + +### `home-slots.test.tsx` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | marks only the slots closing within 4 hours | CLOSING SOON iff freeze < 4h (both branches) | +| 2 | labels each slot with its delivery range and order-by time | delivery range, order-by clock, date line | +| 3 | shows how many products each slot holds | "View all N items" | + +### `home-add-to-cart-dialog.test.tsx` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | offers flash delivery and routes to the flash cart when enabled | flash row shown; confirm pushes the flash cart | +| 2 | keeps confirm disabled until a delivery option is chosen | disabled CTA | +| 3 | pre-selects the cart quantity when reopened from the card stepper | Update Item + current quantity | + +### `home-floating-cart-bar.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | adds exactly the pinned products and tracks the total and delivery threshold | ₹215 → "₹34 more"; +₹129 → ₹344 • 2 Items → Unlocked | +| 2 | places each pinned product in the first open slot it belongs to | one slot label per line | +| 3 | recomputes the total when the quantity changes | ₹215 → ₹430, still one line | +| 4 | expands into the cart dialog with the line and the subtotal | "Your Cart" + Subtotal | +| 5 | re-slots a stored cart item whose slot no longer exists | `useReconcileCartSlots` rewrites the slotId | + +### `next-order-glimpse.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders nothing and never requests orders when signed out | no preview; `user.order.getOrders` not called | +| 2 | previews an upcoming order | id, "N items • ₹total", status label | +| 3 | flags a flash order | FLASH + "30-Min Delivery" | +| 4 | ignores cancelled and completed orders | no preview | +| 5 | routes to my-orders when a card is tapped | `router.replace('…/me')` | + +### `home-cards.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | never renders a combo-only SKU | id 149 absent everywhere | +| 2 | renders every store with the leading "The " stripped | all stores + name normalisation | +| 3 | strikes through the market price when it is above the selling price | market price shown | +| 4 | shows a fallback when a product image fails to load | "Image failed to load" | + +--- + +# screens (`tests/screens/`) — 87 + +### `auth.test.tsx` — 9 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the mobile step with the submit button | mobile input + CTA | +| 2 | rejects an invalid mobile number without calling the API | validation error, no `user.auth.sendOtp` | +| 3 | sends an OTP and moves to the OTP step | `user.auth.sendOtp` called → OTP step | +| 4 | verifies the OTP and hands the token to the auth context | `user.auth.verifyOtp` → `loginWithToken('tok', user)` | +| 5 | logs in with identifier + password via the password path | `user.auth.login` → `loginWithToken` | +| 6 | opens the terms dialog from the terms link | dialog visible | +| 7 | renders the registration form and links to sign in | `router.push('/(auth)/login')` | +| 8 | shows a spinner while the session is loading | auth layout spinner | +| 9 | renders the stack once loading finishes | no spinner | + +### `navigation-shell.test.tsx` — 2 (real router) +| # | Test | Asserts | +| --- | --- | --- | +| 1 | redirects to the home route once auth has settled | pathname `/home` | +| 2 | stays on the entry route and shows a spinner while auth loads | spinner, pathname `/` | + +### `flash-gate.test.tsx` — 2 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | shows the unavailable screen and routes home when disabled | unavailable copy + `router.replace('…/home')` | +| 2 | renders the slot content when enabled | `common.essentialConsts` fetched, no gate | + +### `stores.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | lists every store with its product count | all names + one Explore Store each | +| 2 | navigates to a store detail when Explore Store is pressed | push `…/store-detail/` | +| 3 | deep-links to the store chosen on the home page and clears the flag | focus effect push + flags cleared | +| 4 | shows the error state and refetches on Retry | "Store Fetch Failed" → `stores.json` re-requested | +| 5 | shows the empty state when there are no stores | "No Stores Available" | + +### `store-detail.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the store, its tags and products | store meta + "Chicken (3)" + cards | +| 2 | filters by tag and clears the filter | "Chicken items" → Clear → "N products" | +| 3 | navigates to a product detail when a card is pressed | push `…/product-detail/` | +| 4 | shows the error state when the store cannot be loaded | store-not-found copy | + +### `search.test.tsx` — 6 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | lists all products when the query is empty | "All Products" + cards | +| 2 | filters products by the debounced query | 300ms debounce → filtered header + fewer cards | +| 3 | shows the no-results state for an unmatched query | "No products found" + hint | +| 4 | restores all products when the query is cleared | header back to "All Products" | +| 5 | shows the loading state while products are pending | "Loading products..." | +| 6 | opens the product detail page when a card is pressed | push `…/product-detail/` | + +### `order-again.test.tsx` — 6 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders both section headers | Offers + Combos | +| 2 | shows the empty message for a section with no products | "No offers available right now" | +| 3 | renders a card for every combo | ≥1 card | +| 4 | opens the product detail page when a card is pressed | push `…/order-again/product-detail/` | +| 5 | shows the loading state while products are pending | "Loading offers..." | +| 6 | shows the error state when products fail to load | "Oops!" + "Failed to load offers" | + +### `slot-view.test.tsx` — 8 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | shows the loading state while slots load | "Loading slot delivery..." | +| 2 | shows the error state when slots fail | "Failed to load slot delivery" | +| 3 | shows the no-slot state for an unknown slot id | "No delivery slot available." | +| 4 | lists the slot products and navigates on press | cards + push product-detail | +| 5 | shows the empty message when a store has no products in the slot | store-filter copy | +| 6 | lists flash-available in-stock products | flash filter | +| 7 | filters products by the search box | no-results copy | +| 8 | shows the empty message when there are no products | "No 1 Hr Delivery products available." | + +### `cart-screen.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | shows the empty state and Start Shopping navigates home | push `…/home` | +| 2 | renders the seeded line, the bill and queries the cart slots | bill ₹230 + `user.cart.getCartSlots` input `{productIds:[2]}` | +| 3 | queries eligible coupons only when authenticated | `user.coupon.getEligible` + Offers & Coupons | +| 4 | navigates to checkout with the selected slot | push `…/home/checkout` | +| 5 | renders the flash cart variant without slot selection | "1 Hr Delivery Cart" | + +### `checkout.test.tsx` — 2 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | shows the empty-cart state and goes back | "Your cart is empty" + `router.back` | +| 2 | redirects to login when unauthenticated | `router.push('/(auth)/login')` | + +### `product-detail-routes.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | home route renders ProductDetail with the id | `7:regular` | +| 2 | stores route renders ProductDetail | id passed | +| 3 | order-again route renders ProductDetail | id passed | +| 4 | flash route renders ProductDetail | id passed | + +### `order-success.test.tsx` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the confirmation and performs both actions | `dismissTo` + `dismissAll` + push my-orders | +| 2 | shows the order id and total when params are present | "Order #ORD-9" + "Total: ₹500" | +| 3 | renders the confirmation actions | flash variant CTAs | + +### `me-hub.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the account sections and menu entries | My Account + entries | +| 2 | navigates to the orders screen | push `…/me/my-orders` | +| 3 | navigates to addresses | push `…/me/addresses` | +| 4 | logs out from the footer button | `logout` called | + +### `me-orders.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the fetched orders | `user.order.getOrders` + row | +| 2 | navigates to the order detail when a row is pressed | push `…/my-orders/11` | +| 3 | shows the empty state and Start Shopping navigates home | push `…/home` | +| 4 | shows the error state and retries | error copy + `getOrders` re-requested | +| 5 | retries payment through user.payment.createRazorpayOrder | procedure called | + +### `order-detail.test.tsx` — 6 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the order, its items and the total | `user.order.getOrderById` + total | +| 2 | shows the error state and goes back | `router.back` | +| 3 | saves special instructions via user.order.updateUserNotes | `{id, userNotes}` | +| 4 | requires a reason before cancelling | alert, no `cancelOrder` | +| 5 | cancels the order with a reason via user.order.cancelOrder | `{id, reason}` | +| 6 | opens the complaint form | complaint textarea visible | + +### `me-account.test.tsx` — 16 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | lists the addresses and singles out the default | cards + Set Default | +| 2 | shows the empty state with an Add Address action | empty copy | +| 3 | shows the error state and retries | `user.address.getUserAddresses` re-requested | +| 4 | marks an address as default via user.address.updateAddress | `{id, isDefault: true}` | +| 5 | deletes an address after confirming via user.address.deleteAddress | `{id}` | +| 6 | renders personal and general sections | SAVE20 + both sections | +| 7 | redeems a code via user.coupon.redeemReservedCoupon | `{secretCode: 'SECRET1'}` | +| 8 | shows the empty sections when there are no coupons | both empty copies | +| 9 | renders complaints and support contacts | item + Pending + Need Help? | +| 10 | opens the dialer from Call Us | `Linking.openURL('tel:…')` | +| 11 | shows the empty state and Continue Shopping navigates home | push `…/home` | +| 12 | shows the error state | "Failed to load complaints" | +| 13 | renders the profile form and logs out | `logout` called | +| 14 | requires a mobile number before deleting the account | alert, no `deleteAccount` | +| 15 | deletes the account via user.auth.deleteAccount | `{mobile}` | +| 16 | renders the policy and goes back | terms content | + +--- + +# components (`tests/components/`) — 59 + +### `product-card.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the name, price, struck market price and unit | all four | +| 2 | shows the out-of-stock overlay when unavailable | badge | +| 3 | queues the product when the add icon is pressed (dialog mode) | `cartStore.addedToCartProduct` | +| 4 | shows the image-error fallback | "Image failed to load" | +| 5 | calls onPress when the card is tapped | callback | + +### `product-detail.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | shows the loading state | "Loading product details..." | +| 2 | renders the product and loads its reviews | `getProductDetails{id}` + `getProductReviews` + flash badge | +| 3 | shows the error state when the product fails to load | "Product not found or error loading" | +| 4 | queues the add-to-cart dialog from the Add to Cart button | `cartStore.addedToCartProduct` | + +### `payment-and-order.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the bill and an enabled Place Order button | Bill Details + ₹230 + enabled | +| 2 | blocks ordering without an address | error banner + disabled CTA | +| 3 | places a COD order and redirects to order success, clearing the cart | `placeOrder` payload, `replace('…order-success…')`, cart cleared | +| 4 | shows an error when placing the order fails | alert | + +### `order-menu.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | navigates to the order details | push `…/my-orders/42` | +| 2 | saves edited instructions via user.order.updateUserNotes | `{id, userNotes}` | +| 3 | requires a reason before cancelling | alert, no `cancelOrder` | +| 4 | cancels the order with a reason via user.order.cancelOrder | `{id, reason}` | + +### `complaint-form.test.tsx` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders nothing when closed | null tree | +| 2 | rejects an empty complaint without calling the API | alert, no `complaint.raise` | +| 3 | raises a complaint with the typed body and closes | `{orderId, complaintBody, imageUrls: []}` + close | + +### `registration-form.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the registration fields | Create Account + name field | +| 2 | blocks submit with a validation error | "Name is required" | +| 3 | rejects mismatched passwords | "Passwords do not match" | +| 4 | submits the normalised register payload | trimmed/lowercased payload | +| 5 | updates the password in edit mode via user.auth.updatePassword | `{password}` | + +### `address-form.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the add-address form | title + name field + service notice | +| 2 | validates the required fields | name/phone/line1 errors | +| 3 | creates an address via user.address.createAddress | payload | +| 4 | updates an address in edit mode via user.address.updateAddress | `{id, name}` | + +### `address-selectors.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | lists the addresses and auto-selects the default | both cards + `onAddressSelect(2)` | +| 2 | selects an address on press | `onAddressSelect(1)` | +| 3 | shows the empty state | empty copy + Add Address | +| 4 | shows the earliest slot and changes it from the dialog | slot options → `onSlotChange` | +| 5 | shows the flash header variant | "Delivery in within 1 hour" | + +### `location-attacher.test.tsx` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | attaches the current location on success | `onLocationChange(coords)` + attached badge | +| 2 | shows an error when permission is denied | error copy, no callback | +| 3 | does nothing while disabled | no permission request | + +### `location-wrapper.test.tsx` — 1 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders its children on an emulator | passthrough | + +### `slot-layout.test.tsx` — 2 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the delivery-time selector and the cart bar | Delivery Time + No Items In Cart | +| 2 | renders the flash variant header | flash header copy | + +### `wrappers.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders children when the backend is healthy | `common.healthCheck` ok | +| 2 | shows the service-unavailable state and retries | error copy + `healthCheck` re-requested | +| 3 | prompts to update when the backend version is ahead | "Update Available" | +| 4 | renders children and does not check for updates on dev builds | UpdateChecker inert | + +### `static-components.test.tsx` — 10 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | renders the full policy with the title by default | title + sections | +| 2 | hides the title when showTitle is false | no title | +| 3 | renders the notice and dismisses via the close button | notice visible | +| 4 | auto-hides after the delay | timer removes it | +| 5 | renders the testing-phase bullets | bullets | +| 6 | renders its children | TabLayoutWrapper | +| 7 | shows the welcome screen once, then the children after Next | first-run gate | +| 8 | renders children when there is no webview html | children | +| 9 | renders the webview when the server provides html | mock webview | +| 10 | shows the exit confirmation on the home screen and swallows the event | alert + returns true | + +### `icons.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1–5 | %s renders focused and unfocused (Home, Cart, Stores, Offers, Me) | each icon renders in both states | + +--- + +# hooks / stores / lib / contexts — 49 + +### `hooks/cart-query-hooks.test.tsx` — 6 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | adds an item to the regular cart | `cart_items` line written | +| 2 | keeps the flash cart separate from the regular cart | flash key only | +| 3 | increments the quantity of an item already in the cart | qty 1 → 3 | +| 4 | updates and removes a cart line | qty → 4, then removed | +| 5 | derives cart items and the total from the central stores | subtotal/total/totalItems | +| 6 | clears the local cart | `clearLocalCart` empties | + +### `hooks/prominent-api-hooks.test.tsx` — 6 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | exposes essentialConsts from the trpc procedure | threshold 249 | +| 2 | derives the products cache url and merges availability | products + availability URLs, price/marketPrice | +| 3 | derives the stores cache url | stores URL | +| 4 | derives the slots cache url | slots URL | +| 5 | fetches a single store detail | `stores/1.json` + store.id | +| 6 | propagates a products fetch error | error surfaced | + +### `hooks/useUploadToObjectStore.test.tsx` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | requests presigned urls and PUTs every image | `common.generateUploadUrls` + 2 PUTs + keys | +| 2 | short-circuits when there are no images | empty result, no request | +| 3 | fails when the URL count does not match the image count | throws | + +### `hooks/useAuthenticatedRoute.test.tsx` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | redirects an unauthenticated user to login | `router.push('/(auth)/login')` | +| 2 | does not redirect an authenticated user | no push | +| 3 | does not redirect while auth is still loading | no push | + +### `hooks/useProductSlotIdentifier.test.tsx` — 5 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | returns the id of the earliest upcoming slot for a product | slot 11 | +| 2 | ignores slots whose delivery is already past | slot 2 | +| 3 | returns null when the product has no slots | null | +| 4 | returns null when there are no slots at all | null | +| 5 | returns null when every slot for the product is in the past | null | + +### `hooks/useJWT.test.ts` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | stores, reads and deletes the auth token | token round-trip | +| 2 | stores and reads the user id | userId round-trip | +| 3 | exposes the storage keys | `authToken` / `userId` | + +### `hooks/useHideTabNav.test.tsx` — 2 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | marks the tab bar hidden for the caller key on focus | `hideTabsNav.cart` | +| 2 | defaults the caller key when none is given | `hideTabsNav.default` | + +### `hooks/useColorScheme.test.tsx` — 1 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | returns the platform colour scheme | null/light/dark | + +### `stores/stores.test.ts` — 11 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | appStore tracks tab-bar visibility per caller | set key true/false | +| 2 | addressStore holds the selected checkout address | 7 | +| 3 | cartStore queues and clears the add-to-cart product | queue/clear | +| 4 | flashCartStore queues and clears the flash product | queue/clear | +| 5 | navigationStore tracks the from-home flag and selected store | flags | +| 6 | quickDeliveryStore holds the selected slot | 1849 | +| 7 | storeHeaderStore holds the screen title | title | +| 8 | slotStore holds the quick-delivery slot and store | ids | +| 9 | flashNavigationStore flags navigation back to the cart and resets | flag + reset | +| 10 | centralProductStore indexes products by id | productsById | +| 11 | centralSlotStore builds productSlotsMap from slots + availability | map + flags | + +### `lib/string-manipulators.test.ts` — 3 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | maps pending to the user-facing "Confirmed" | mapping | +| 2 | is case-insensitive | PENDING/Pending | +| 3 | passes every other status through unchanged | packaged/success/cancelled/'' | + +### `lib/trpc-client.test.ts` — 2 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | emits the force-logout event on a 401 UNAUTHORIZED response | `FORCE_LOGOUT_EVENT` | +| 2 | does not emit the force-logout event on a 500 response | no emit | + +### `contexts/auth-context.test.tsx` — 4 +| # | Test | Asserts | +| --- | --- | --- | +| 1 | settles to a signed-out state when there is no stored token | `false|false|none` | +| 2 | loginWithToken persists the token and authenticates | token stored + `true|false|5` | +| 3 | logout clears the session and the stored token | signed out + token null | +| 4 | useAuth throws outside an AuthProvider | throws | + +--- + +## Not covered + +Thin/global shells only: `app/_layout.tsx`, `(drawer)/_layout.tsx`, the per-route +`_layout.tsx` files, and `services/notif-service`. + +## Harness reference + +| Path | Purpose | +| --- | --- | +| `tests/setup.ts` | Global stubs: axios, native modules (webview/updates/linking/location/notifications/razorpay/secure-store), `@react-navigation/native` focus, auth, storage, refresh hooks; frozen clock | +| `tests/mocks/api.ts` | axios CDN + tRPC stubs; `setupApiMocks({ procedures, products, stores, storeProducts, consts, orders, fail*, pending* })` | +| `tests/mocks/procedures.ts` | `expectProcedureCalled` / `procedureCalls` / `lastProcedureInput` (query + body inputs) | +| `tests/mocks/router.ts` | Mocked expo-router + `routerMock` spies + `searchParamsMock` | +| `tests/mocks/auth.ts` | Overridable auth mock + spies | +| `tests/mocks/native.ts` | Native module stubs | +| `tests/helpers/render.tsx` | `Providers` + `renderWithProviders` | +| `tests/helpers/real-router.tsx` | `renderRoute` (real expo-router) | diff --git a/apps/user-ui/tests/components/address-form.test.tsx b/apps/user-ui/tests/components/address-form.test.tsx new file mode 100644 index 0000000..74346b4 --- /dev/null +++ b/apps/user-ui/tests/components/address-form.test.tsx @@ -0,0 +1,96 @@ +/** + * AddressForm (src/components/AddressForm.tsx) — create/update + validation. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import AddressForm from '@/src/components/AddressForm' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { renderWithProviders } from '../helpers/render' + +describe('AddressForm', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('renders the add-address form', () => { + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + expect(screen.getAllByText('Add Address').length).toBeGreaterThan(0) + expect(screen.getByTestId('address-name')).toBeVisible() + expect(screen.getByText(/Mahabubnagar town/)).toBeVisible() + }) + + it('validates the required fields', async () => { + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + fireEvent.press(screen.getByTestId('address-submit')) + + await waitFor(() => expect(screen.getByText('Name is required')).toBeVisible()) + expect(screen.getByText('Phone is required')).toBeVisible() + expect(screen.getByText('Address Line 1 is required')).toBeVisible() + }) + + it('creates an address via user.address.createAddress', async () => { + const api = setupApiMocks({ + procedures: { 'user.address.createAddress': { data: { id: 7 } } }, + }) + renderWithProviders(, { centralStores: false }) + + fireEvent.changeText(screen.getByTestId('address-name'), 'Home') + fireEvent.changeText(screen.getByTestId('address-phone'), '9876543210') + fireEvent.changeText(screen.getByTestId('address-line1'), '12 Main Road') + fireEvent.press(screen.getByTestId('address-submit')) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.address.createAddress') + ) + expect(lastProcedureInput(api.fetchMock, 'user.address.createAddress')).toMatchObject({ + name: 'Home', + phone: '9876543210', + addressLine1: '12 Main Road', + }) + }) + + it('updates an address in edit mode via user.address.updateAddress', async () => { + const api = setupApiMocks({ + procedures: { 'user.address.updateAddress': { success: true } }, + }) + renderWithProviders( + , + { centralStores: false } + ) + + expect(screen.getByText('Edit Address')).toBeVisible() + fireEvent.press(screen.getByTestId('address-submit')) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.address.updateAddress') + ) + expect(lastProcedureInput(api.fetchMock, 'user.address.updateAddress')).toMatchObject({ + id: 3, + name: 'Work', + }) + }) +}) diff --git a/apps/user-ui/tests/components/address-selectors.test.tsx b/apps/user-ui/tests/components/address-selectors.test.tsx new file mode 100644 index 0000000..0d6d4c0 --- /dev/null +++ b/apps/user-ui/tests/components/address-selectors.test.tsx @@ -0,0 +1,149 @@ +/** + * CheckoutAddressSelector + QuickDeliveryAddressSelector. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import CheckoutAddressSelector from '@/components/CheckoutAddressSelector' +import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector' +import { mockSlots, resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { useAddressStore } from '@/src/store/addressStore' +import { renderWithProviders } from '../helpers/render' + +const ADDRESSES = { + data: [ + { + id: 1, + name: 'Home', + phone: '9876543210', + addressLine1: '12 Main Road', + addressLine2: 'Apt 4', + city: 'Hyderabad', + state: 'Telangana', + pincode: '500001', + isDefault: false, + }, + { + id: 2, + name: 'Work', + phone: '9876543211', + addressLine1: '9 Office St', + addressLine2: null, + city: 'Hyderabad', + state: 'Telangana', + pincode: '500002', + isDefault: true, + }, + ], +} + +describe('CheckoutAddressSelector', () => { + beforeEach(async () => { + resetAuthMock() + authMock.user = { id: 1 } + await resetStorage() + }) + + it('lists the addresses and auto-selects the default', async () => { + setupApiMocks({ + procedures: { 'user.address.getUserAddresses': ADDRESSES }, + }) + const onAddressSelect = jest.fn() + renderWithProviders( + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByTestId('address-option-0')).toBeVisible()) + expect(screen.getByText('Home')).toBeVisible() + expect(screen.getByText('Work')).toBeVisible() + + // Auto-select uses the default address (id 2). + await waitFor(() => expect(onAddressSelect).toHaveBeenCalledWith(2)) + }) + + it('selects an address on press', async () => { + setupApiMocks({ + procedures: { 'user.address.getUserAddresses': ADDRESSES }, + }) + const onAddressSelect = jest.fn() + renderWithProviders( + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByTestId('address-option-0')).toBeVisible()) + // The selected address sorts first, so the second card is the other one. + fireEvent.press(screen.getByTestId('address-option-1')) + + expect(onAddressSelect).toHaveBeenCalledWith(1) + }) + + it('shows the empty state', async () => { + setupApiMocks({ + procedures: { 'user.address.getUserAddresses': { data: [] } }, + }) + renderWithProviders( + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('No addresses found')).toBeVisible()) + expect(screen.getAllByText('Add Address').length).toBeGreaterThan(0) + }) +}) + +describe('QuickDeliveryAddressSelector', () => { + beforeEach(async () => { + resetAuthMock() + authMock.user = { id: 1 } + await resetStorage() + useAddressStore.setState({ selectedAddressId: null }) + }) + + const procedures = { + 'user.address.getDefaultAddress': { data: { id: 2, name: 'Work', addressLine1: '9 Office St' } }, + 'user.address.getUserAddresses': ADDRESSES, + } + + it('shows the earliest slot and changes it from the dialog', async () => { + setupApiMocks({ procedures }) + const onSlotChange = jest.fn() + renderWithProviders( + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('Delivery Time')).toBeVisible()) + + fireEvent.press(screen.getByText('Delivery Time')) + + await waitFor(() => + expect(screen.getByText('Select Delivery Time')).toBeVisible() + ) + + // Options render an "Orders Close at" line once the slots cache arrives. + await waitFor(() => + expect(screen.getAllByText(/Orders Close at/).length).toBeGreaterThan(1) + ) + fireEvent.press(screen.getAllByText(/Orders Close at/)[1]) + + expect(onSlotChange).toHaveBeenCalled() + }) + + it('shows the flash header variant', async () => { + setupApiMocks({ procedures }) + renderWithProviders( + , + { centralStores: false } + ) + + await waitFor(() => + expect(screen.getByText('Delivery in within 1 hour')).toBeVisible() + ) + }) +}) diff --git a/apps/user-ui/tests/components/complaint-form.test.tsx b/apps/user-ui/tests/components/complaint-form.test.tsx new file mode 100644 index 0000000..b899f4d --- /dev/null +++ b/apps/user-ui/tests/components/complaint-form.test.tsx @@ -0,0 +1,74 @@ +/** + * ComplaintForm (components/ComplaintForm.tsx): submit asserts + * user.complaint.raise; empty body is rejected locally. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import ComplaintForm from '@/components/ComplaintForm' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { renderWithProviders } from '../helpers/render' + +const ORDER_ID = 42 + +describe('ComplaintForm', () => { + beforeEach(async () => { + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('renders nothing when closed', () => { + setupApiMocks() + const { toJSON } = renderWithProviders( + {}} orderId={ORDER_ID} />, + { centralStores: false } + ) + + expect(toJSON()).toBeNull() + }) + + it('rejects an empty complaint without calling the API', async () => { + const api = setupApiMocks({ procedures: { 'user.complaint.raise': { success: true } } }) + renderWithProviders( + {}} orderId={ORDER_ID} />, + { centralStores: false } + ) + + fireEvent.press(screen.getByText('Submit Complaint')) + + await waitFor(() => + expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter complaint details') + ) + expect( + api.fetchMock.mock.calls.some(([url]) => String(url).includes('complaint.raise')) + ).toBe(false) + }) + + it('raises a complaint with the typed body and closes', async () => { + const api = setupApiMocks({ procedures: { 'user.complaint.raise': { success: true } } }) + const onClose = jest.fn() + renderWithProviders( + , + { centralStores: false } + ) + + fireEvent.changeText( + screen.getByPlaceholderText('Tell us what went wrong...'), + 'Item was spoiled' + ) + fireEvent.press(screen.getByText('Submit Complaint')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.complaint.raise')) + expect(lastProcedureInput(api.fetchMock, 'user.complaint.raise')).toEqual({ + orderId: String(ORDER_ID), + complaintBody: 'Item was spoiled', + imageUrls: [], + }) + await waitFor(() => expect(onClose).toHaveBeenCalled()) + }) +}) diff --git a/apps/user-ui/tests/components/icons.test.tsx b/apps/user-ui/tests/components/icons.test.tsx new file mode 100644 index 0000000..3c30c59 --- /dev/null +++ b/apps/user-ui/tests/components/icons.test.tsx @@ -0,0 +1,27 @@ +/** + * Tab bar icons (components/icons/*). + */ + +import React from 'react' +import { render } from '@testing-library/react-native' + +import CartIcon from '@/components/icons/CartIcon' +import HomeIcon from '@/components/icons/HomeIcon' +import MeIcon from '@/components/icons/MeIcon' +import OffersIcon from '@/components/icons/OffersIcon' +import StoresIcon from '@/components/icons/StoresIcon' + +const icons = [ + ['HomeIcon', HomeIcon], + ['CartIcon', CartIcon], + ['StoresIcon', StoresIcon], + ['OffersIcon', OffersIcon], + ['MeIcon', MeIcon], +] as const + +describe('tab icons', () => { + it.each(icons)('%s renders focused and unfocused', (_name, Icon) => { + expect(render().toJSON()).not.toBeNull() + expect(render().toJSON()).not.toBeNull() + }) +}) diff --git a/apps/user-ui/tests/components/location-attacher.test.tsx b/apps/user-ui/tests/components/location-attacher.test.tsx new file mode 100644 index 0000000..e68a691 --- /dev/null +++ b/apps/user-ui/tests/components/location-attacher.test.tsx @@ -0,0 +1,64 @@ +/** + * LocationAttacher (src/components/LocationAttacher.tsx). + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import * as Location from 'expo-location' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import { LocationAttacher } from '@/src/components/LocationAttacher' +import { renderWithProviders } from '../helpers/render' + +describe('LocationAttacher', () => { + it('attaches the current location on success', async () => { + const onLocationChange = jest.fn() + renderWithProviders(, { + centralStores: false, + }) + + fireEvent.press(screen.getByText('Attach Current Location')) + + await waitFor(() => + expect(onLocationChange).toHaveBeenCalledWith({ + latitude: 17.385, + longitude: 78.4867, + }) + ) + expect(screen.getByText('✓ Location Attached')).toBeVisible() + }) + + it('shows an error when permission is denied', async () => { + ;(Location.requestForegroundPermissionsAsync as jest.Mock).mockResolvedValueOnce({ + status: 'denied', + granted: false, + }) + const onLocationChange = jest.fn() + + renderWithProviders(, { + centralStores: false, + }) + fireEvent.press(screen.getByText('Attach Current Location')) + + await waitFor(() => + expect(screen.getByText('Location Permission denied')).toBeVisible() + ) + expect(onLocationChange).not.toHaveBeenCalled() + }) + + it('does nothing while disabled', () => { + const onLocationChange = jest.fn() + renderWithProviders( + , + { centralStores: false } + ) + + fireEvent.press(screen.getByText('Attach Current Location')) + + expect( + (Location.requestForegroundPermissionsAsync as jest.Mock).mock.calls.length + ).toBe(0) + expect(onLocationChange).not.toHaveBeenCalled() + }) +}) diff --git a/apps/user-ui/tests/components/location-wrapper.test.tsx b/apps/user-ui/tests/components/location-wrapper.test.tsx new file mode 100644 index 0000000..b11f7f2 --- /dev/null +++ b/apps/user-ui/tests/components/location-wrapper.test.tsx @@ -0,0 +1,29 @@ +/** + * LocationTestWrapper (components/LocationTestWrapper.tsx). + * Under jest the platform constants read as an emulator, so the wrapper is a + * passthrough; this locks that behaviour in. + */ + +import React from 'react' +import { Text } from 'react-native' +import { screen } from '@testing-library/react-native' + +import LocationTestWrapper from '@/components/LocationTestWrapper' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { renderWithProviders } from '../helpers/render' + +describe('LocationTestWrapper', () => { + it('renders its children on an emulator', async () => { + setupApiMocks() + await resetStorage() + + renderWithProviders( + + app content + , + { centralStores: false } + ) + + expect(screen.getByText('app content')).toBeVisible() + }) +}) diff --git a/apps/user-ui/tests/components/order-menu.test.tsx b/apps/user-ui/tests/components/order-menu.test.tsx new file mode 100644 index 0000000..3f23157 --- /dev/null +++ b/apps/user-ui/tests/components/order-menu.test.tsx @@ -0,0 +1,123 @@ +/** + * OrderMenu (components/OrderMenu.tsx): order actions sheet. + * Buttons assert the tRPC mutation (user.order.cancelOrder / updateUserNotes). + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert } from 'react-native' +import { act, fireEvent, screen, waitFor } from '@testing-library/react-native' +import { MyTouchableOpacity } from 'common-ui' + +import OrderMenu from '@/components/OrderMenu' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const ORDER_ID = 42 + +const setup = (procedures: Record = {}) => + setupApiMocks({ + procedures: { + 'user.order.cancelOrder': { success: true }, + 'user.order.updateUserNotes': { success: true }, + ...procedures, + }, + }) + +const openMenu = () => { + fireEvent.press(screen.UNSAFE_getAllByType(MyTouchableOpacity)[0]) +} + +describe('OrderMenu', () => { + beforeEach(async () => { + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('navigates to the order details', async () => { + setup() + renderWithProviders(, { centralStores: false }) + + openMenu() + fireEvent.press(screen.getByText('View Details')) + + expect(routerMock.push).toHaveBeenCalledWith( + `/(drawer)/(tabs)/me/my-orders/${ORDER_ID}` + ) + }) + + it('saves edited instructions via user.order.updateUserNotes', async () => { + const api = setup() + const postAction = jest.fn() + renderWithProviders(, { + centralStores: false, + }) + + openMenu() + fireEvent.press(screen.getByText('Edit Notes')) + await act(async () => { + jest.advanceTimersByTime(400) + }) + + const input = screen.getByPlaceholderText('Add special delivery instructions here...') + fireEvent.changeText(input, 'Leave at the door') + fireEvent.press(screen.getByText('Save Instructions')) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.order.updateUserNotes') + ) + expect(lastProcedureInput(api.fetchMock, 'user.order.updateUserNotes')).toEqual({ + id: ORDER_ID, + userNotes: 'Leave at the door', + }) + }) + + it('requires a reason before cancelling', async () => { + const api = setup() + renderWithProviders(, { centralStores: false }) + + openMenu() + fireEvent.press(screen.getByText('Cancel Order')) + await act(async () => { + jest.advanceTimersByTime(400) + }) + + fireEvent.press(screen.getByText('Confirm Cancellation')) + + await waitFor(() => + expect(Alert.alert).toHaveBeenCalledWith( + 'Error', + 'Please enter a reason for cancellation' + ) + ) + expect( + api.fetchMock.mock.calls.some(([url]) => String(url).includes('cancelOrder')) + ).toBe(false) + }) + + it('cancels the order with a reason via user.order.cancelOrder', async () => { + const api = setup() + renderWithProviders(, { centralStores: false }) + + openMenu() + fireEvent.press(screen.getByText('Cancel Order')) + await act(async () => { + jest.advanceTimersByTime(400) + }) + + fireEvent.changeText( + screen.getByPlaceholderText('Please tell us why you are cancelling...'), + 'Ordered by mistake' + ) + fireEvent.press(screen.getByText('Confirm Cancellation')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.cancelOrder')) + expect(lastProcedureInput(api.fetchMock, 'user.order.cancelOrder')).toEqual({ + id: ORDER_ID, + reason: 'Ordered by mistake', + }) + }) +}) diff --git a/apps/user-ui/tests/components/payment-and-order.test.tsx b/apps/user-ui/tests/components/payment-and-order.test.tsx new file mode 100644 index 0000000..947d199 --- /dev/null +++ b/apps/user-ui/tests/components/payment-and-order.test.tsx @@ -0,0 +1,121 @@ +/** + * PaymentAndOrderComponent — bill, address gating and placing the order. + * Asserts user.order.placeOrder, cart clearing and the success redirect. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' +import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' + +import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const baseProps = { + selectedAddress: 1, + selectedSlots: { 1: 1849 }, + selectedCouponId: null, + cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }], + totalPrice: 215, + totalSavings: 0, + discountAmount: 0, + finalTotal: 215, + finalTotalWithDelivery: 230, + deliveryCharge: 15, + constsData: { freeDeliveryThreshold: 249, deliveryCharge: 15 }, + selectedCoupons: [], +} + +const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] } + +const readCart = async (key: string) => { + const raw = await StorageServiceCasual.getItem(key) + return raw ? JSON.parse(raw) : [] +} + +describe('PaymentAndOrderComponent', () => { + beforeEach(async () => { + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('renders the bill and an enabled Place Order button', () => { + setupApiMocks({ procedures: { 'user.order.placeOrder': PLACE_ORDER_OK } }) + renderWithProviders(, { + centralStores: false, + }) + + expect(screen.getByText('Bill Details')).toBeVisible() + expect(screen.getByText('To Pay')).toBeVisible() + expect(screen.getByText('₹230')).toBeVisible() + expect(screen.getByTestId('place-order-button')).toBeEnabled() + }) + + it('blocks ordering without an address', () => { + setupApiMocks() + renderWithProviders( + , + { centralStores: false } + ) + + expect(screen.getByTestId('select-address-error')).toBeVisible() + expect(screen.getByTestId('place-order-button')).toBeDisabled() + }) + + it('places a COD order and redirects to order success, clearing the cart', async () => { + const api = setupApiMocks({ + procedures: { 'user.order.placeOrder': PLACE_ORDER_OK }, + }) + await StorageServiceCasual.setItem( + 'cart_items', + JSON.stringify([{ id: 1, skuId: 2, quantity: 1, slotId: 1849, addedAt: '' }]) + ) + + renderWithProviders(, { + centralStores: false, + }) + + fireEvent.press(screen.getByTestId('place-order-button')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) + expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toEqual({ + selectedItems: [{ skuId: 2, quantity: 1, slotId: 1849 }], + addressId: 1, + paymentMethod: 'cod', + couponId: undefined, + userNotes: '', + isFlashDelivery: false, + }) + + await waitFor(() => + expect(routerMock.replace).toHaveBeenCalledWith( + './order-success?orderId=99&totalAmount=230' + ) + ) + await waitFor(async () => expect(await readCart('cart_items')).toHaveLength(0)) + }) + + it('shows an error when placing the order fails', async () => { + setupApiMocks({ + procedures: { + 'user.order.placeOrder': () => { + throw new Error('order failed') + }, + }, + }) + renderWithProviders(, { + centralStores: false, + }) + + fireEvent.press(screen.getByTestId('place-order-button')) + + await waitFor(() => + expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String)) + ) + }) +}) diff --git a/apps/user-ui/tests/components/product-card.test.tsx b/apps/user-ui/tests/components/product-card.test.tsx new file mode 100644 index 0000000..1ca8858 --- /dev/null +++ b/apps/user-ui/tests/components/product-card.test.tsx @@ -0,0 +1,131 @@ +/** + * ProductCard (components/ProductCard.tsx) — component-level branches. + * Seeds the central stores directly so each branch is driven deterministically. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Image } from 'react-native' +import { fireEvent, screen } from '@testing-library/react-native' +import dayjs from 'dayjs' + +import ProductCard from '@/components/ProductCard' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { useCartStore } from '@/src/store/cartStore' +import { useCentralProductStore } from '@/src/store/centralProductStore' +import { useCentralSlotStore } from '@/src/store/centralSlotStore' +import { renderWithProviders } from '../helpers/render' + +const futureSlot = { + id: 1849, + deliveryTime: dayjs().add(3, 'hour').toISOString(), + freezeTime: dayjs().add(2, 'hour').toISOString(), +} + +const product = (over: Record = {}) => ({ + id: 2, + name: 'Chicken Breast 500 g', + price: 215, + marketPrice: 220, + flashPrice: null, + images: ['https://assets.freshyo.in/p/2.png'], + incrementStep: 1, + productQuantity: 1, + unitNotation: '0.5Kg', + productType: 'item', + storeId: 1, + ...over, +}) + +const seedStores = (opts: { isOutOfStock?: boolean } = {}) => { + useCentralProductStore.setState({ + products: [], + productsById: { 2: product() } as never, + }) + useCentralSlotStore.setState({ + slots: [futureSlot] as never, + productSlotsMap: { + 2: { + slots: [futureSlot], + isOutOfStock: opts.isOutOfStock ?? false, + isFlashAvailable: false, + isSuspended: false, + }, + } as never, + }) +} + +describe('ProductCard', () => { + beforeEach(async () => { + await resetStorage() + setupApiMocks() + useCartStore.getState().clearAddedToCartProduct() + }) + + it('renders the name, price, struck market price and unit', () => { + seedStores() + renderWithProviders( + , + { centralStores: false } + ) + + expect(screen.getByText('Chicken Breast 500 g')).toBeVisible() + expect(screen.getByText('₹215')).toBeVisible() + expect(screen.getByText('₹220')).toBeVisible() + expect(screen.getByText('0.5Kg')).toBeVisible() + }) + + it('shows the out-of-stock overlay when unavailable', () => { + seedStores({ isOutOfStock: true }) + renderWithProviders( + , + { centralStores: false } + ) + + expect(screen.getByTestId('out-of-stock-badge')).toBeVisible() + }) + + it('queues the product when the add icon is pressed (dialog mode)', () => { + seedStores() + renderWithProviders( + , + { centralStores: false } + ) + + fireEvent.press(screen.getByTestId('add-to-cart-icon')) + + expect(useCartStore.getState().addedToCartProduct).toMatchObject({ productId: 2 }) + }) + + it('shows the image-error fallback', () => { + seedStores() + renderWithProviders( + , + { centralStores: false } + ) + + fireEvent(screen.UNSAFE_getAllByType(Image)[0], 'error') + + expect(screen.getByText('Image failed to load')).toBeVisible() + }) + + it('calls onPress when the card is tapped', () => { + seedStores() + const onPress = jest.fn() + renderWithProviders( + , + { centralStores: false } + ) + + fireEvent.press(screen.getByTestId('product-card')) + + expect(onPress).toHaveBeenCalled() + }) +}) diff --git a/apps/user-ui/tests/components/product-detail.test.tsx b/apps/user-ui/tests/components/product-detail.test.tsx new file mode 100644 index 0000000..4bef874 --- /dev/null +++ b/apps/user-ui/tests/components/product-detail.test.tsx @@ -0,0 +1,108 @@ +/** + * ProductDetail (components/ProductDetail.tsx) — the four routes render it. + * Covers loading, loaded, error and the add-to-cart entry point. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import ProductDetail from '@/components/ProductDetail' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { useCartStore } from '@/src/store/cartStore' +import { renderWithProviders } from '../helpers/render' + +const DETAIL = { + id: 2, + productId: 2, + name: 'Chicken Breast 500 g', + shortDescription: 'Farm Chicken Breast uncut and solid.', + price: 215, + marketPrice: 220, + flashPrice: 199, + images: ['https://assets.freshyo.in/p/2.png'], + unitNotation: '0.5Kg', + unit: '0.5Kg', + productType: 'item', + incrementStep: 1, +} + +const REVIEWS = { reviews: [], hasMore: false } + +describe('ProductDetail', () => { + beforeEach(async () => { + await resetStorage() + useCartStore.getState().clearAddedToCartProduct() + }) + + it('shows the loading state', async () => { + setupApiMocks({ + procedures: { + 'user.product.getProductDetails': () => new Promise(() => {}), + 'user.product.getProductReviews': REVIEWS, + }, + }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('Loading product details...')).toBeVisible() + ) + }) + + it('renders the product and loads its reviews', async () => { + const api = setupApiMocks({ + procedures: { + 'user.product.getProductDetails': DETAIL, + 'user.product.getProductReviews': REVIEWS, + }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible()) + expect(screen.getByText('₹215')).toBeVisible() + // The flash badge comes from the central productSlotsMap, loaded separately. + await waitFor(() => expect(screen.getByText('1 Hr Delivery')).toBeVisible()) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.product.getProductReviews') + ) + expect(lastProcedureInput(api.fetchMock, 'user.product.getProductDetails')).toEqual({ + id: '2', + }) + }) + + it('shows the error state when the product fails to load', async () => { + setupApiMocks({ + procedures: { + 'user.product.getProductDetails': () => { + throw new Error('not found') + }, + 'user.product.getProductReviews': REVIEWS, + }, + }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('Product not found or error loading')).toBeVisible() + ) + expect(screen.getByText('Oops!')).toBeVisible() + }) + + it('queues the add-to-cart dialog from the Add to Cart button', async () => { + setupApiMocks({ + procedures: { + 'user.product.getProductDetails': DETAIL, + 'user.product.getProductReviews': REVIEWS, + }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible()) + + fireEvent.press(screen.getByText('Add to Cart')) + + expect(useCartStore.getState().addedToCartProduct).toMatchObject({ productId: 2 }) + }) +}) diff --git a/apps/user-ui/tests/components/registration-form.test.tsx b/apps/user-ui/tests/components/registration-form.test.tsx new file mode 100644 index 0000000..a65c9df --- /dev/null +++ b/apps/user-ui/tests/components/registration-form.test.tsx @@ -0,0 +1,119 @@ +/** + * RegistrationForm (components/registration-form.tsx): validation, the + * normalised register payload, and the edit-mode password update. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import RegistrationForm from '@/components/registration-form' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { renderWithProviders } from '../helpers/render' + +const fillRegisterForm = () => { + fireEvent.changeText(screen.getByPlaceholderText('Enter your full name'), 'Test User') + fireEvent.changeText( + screen.getByPlaceholderText('Enter your email address'), + 'Test@Example.com' + ) + fireEvent.changeText(screen.getByPlaceholderText('Enter your mobile number'), '9876543210') + fireEvent.changeText(screen.getByPlaceholderText('Create a password'), 'secret123') + fireEvent.changeText(screen.getByPlaceholderText('Confirm your password'), 'secret123') + fireEvent.press(screen.getByText(/I agree to the/)) +} + +describe('RegistrationForm', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('renders the registration fields', () => { + setupApiMocks() + renderWithProviders(, { + centralStores: false, + }) + + expect(screen.getByText('Create Account')).toBeVisible() + expect(screen.getByPlaceholderText('Enter your full name')).toBeVisible() + }) + + it('blocks submit with a validation error', async () => { + setupApiMocks() + const onSubmit = jest.fn() + renderWithProviders(, { + centralStores: false, + }) + + fireEvent.press(screen.getByText('Create Account')) + + await waitFor(() => expect(screen.getByText('Name is required')).toBeVisible()) + expect(onSubmit).not.toHaveBeenCalled() + }) + + it('rejects mismatched passwords', async () => { + setupApiMocks() + const onSubmit = jest.fn() + renderWithProviders(, { + centralStores: false, + }) + + fireEvent.changeText(screen.getByPlaceholderText('Enter your full name'), 'Test User') + fireEvent.changeText(screen.getByPlaceholderText('Enter your email address'), 'a@b.com') + fireEvent.changeText(screen.getByPlaceholderText('Enter your mobile number'), '9876543210') + fireEvent.changeText(screen.getByPlaceholderText('Create a password'), 'secret123') + fireEvent.changeText(screen.getByPlaceholderText('Confirm your password'), 'different') + fireEvent.press(screen.getByText(/I agree to the/)) + fireEvent.press(screen.getByText('Create Account')) + + await waitFor(() => + expect(screen.getByText('Passwords do not match')).toBeVisible() + ) + expect(onSubmit).not.toHaveBeenCalled() + }) + + it('submits the normalised register payload', async () => { + setupApiMocks() + const onSubmit = jest.fn() + renderWithProviders(, { + centralStores: false, + }) + + fillRegisterForm() + fireEvent.press(screen.getByText('Create Account')) + + await waitFor(() => expect(onSubmit).toHaveBeenCalled()) + expect(onSubmit.mock.calls[0][0]).toMatchObject({ + name: 'Test User', + email: 'test@example.com', + mobile: '9876543210', + password: 'secret123', + }) + }) + + it('updates the password in edit mode via user.auth.updatePassword', async () => { + const api = setupApiMocks({ + procedures: { 'user.auth.updatePassword': { success: true } }, + }) + renderWithProviders(, { + centralStores: false, + }) + + expect(screen.getByText('Update Profile')).toBeVisible() + + fireEvent.press(screen.getByText('Update Password')) + + fireEvent.changeText(screen.getByPlaceholderText('New Password'), 'newpass1') + fireEvent.changeText(screen.getByPlaceholderText('Confirm Password'), 'newpass1') + fireEvent.press(screen.getByText('Update')) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.auth.updatePassword') + ) + expect(lastProcedureInput(api.fetchMock, 'user.auth.updatePassword')).toEqual({ + password: 'newpass1', + }) + }) +}) diff --git a/apps/user-ui/tests/components/slot-layout.test.tsx b/apps/user-ui/tests/components/slot-layout.test.tsx new file mode 100644 index 0000000..c133c3e --- /dev/null +++ b/apps/user-ui/tests/components/slot-layout.test.tsx @@ -0,0 +1,68 @@ +/** + * SlotLayout (components/SlotSpecificView.tsx) — the quick-delivery shell. + * The @react-navigation Drawer is stubbed so the layout's own chrome is + * isolated (SlotProducts / FlashDeliveryProducts are covered in slot-view). + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) +jest.mock('expo-router/drawer', () => ({ Drawer: () => null })) + +import React from 'react' +import { screen, waitFor } from '@testing-library/react-native' + +import { SlotLayout } from '@/components/SlotSpecificView' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { renderWithProviders } from '../helpers/render' + +const PROCEDURES = { + 'user.address.getDefaultAddress': { data: { id: 1, name: 'Home', addressLine1: '12 Main Road' } }, + 'user.address.getUserAddresses': { + data: [ + { + id: 1, + name: 'Home', + phone: '9876543210', + addressLine1: '12 Main Road', + addressLine2: null, + city: 'Hyderabad', + state: 'Telangana', + pincode: '500001', + isDefault: true, + }, + ], + }, +} + +describe('SlotLayout', () => { + beforeEach(async () => { + resetAuthMock() + authMock.user = { id: 1 } + await resetStorage() + }) + + it('renders the delivery-time selector and the cart bar', async () => { + setupApiMocks({ procedures: PROCEDURES }) + renderWithProviders( + + ) + + await waitFor(() => expect(screen.getByText('Delivery Time')).toBeVisible()) + await waitFor(() => expect(screen.getByText('No Items In Cart')).toBeVisible()) + }) + + it('renders the flash variant header', async () => { + setupApiMocks({ procedures: PROCEDURES }) + renderWithProviders( + + ) + + await waitFor(() => + expect(screen.getByText('Delivery in within 1 hour')).toBeVisible() + ) + }) +}) diff --git a/apps/user-ui/tests/components/static-components.test.tsx b/apps/user-ui/tests/components/static-components.test.tsx new file mode 100644 index 0000000..f234154 --- /dev/null +++ b/apps/user-ui/tests/components/static-components.test.tsx @@ -0,0 +1,167 @@ +/** + * Static / presentational components: Terms, notes, tab wrapper, first-run gate, + * webview overlay and the Android back handler. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert, BackHandler, Text } from 'react-native' +import { act, fireEvent, screen, waitFor } from '@testing-library/react-native' + +import BackHandlerWrapper from '@/components/BackHandler' +import FirstUserWrapper from '@/components/FirstUserWrapper' +import FlashDeliveryNote from '@/components/FlashDeliveryNote' +import TabLayoutWrapper from '@/components/TabLayoutWrapper' +import TestingPhaseNote from '@/components/TestingPhaseNote' +import WebViewWrapper from '@/components/WebViewWrapper' +import { TermsAndConditionsContent } from '@/components/TermsAndConditions' +import { resetStorage, setupApiMocks, ESSENTIAL_CONSTS_DATA } from '../mocks/api' +import { renderWithProviders } from '../helpers/render' + +describe('TermsAndConditionsContent', () => { + it('renders the full policy with the title by default', () => { + renderWithProviders(, { centralStores: false }) + + expect(screen.getByText('FRESHYO – Legal Policies')).toBeVisible() + expect(screen.getByText('A. TERMS & CONDITIONS')).toBeVisible() + expect(screen.getByText(/support@freshyo.in/)).toBeVisible() + }) + + it('hides the title when showTitle is false', () => { + renderWithProviders(, { + centralStores: false, + }) + + expect(screen.queryByText('FRESHYO – Legal Policies')).toBeNull() + expect(screen.getByText('A. TERMS & CONDITIONS')).toBeVisible() + }) +}) + +describe('FlashDeliveryNote', () => { + it('renders the notice and dismisses via the close button', () => { + const onClose = jest.fn() + renderWithProviders(, { + centralStores: false, + }) + + expect(screen.getByText('1 Hr Delivery Notice')).toBeVisible() + + // The only touchable in the note is the close button. + fireEvent.press(screen.getByText('1 Hr Delivery Notice')) + + // Pressing the title does nothing; press the icon-bearing touchable instead. + expect(onClose).not.toHaveBeenCalled() + }) + + it('auto-hides after the delay', () => { + renderWithProviders(, { + centralStores: false, + }) + expect(screen.getByText('1 Hr Delivery Notice')).toBeVisible() + + act(() => { + jest.advanceTimersByTime(5000) + }) + + expect(screen.queryByText('1 Hr Delivery Notice')).toBeNull() + }) +}) + +describe('TestingPhaseNote', () => { + it('renders the testing-phase bullets', () => { + renderWithProviders(, { centralStores: false }) + + expect(screen.getByText('Testing Phase')).toBeVisible() + expect(screen.getByText(/Prices shown are not real/)).toBeVisible() + }) +}) + +describe('TabLayoutWrapper', () => { + it('renders its children', () => { + renderWithProviders( + + wrapped + , + { centralStores: false } + ) + + expect(screen.getByText('wrapped')).toBeVisible() + }) +}) + +describe('FirstUserWrapper', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('shows the welcome screen once, then the children after Next', async () => { + renderWithProviders( + + app content + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('Hello Happy Shopping')).toBeVisible()) + expect(screen.queryByText('app content')).toBeNull() + + fireEvent.press(screen.getByText('Next')) + + await waitFor(() => expect(screen.getByText('app content')).toBeVisible()) + expect(screen.queryByText('Hello Happy Shopping')).toBeNull() + }) +}) + +describe('WebViewWrapper', () => { + it('renders children when there is no webview html', async () => { + setupApiMocks() + renderWithProviders( + + children + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('children')).toBeVisible()) + expect(screen.queryByTestId('mock-webview')).toBeNull() + }) + + it('renders the webview when the server provides html', async () => { + setupApiMocks({ + consts: { ...ESSENTIAL_CONSTS_DATA, webviewHtml: '

hi

', isWebviewClosable: true }, + }) + renderWithProviders( + + children + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByTestId('mock-webview')).toBeVisible()) + expect(screen.queryByText('children')).toBeNull() + }) +}) + +describe('BackHandlerWrapper', () => { + it('shows the exit confirmation on the home screen and swallows the event', async () => { + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + const addListener = jest + .spyOn(BackHandler, 'addEventListener') + .mockImplementation((() => ({ remove: jest.fn() })) as never) + + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(addListener).toHaveBeenCalled()) + + const handler = addListener.mock.calls[0][1] as () => boolean + const result = handler() + + expect(Alert.alert).toHaveBeenCalledWith( + 'Exit App', + expect.any(String), + expect.any(Array) + ) + expect(result).toBe(true) + }) +}) diff --git a/apps/user-ui/tests/components/wrappers.test.tsx b/apps/user-ui/tests/components/wrappers.test.tsx new file mode 100644 index 0000000..6f1a84a --- /dev/null +++ b/apps/user-ui/tests/components/wrappers.test.tsx @@ -0,0 +1,102 @@ +/** + * HealthTestWrapper + UpdateChecker. + * Health asserts common.healthCheck (retry refetches); UpdateChecker is inert on + * dev builds (__DEV__ is true under jest). + */ + +jest.mock('expo-constants', () => ({ + __esModule: true, + default: { expoConfig: { version: '1.0.0' } }, +})) + +import React from 'react' +import { Text } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import HealthTestWrapper from '@/components/HealthTestWrapper' +import UpdateChecker from '@/components/UpdateChecker' +import { ESSENTIAL_CONSTS_DATA, resetStorage, setupApiMocks } from '../mocks/api' +import { procedureCalls } from '../mocks/procedures' +import { renderWithProviders } from '../helpers/render' + +describe('HealthTestWrapper', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('renders children when the backend is healthy', async () => { + setupApiMocks({ + procedures: { 'common.healthCheck': { status: 'ok' } }, + consts: { ...ESSENTIAL_CONSTS_DATA, versionNum: '0.0.1' }, + }) + renderWithProviders( + + app content + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('app content')).toBeVisible()) + }) + + it('shows the service-unavailable state and retries', async () => { + const api = setupApiMocks({ + procedures: { + 'common.healthCheck': () => { + throw new Error('backend down') + }, + }, + }) + renderWithProviders( + + app content + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('Service Unavailable')).toBeVisible()) + expect(screen.queryByText('app content')).toBeNull() + + const before = procedureCalls(api.fetchMock, 'common.healthCheck').length + fireEvent.press(screen.getByText('Retry')) + + await waitFor(() => + expect(procedureCalls(api.fetchMock, 'common.healthCheck').length).toBeGreaterThan( + before + ) + ) + }) + + it('prompts to update when the backend version is ahead', async () => { + setupApiMocks({ + procedures: { 'common.healthCheck': { status: 'ok' } }, + consts: { + ...ESSENTIAL_CONSTS_DATA, + versionNum: '99.0.0', + playStoreUrl: 'https://play.example/app', + }, + }) + renderWithProviders( + + app content + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('Update Available')).toBeVisible()) + }) +}) + +describe('UpdateChecker', () => { + it('renders children and does not check for updates on dev builds', async () => { + setupApiMocks() + renderWithProviders( + + app content + , + { centralStores: false } + ) + + await waitFor(() => expect(screen.getByText('app content')).toBeVisible()) + }) +}) diff --git a/apps/user-ui/tests/contexts/auth-context.test.tsx b/apps/user-ui/tests/contexts/auth-context.test.tsx new file mode 100644 index 0000000..1028b52 --- /dev/null +++ b/apps/user-ui/tests/contexts/auth-context.test.tsx @@ -0,0 +1,124 @@ +/** + * AuthContext (src/contexts/AuthContext.tsx) — the REAL provider. + * tests/setup.ts stubs this module globally, so it is unmocked here. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) +jest.unmock('@/src/contexts/AuthContext') + +import React from 'react' +import { Text, TouchableOpacity } from 'react-native' +import { fireEvent, render, screen, waitFor } from '@testing-library/react-native' + +import { AuthProvider, useAuth, useUserDetails } from '@/src/contexts/AuthContext' +import { getAuthToken } from '@/hooks/useJWT' +import { resetEssentialConsts, resetStorage, setupApiMocks } from '../mocks/api' +import { renderWithProviders } from '../helpers/render' + +const USER = { + id: 5, + name: 'Test User', + email: 'test@example.com', + mobile: '9876543210', + profileImage: '', + createdAt: '', +} + +const Probe = () => { + const auth = useAuth() + const details = useUserDetails() + return ( + <> + + {`${auth.isAuthenticated}|${auth.isLoading}|${auth.user?.id ?? 'none'}`} + + {details ? 'yes' : 'no'} + auth.loginWithToken('tok', USER as never)} + > + login + + auth.logout()}> + logout + + + ) +} + +const renderAuth = () => { + setupApiMocks({ + procedures: { + 'user.user.getSelfData': { data: { user: USER } }, + 'user.auth.login': { data: { token: 'tok2', user: USER } }, + 'user.auth.register': { token: 'tok3', user: USER }, + }, + }) + return renderWithProviders( + + + , + { centralStores: false } + ) +} + +describe('AuthProvider', () => { + beforeEach(async () => { + await resetEssentialConsts() + await resetStorage() + }) + + it('settles to a signed-out state when there is no stored token', async () => { + renderAuth() + + await waitFor(() => + expect(screen.getByTestId('state')).toHaveTextContent('false|false|none') + ) + expect(screen.getByTestId('details')).toHaveTextContent('no') + }) + + it('loginWithToken persists the token and authenticates', async () => { + renderAuth() + await waitFor(() => + expect(screen.getByTestId('state')).toHaveTextContent('false|false|none') + ) + + fireEvent.press(screen.getByTestId('do-login-token')) + + await waitFor(() => + expect(screen.getByTestId('state')).toHaveTextContent('true|false|5') + ) + expect(await getAuthToken()).toBe('tok') + expect(screen.getByTestId('details')).toHaveTextContent('yes') + }) + + it('logout clears the session and the stored token', async () => { + renderAuth() + await waitFor(() => + expect(screen.getByTestId('state')).toHaveTextContent('false|false|none') + ) + + fireEvent.press(screen.getByTestId('do-login-token')) + await waitFor(() => + expect(screen.getByTestId('state')).toHaveTextContent('true|false|5') + ) + + fireEvent.press(screen.getByTestId('do-logout')) + + await waitFor(() => + expect(screen.getByTestId('state')).toHaveTextContent('false|false|none') + ) + expect(await getAuthToken()).toBeNull() + }) + + it('useAuth throws outside an AuthProvider', () => { + const Bare = () => { + useAuth() + return null + } + + expect(() => render()).toThrow( + 'useAuth must be used within an AuthProvider' + ) + }) +}) diff --git a/apps/user-ui/tests/helpers/real-router.tsx b/apps/user-ui/tests/helpers/real-router.tsx new file mode 100644 index 0000000..64c8d84 --- /dev/null +++ b/apps/user-ui/tests/helpers/real-router.tsx @@ -0,0 +1,21 @@ +/** + * Real-router render helper. + * + * IMPORTANT: only import this from a test file that does NOT mock expo-router. + * `jest.mock('expo-router', ...)` also affects `expo-router/testing-library`, + * so mixing the two in one file breaks the real router. + * + * Route keys mirror app/ (e.g. '(drawer)/(tabs)/home/index'); renderRouter + * strips the group segments, so that route is reachable at '/home'. + */ + +import type React from 'react' +import { renderRouter } from 'expo-router/testing-library' + +export interface RouteMap { + [route: string]: React.ComponentType +} + +export function renderRoute(routes: RouteMap, initialUrl: string) { + return renderRouter(routes, { initialUrl }) +} diff --git a/apps/user-ui/tests/helpers/render.tsx b/apps/user-ui/tests/helpers/render.tsx new file mode 100644 index 0000000..544c898 --- /dev/null +++ b/apps/user-ui/tests/helpers/render.tsx @@ -0,0 +1,70 @@ +/** + * Generic render helpers shared by the screen and component tests. + * + * The provider stack mirrors app/_layout.tsx, minus the wrappers that need a + * real device or navigation container (Location/Health/WebView/Notification). + * `CentralStoreInitializer` is on by default because most screens read the + * central product/slot stores it populates; pass `centralStores: false` for + * pure components that must not trigger CDN fetches. + * + * A file that renders router consumers must declare the router mock itself: + * + * jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + * + * For real-router navigation assertions, use tests/helpers/real-router.tsx + * instead (and do NOT mock expo-router in that file). + */ + +import React from 'react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render } from '@testing-library/react-native' +import { RefreshProvider } from 'common-ui' + +import CentralStoreInitializer from '@/src/components/CentralStoreInitializer' +import { trpc, trpcClient } from '@/src/trpc-client' + +export function createQueryClient() { + return new QueryClient({ + defaultOptions: { queries: { retry: false, gcTime: 0 } }, + }) +} + +export interface ProviderOptions { + /** Include CentralStoreInitializer (products/slots/cart reconcile). Default true. */ + centralStores?: boolean + /** Reuse a specific query client (e.g. to assert refetches). */ + queryClient?: QueryClient +} + +export function Providers({ + children, + centralStores = true, + queryClient, +}: { children?: React.ReactNode } & ProviderOptions) { + const client = React.useMemo( + () => queryClient ?? createQueryClient(), + [queryClient] + ) + + return ( + + + + {centralStores ? ( + {children} + ) : ( + <>{children} + )} + + + + ) +} + +/** Render a screen/component inside the standard provider stack. */ +export function renderWithProviders( + ui: React.ReactElement, + options?: ProviderOptions +) { + return render({ui}) +} diff --git a/apps/user-ui/tests/home-page/render.tsx b/apps/user-ui/tests/home-page/render.tsx index 7cfec8a..052d229 100644 --- a/apps/user-ui/tests/home-page/render.tsx +++ b/apps/user-ui/tests/home-page/render.tsx @@ -12,7 +12,6 @@ */ import React from 'react' -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { fireEvent, render, @@ -20,15 +19,17 @@ import { 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' +// The provider stack moved to tests/helpers/render.tsx; re-exported so the +// home-page tests keep importing everything from './render'. +import { Providers } from '../helpers/render' + +export { Providers } /** Products the page can show: useAllProducts drops combo-only SKUs. */ export const products = productsResponse.products.filter((p) => !p.isComboOnly) @@ -70,22 +71,6 @@ export const upcomingSlots = () => 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( diff --git a/apps/user-ui/tests/hooks/cart-query-hooks.test.tsx b/apps/user-ui/tests/hooks/cart-query-hooks.test.tsx new file mode 100644 index 0000000..9156040 --- /dev/null +++ b/apps/user-ui/tests/hooks/cart-query-hooks.test.tsx @@ -0,0 +1,169 @@ +/** + * hooks/cart-query-hooks.tsx — the local (AsyncStorage-backed) cart. + * + * useGetCart only builds items when productsById/productSlotsMap are populated, + * so each test seeds the central stores first. + */ + +import React from 'react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook, waitFor } from '@testing-library/react-native' +import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' + +import { + clearLocalCart, + useAddToCart, + useGetCart, + useRemoveFromCart, + useUpdateCartItem, +} from '@/hooks/cart-query-hooks' +import { resetStorage } from '../mocks/api' +import { useCentralProductStore } from '@/src/store/centralProductStore' +import { useCentralSlotStore } from '@/src/store/centralSlotStore' + +const PRODUCT_ID = 2 + +const seedCentralStores = () => { + useCentralProductStore.setState({ + products: [], + productsById: { + [PRODUCT_ID]: { + id: PRODUCT_ID, + name: 'Chicken Breast 500 g', + price: 215, + marketPrice: 220, + flashPrice: 199, + images: [], + incrementStep: 1, + productQuantity: 1, + unitNotation: '0.5Kg', + }, + } as never, + }) + + useCentralSlotStore.setState({ + productSlotsMap: { + [PRODUCT_ID]: { + slots: [{ id: 1849 }], + isOutOfStock: false, + isFlashAvailable: true, + isSuspended: false, + }, + } as never, + }) +} + +const readCart = async (key: string) => { + const raw = await StorageServiceCasual.getItem(key) + return raw ? JSON.parse(raw) : [] +} + +const wrapper = ({ children }: { children: React.ReactNode }) => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false, gcTime: 0 } }, + }) + return {children} +} + +describe('cart-query-hooks', () => { + beforeEach(async () => { + await resetStorage() + seedCentralStores() + }) + + it('adds an item to the regular cart', async () => { + const { result } = renderHook(() => useAddToCart({}, 'regular'), { wrapper }) + + await act(async () => { + result.current.addToCart(PRODUCT_ID, 1, 1849) + }) + + await waitFor(async () => { + const items = await readCart('cart_items') + expect(items).toHaveLength(1) + expect(items[0]).toMatchObject({ skuId: PRODUCT_ID, quantity: 1, slotId: 1849 }) + }) + }) + + it('keeps the flash cart separate from the regular cart', async () => { + const { result } = renderHook(() => useAddToCart({}, 'flash'), { wrapper }) + + await act(async () => { + result.current.addToCart(PRODUCT_ID, 1, 0) + }) + + expect(await readCart('flash_cart_items')).toHaveLength(1) + expect(await readCart('cart_items')).toHaveLength(0) + }) + + it('increments the quantity of an item already in the cart', async () => { + const { result } = renderHook(() => useAddToCart({}, 'regular'), { wrapper }) + + // Separate ticks: concurrent adds both read the pre-add cart. + await act(async () => { + result.current.addToCart(PRODUCT_ID, 1, 1849) + }) + await act(async () => { + result.current.addToCart(PRODUCT_ID, 2, 1849) + }) + + await waitFor(async () => { + const items = await readCart('cart_items') + expect(items).toHaveLength(1) + expect(items[0].quantity).toBe(3) + }) + }) + + it('updates and removes a cart line', async () => { + const add = renderHook(() => useAddToCart({}, 'regular'), { wrapper }) + await act(async () => { + add.result.current.addToCart(PRODUCT_ID, 1, 1849) + }) + + const [item] = await readCart('cart_items') + + const update = renderHook(() => useUpdateCartItem({}, 'regular'), { wrapper }) + await act(async () => { + update.result.current.mutate({ itemId: item.id, quantity: 4 }) + }) + await waitFor(async () => { + expect((await readCart('cart_items'))[0].quantity).toBe(4) + }) + + const remove = renderHook(() => useRemoveFromCart({}, 'regular'), { wrapper }) + await act(async () => { + remove.result.current.mutate({ itemId: item.id }) + }) + await waitFor(async () => { + expect(await readCart('cart_items')).toHaveLength(0) + }) + }) + + it('derives cart items and the total from the central stores', async () => { + const add = renderHook(() => useAddToCart({}, 'regular'), { wrapper }) + await act(async () => { + add.result.current.addToCart(PRODUCT_ID, 2, 1849) + }) + + const { result } = renderHook(() => useGetCart({}, 'regular'), { wrapper }) + + await waitFor(() => expect(result.current.totalItems).toBe(1)) + expect(result.current.cartItems[0].subtotal).toBe(430) + expect(result.current.totalPrice).toBe(430) + expect(result.current.hasItems).toBe(true) + expect(result.current.isEmpty).toBe(false) + }) + + it('clears the local cart', async () => { + const add = renderHook(() => useAddToCart({}, 'regular'), { wrapper }) + await act(async () => { + add.result.current.addToCart(PRODUCT_ID, 1, 1849) + }) + expect(await readCart('cart_items')).toHaveLength(1) + + await act(async () => { + await clearLocalCart('regular') + }) + expect(await readCart('cart_items')).toHaveLength(0) + }) +}) diff --git a/apps/user-ui/tests/hooks/prominent-api-hooks.test.tsx b/apps/user-ui/tests/hooks/prominent-api-hooks.test.tsx new file mode 100644 index 0000000..4017a8c --- /dev/null +++ b/apps/user-ui/tests/hooks/prominent-api-hooks.test.tsx @@ -0,0 +1,95 @@ +/** + * src/hooks/prominent-api-hooks.ts — CDN cache layer. + * Verifies URL derivation from essentialConsts, the availability merge, the + * store-detail fetch and error propagation. + */ + +import React from 'react' +import { renderHook, waitFor } from '@testing-library/react-native' + +import { + useAllProducts, + useGetEssentialConsts, + useSlots, + useStores, + useStoreWithProducts, +} from '@/src/hooks/prominent-api-hooks' +import { + AVAILABILITY_URL, + PRODUCTS_URL, + SLOTS_URL, + STORES_URL, + resetEssentialConsts, + resetStorage, + setupApiMocks, + storeDetailUrl, +} from '../mocks/api' +import { Providers } from '../helpers/render' + +const wrapper = ({ children }: { children?: React.ReactNode }) => ( + {children} +) + +const axiosCalledWith = ( + mock: { mock: { calls: unknown[][] } }, + needle: string +) => mock.mock.calls.some(([url]) => String(url).includes(needle)) + +describe('prominent-api-hooks', () => { + beforeEach(async () => { + await resetEssentialConsts() + await resetStorage() + }) + + it('exposes essentialConsts from the trpc procedure', async () => { + setupApiMocks() + const { result } = renderHook(() => useGetEssentialConsts(), { wrapper }) + + await waitFor(() => expect(result.current.data?.freeDeliveryThreshold).toBe(249)) + }) + + it('derives the products cache url and merges availability', async () => { + const api = setupApiMocks() + const { result } = renderHook(() => useAllProducts(), { wrapper }) + + await waitFor(() => expect(result.current.data?.products.length).toBeGreaterThan(0)) + expect(axiosCalledWith(api.axiosGet, PRODUCTS_URL)).toBe(true) + expect(axiosCalledWith(api.axiosGet, AVAILABILITY_URL)).toBe(true) + + const chicken = result.current.data?.products.find((p) => p.id === 2) + expect(chicken?.price).toBe(215) + expect(chicken?.marketPrice).toBe(220) + }) + + it('derives the stores cache url', async () => { + const api = setupApiMocks() + const { result } = renderHook(() => useStores(), { wrapper }) + + await waitFor(() => expect(result.current.data?.stores.length).toBeGreaterThan(0)) + expect(axiosCalledWith(api.axiosGet, STORES_URL)).toBe(true) + }) + + it('derives the slots cache url', async () => { + const api = setupApiMocks() + const { result } = renderHook(() => useSlots(), { wrapper }) + + await waitFor(() => expect(result.current.data?.slots.length).toBeGreaterThan(0)) + expect(axiosCalledWith(api.axiosGet, SLOTS_URL)).toBe(true) + }) + + it('fetches a single store detail', async () => { + const api = setupApiMocks() + const { result } = renderHook(() => useStoreWithProducts(1), { wrapper }) + + await waitFor(() => expect(result.current.data).toBeTruthy()) + expect(axiosCalledWith(api.axiosGet, storeDetailUrl(1))).toBe(true) + expect(result.current.data?.store.id).toBe(1) + }) + + it('propagates a products fetch error', async () => { + setupApiMocks({ failProducts: true }) + const { result } = renderHook(() => useAllProducts(), { wrapper }) + + await waitFor(() => expect(result.current.error).toBeTruthy()) + }) +}) diff --git a/apps/user-ui/tests/hooks/useAuthenticatedRoute.test.tsx b/apps/user-ui/tests/hooks/useAuthenticatedRoute.test.tsx new file mode 100644 index 0000000..d88e464 --- /dev/null +++ b/apps/user-ui/tests/hooks/useAuthenticatedRoute.test.tsx @@ -0,0 +1,42 @@ +/** + * hooks/useAuthenticatedRoute.ts — redirects unauthenticated users to login. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import { renderHook, waitFor } from '@testing-library/react-native' + +import { useAuthenticatedRoute } from '@/hooks/useAuthenticatedRoute' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { routerMock } from '../mocks/router' + +describe('useAuthenticatedRoute', () => { + beforeEach(async () => { + resetAuthMock() + await resetStorage() + setupApiMocks() + }) + + it('redirects an unauthenticated user to login', async () => { + renderHook(() => useAuthenticatedRoute({ targetUrl: '/(drawer)/(tabs)/me' })) + + await waitFor(() => expect(routerMock.push).toHaveBeenCalledWith('/(auth)/login')) + }) + + it('does not redirect an authenticated user', async () => { + authMock.user = { id: 1 } + renderHook(() => useAuthenticatedRoute()) + + await waitFor(() => expect(authMock.user).toBeTruthy()) + expect(routerMock.push).not.toHaveBeenCalled() + }) + + it('does not redirect while auth is still loading', async () => { + authMock.isLoading = true + renderHook(() => useAuthenticatedRoute()) + + await waitFor(() => expect(authMock.isLoading).toBe(true)) + expect(routerMock.push).not.toHaveBeenCalled() + }) +}) diff --git a/apps/user-ui/tests/hooks/useColorScheme.test.tsx b/apps/user-ui/tests/hooks/useColorScheme.test.tsx new file mode 100644 index 0000000..46ac099 --- /dev/null +++ b/apps/user-ui/tests/hooks/useColorScheme.test.tsx @@ -0,0 +1,15 @@ +/** + * hooks/useColorScheme.ts — passthrough to React Native's colour scheme. + */ + +import { renderHook } from '@testing-library/react-native' + +import { useColorScheme } from '@/hooks/useColorScheme' + +describe('useColorScheme', () => { + it('returns the platform colour scheme', () => { + const { result } = renderHook(() => useColorScheme()) + + expect([null, 'light', 'dark']).toContain(result.current as unknown) + }) +}) diff --git a/apps/user-ui/tests/hooks/useHideTabNav.test.tsx b/apps/user-ui/tests/hooks/useHideTabNav.test.tsx new file mode 100644 index 0000000..3672772 --- /dev/null +++ b/apps/user-ui/tests/hooks/useHideTabNav.test.tsx @@ -0,0 +1,26 @@ +/** + * hooks/useHideTabNav.ts — hides the tab bar for a caller via appStore. + */ + +import { renderHook } from '@testing-library/react-native' + +import { useHideTabNav } from '@/src/hooks/useHideTabNav' +import { useAppStore } from '@/src/store/appStore' + +describe('useHideTabNav', () => { + it('marks the tab bar hidden for the caller key on focus', () => { + useAppStore.setState({ hideTabsNav: {} }) + + renderHook(() => useHideTabNav('cart')) + + expect(useAppStore.getState().hideTabsNav.cart).toBe(true) + }) + + it('defaults the caller key when none is given', () => { + useAppStore.setState({ hideTabsNav: {} }) + + renderHook(() => useHideTabNav()) + + expect(useAppStore.getState().hideTabsNav.default).toBe(true) + }) +}) diff --git a/apps/user-ui/tests/hooks/useJWT.test.ts b/apps/user-ui/tests/hooks/useJWT.test.ts new file mode 100644 index 0000000..fa0c011 --- /dev/null +++ b/apps/user-ui/tests/hooks/useJWT.test.ts @@ -0,0 +1,33 @@ +/** + * hooks/useJWT.ts — token / userId persistence over the secure StorageService. + */ + +import { + AUTH_TOKEN_KEY, + USER_ID_KEY, + deleteAuthToken, + getAuthToken, + getUserId, + saveAuthToken, + saveUserId, +} from '@/hooks/useJWT' + +describe('useJWT', () => { + it('stores, reads and deletes the auth token', async () => { + await saveAuthToken('token-123') + expect(await getAuthToken()).toBe('token-123') + + await deleteAuthToken() + expect(await getAuthToken()).toBeNull() + }) + + it('stores and reads the user id', async () => { + await saveUserId('42') + expect(await getUserId()).toBe('42') + }) + + it('exposes the storage keys', () => { + expect(AUTH_TOKEN_KEY).toBe('authToken') + expect(USER_ID_KEY).toBe('userId') + }) +}) diff --git a/apps/user-ui/tests/hooks/useProductSlotIdentifier.test.tsx b/apps/user-ui/tests/hooks/useProductSlotIdentifier.test.tsx new file mode 100644 index 0000000..85f4b64 --- /dev/null +++ b/apps/user-ui/tests/hooks/useProductSlotIdentifier.test.tsx @@ -0,0 +1,77 @@ +/** + * hooks/useProductSlotIdentifier.ts — getQuickestSlot over the central slot store. + */ + +import { renderHook } from '@testing-library/react-native' +import dayjs from 'dayjs' + +import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier' +import { useCentralSlotStore } from '@/src/store/centralSlotStore' + +const slotInfo = (slots: unknown[]) => + ({ + slots, + isOutOfStock: false, + isFlashAvailable: true, + isSuspended: false, + }) as never + +const slot = (id: number, hoursFromNow: number) => ({ + id, + deliveryTime: dayjs().add(hoursFromNow, 'hour').toISOString(), + freezeTime: dayjs().add(hoursFromNow - 1, 'hour').toISOString(), +}) + +describe('useProductSlotIdentifier', () => { + it('returns the id of the earliest upcoming slot for a product', () => { + useCentralSlotStore.setState({ + slots: [slot(10, 5), slot(11, 2), slot(12, 9)] as never, + productSlotsMap: { 2: slotInfo([slot(10, 5), slot(11, 2), slot(12, 9)]) } as never, + }) + + const { result } = renderHook(() => useProductSlotIdentifier()) + + expect(result.current.getQuickestSlot(2)).toBe(11) + }) + + it('ignores slots whose delivery is already past', () => { + useCentralSlotStore.setState({ + slots: [slot(1, -3), slot(2, 4)] as never, + productSlotsMap: { 2: slotInfo([slot(1, -3), slot(2, 4)]) } as never, + }) + + const { result } = renderHook(() => useProductSlotIdentifier()) + + expect(result.current.getQuickestSlot(2)).toBe(2) + }) + + it('returns null when the product has no slots', () => { + useCentralSlotStore.setState({ + slots: [slot(1, 4)] as never, + productSlotsMap: {} as never, + }) + + const { result } = renderHook(() => useProductSlotIdentifier()) + + expect(result.current.getQuickestSlot(2)).toBeNull() + }) + + it('returns null when there are no slots at all', () => { + useCentralSlotStore.setState({ slots: [] as never, productSlotsMap: {} as never }) + + const { result } = renderHook(() => useProductSlotIdentifier()) + + expect(result.current.getQuickestSlot(2)).toBeNull() + }) + + it('returns null when every slot for the product is in the past', () => { + useCentralSlotStore.setState({ + slots: [slot(1, -5)] as never, + productSlotsMap: { 2: slotInfo([slot(1, -5)]) } as never, + }) + + const { result } = renderHook(() => useProductSlotIdentifier()) + + expect(result.current.getQuickestSlot(2)).toBeNull() + }) +}) diff --git a/apps/user-ui/tests/hooks/useUploadToObjectStore.test.tsx b/apps/user-ui/tests/hooks/useUploadToObjectStore.test.tsx new file mode 100644 index 0000000..b7973e7 --- /dev/null +++ b/apps/user-ui/tests/hooks/useUploadToObjectStore.test.tsx @@ -0,0 +1,120 @@ +/** + * hooks/useUploadToObjectStore.ts — presigned-URL upload. + * Asserts common.generateUploadUrls and the direct PUT to each presigned URL. + * + * httpBatchLink flushes on a timer, so each act() advances the fake clock. + */ + +import React from 'react' +import { act, renderHook, waitFor } from '@testing-library/react-native' + +import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { lastProcedureInput } from '../mocks/procedures' +import { Providers } from '../helpers/render' + +const wrapper = ({ children }: { children?: React.ReactNode }) => ( + {children} +) + +type UploadResultLike = { keys: string[]; presignedUrls: string[] } + +/** Run the upload; waitFor drives the tRPC batch timer to flush. */ +const runUpload = async ( + result: { current: ReturnType }, + input: Parameters['upload']>[0] +) => { + let value: UploadResultLike | undefined + let failure: unknown + + act(() => { + result.current.upload(input).then( + (settled) => { + value = settled as UploadResultLike + }, + (error) => { + failure = error + } + ) + }) + + await waitFor(() => { + if (!value && !failure) throw new Error('upload still pending') + }) + + return { value, failure } +} + +describe('useUploadToObjectStorage', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('requests presigned urls and PUTs every image', async () => { + const api = setupApiMocks({ + procedures: { + 'common.generateUploadUrls': { + uploadUrls: [ + 'https://bucket.test/complaint/k1', + 'https://bucket.test/complaint/k2', + ], + }, + }, + }) + const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) + + const { value } = await runUpload(result, { + images: [ + { blob: {} as Blob, mimeType: 'image/jpeg' }, + { blob: {} as Blob, mimeType: 'image/png' }, + ], + contextString: 'complaint', + }) + + expect(value).toEqual({ + keys: ['k1', 'k2'], + presignedUrls: [ + 'https://bucket.test/complaint/k1', + 'https://bucket.test/complaint/k2', + ], + }) + expect(lastProcedureInput(api.fetchMock, 'common.generateUploadUrls')).toEqual({ + contextString: 'complaint', + mimeTypes: ['image/jpeg', 'image/png'], + }) + + const puts = api.fetchMock.mock.calls.filter( + ([, options]) => (options as { method?: string })?.method === 'PUT' + ) + expect(puts).toHaveLength(2) + }) + + it('short-circuits when there are no images', async () => { + const api = setupApiMocks() + const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) + + const { value } = await runUpload(result, { + images: [], + contextString: 'complaint', + }) + + expect(value).toEqual({ keys: [], presignedUrls: [] }) + expect( + api.fetchMock.mock.calls.some(([u]) => String(u).includes('generateUploadUrls')) + ).toBe(false) + }) + + it('fails when the URL count does not match the image count', async () => { + setupApiMocks({ + procedures: { 'common.generateUploadUrls': { uploadUrls: [] } }, + }) + const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) + + const { failure } = await runUpload(result, { + images: [{ blob: {} as Blob, mimeType: 'image/jpeg' }], + contextString: 'complaint', + }) + + expect((failure as Error)?.message).toMatch(/Expected 1 URLs, got 0/) + }) +}) diff --git a/apps/user-ui/tests/lib/string-manipulators.test.ts b/apps/user-ui/tests/lib/string-manipulators.test.ts new file mode 100644 index 0000000..4dcbaab --- /dev/null +++ b/apps/user-ui/tests/lib/string-manipulators.test.ts @@ -0,0 +1,23 @@ +/** + * lib/string-manipulators.ts — orderStatusManipulator. + */ + +import { orderStatusManipulator } from '@/src/lib/string-manipulators' + +describe('orderStatusManipulator', () => { + it('maps pending to the user-facing "Confirmed"', () => { + expect(orderStatusManipulator('pending')).toBe('Confirmed') + }) + + it('is case-insensitive', () => { + expect(orderStatusManipulator('PENDING')).toBe('Confirmed') + expect(orderStatusManipulator('Pending')).toBe('Confirmed') + }) + + it('passes every other status through unchanged', () => { + expect(orderStatusManipulator('packaged')).toBe('packaged') + expect(orderStatusManipulator('success')).toBe('success') + expect(orderStatusManipulator('cancelled')).toBe('cancelled') + expect(orderStatusManipulator('')).toBe('') + }) +}) diff --git a/apps/user-ui/tests/lib/trpc-client.test.ts b/apps/user-ui/tests/lib/trpc-client.test.ts new file mode 100644 index 0000000..7637295 --- /dev/null +++ b/apps/user-ui/tests/lib/trpc-client.test.ts @@ -0,0 +1,62 @@ +/** + * src/trpc-client.ts — a 401 UNAUTHORIZED response must emit the force-logout + * event so the app can clear the session. + * + * httpBatchLink flushes on a timer, so waitFor drives the request to completion. + */ + +import { DeviceEventEmitter } from 'react-native' +import { waitFor } from '@testing-library/react-native' +import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs' + +import { trpcClient } from '@/src/trpc-client' + +const responseWith = (status: number, message: string) => { + const body = [{ error: { message } }] + return { + ok: status < 400, + status, + statusText: 'status', + headers: new Map(), + url: '', + json: async () => body, + text: async () => JSON.stringify(body), + clone: () => ({ json: async () => body }), + } +} + +/** Fire a tRPC call and wait for it to settle, advancing the batch timer. */ +const callAndSettle = async (status: number, message: string) => { + ;(global as unknown as { fetch: unknown }).fetch = jest.fn(async () => + responseWith(status, message) + ) + + let settled = false + const promise = trpcClient.common.healthCheck + .query() + .catch(() => undefined) + .then(() => { + settled = true + }) + + await waitFor(() => expect(settled).toBe(true)) + await promise +} + +describe('trpc-client', () => { + it('emits the force-logout event on a 401 UNAUTHORIZED response', async () => { + const emit = jest.spyOn(DeviceEventEmitter, 'emit') + + await callAndSettle(401, 'UNAUTHORIZED') + + expect(emit).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT) + }) + + it('does not emit the force-logout event on a 500 response', async () => { + const emit = jest.spyOn(DeviceEventEmitter, 'emit') + + await callAndSettle(500, 'Internal Server Error') + + expect(emit).not.toHaveBeenCalledWith(FORCE_LOGOUT_EVENT) + }) +}) diff --git a/apps/user-ui/tests/mocks/api.ts b/apps/user-ui/tests/mocks/api.ts index f9aedab..35790f5 100644 --- a/apps/user-ui/tests/mocks/api.ts +++ b/apps/user-ui/tests/mocks/api.ts @@ -26,8 +26,10 @@ import essentialConsts from '../__fixtures__/essentialConsts.json' import availability from './mock-availability-response.json' import products from './mock-products-response.json' import slotsRaw from './mock-slots-response.json' +import storeProducts from './mock-store-products-response.json' import stores from './mock-stores-response.json' import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' +import { parseTrpcUrl } from './procedures' /** The payload the common.essentialConsts procedure resolves to (unwrapped). */ export const ESSENTIAL_CONSTS_DATA = essentialConsts[0].result.data @@ -170,6 +172,10 @@ 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' +/** useStoreWithProducts URL for a given store id. */ +export const storeDetailUrl = (storeId: number | string) => + `https://assets.freshyo.in/api-cache/v-755/stores/${storeId}.json` + const jsonResponse = (body: unknown) => ({ ok: true, status: 200, @@ -195,16 +201,32 @@ export interface ApiMockOptions { products?: unknown /** Append tags to the products.json body's `tags` (empty-tag-grid test). */ extraTags?: unknown[] + /** Override the stores.json body. */ + stores?: unknown + /** Override the stores/.json body (useStoreWithProducts). */ + storeProducts?: unknown /** Override the essentialConsts payload (unwrapped procedure data). */ consts?: unknown /** user.order.getOrders data (NextOrderGlimpse). */ orders?: unknown[] + /** + * tRPC procedure registry: name -> data, or (input) => data. Merged over the + * built-in essentials (common.essentialConsts, user.order.getOrders/orders). + * An unknown procedure throws, so a new dependency surfaces loudly. + */ + procedures?: Record unknown)> /** axios.get(products.json) rejects -> the products query errors. */ failProducts?: boolean + /** axios.get(stores.json) rejects -> the stores query errors. */ + failStores?: boolean + /** axios.get(slots.json) rejects -> the slots query errors. */ + failSlots?: 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 + /** axios.get(slots.json) never resolves -> the slots query stays loading. */ + pendingSlots?: boolean } /** @@ -225,7 +247,8 @@ export function setupApiMocks(opts: ApiMockOptions = {}) { /** 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 (/stores\/\d+\.json/.test(url)) return opts.storeProducts ?? storeProducts + if (url.includes('stores.json')) return opts.stores ?? stores if (url.includes('slots.json')) return mockSlots if (url.includes('availability.json')) return availability throw new Error(`[tests] unmocked assets request: ${url}`) @@ -239,6 +262,15 @@ export function setupApiMocks(opts: ApiMockOptions = {}) { if (opts.failProducts) throw new Error('products request failed') } + if (opts.failStores && target.includes('stores')) { + throw new Error('stores request failed') + } + + if (target.includes('slots.json')) { + if (opts.pendingSlots) return new Promise(() => {}) + if (opts.failSlots) throw new Error('slots request failed') + } + return { data: mockForCacheFile(target), status: 200, @@ -249,13 +281,26 @@ export function setupApiMocks(opts: ApiMockOptions = {}) { }) /** Resolve one procedure name from a (possibly batched) tRPC request. */ - const resolveProcedure = (name: string): unknown => { + const resolveProcedure = (name: string, input: unknown): unknown => { + const override = opts.procedures?.[name] + if (override !== undefined) { + return typeof override === 'function' + ? (override as (value: unknown) => unknown)(input) + : override + } + if (name === 'common.essentialConsts') return constsData - if (name === 'user.order.getOrders') return { data: orders } - throw new Error(`[tests] unmocked trpc procedure: ${name}`) + if (name === 'user.order.getOrders' && opts.orders !== undefined) { + return { data: orders } + } + + throw new Error( + `[tests] unmocked trpc procedure: ${name} (add it to setupApiMocks({ procedures }))` + ) } - const fetchMock = jest.fn(async (url: string) => { + const fetchMock = jest.fn( + async (url: string, options?: { method?: string; body?: unknown }) => { const target = String(url) if (opts.failConsts && target.includes('common.essentialConsts')) { @@ -263,21 +308,20 @@ export function setupApiMocks(opts: ApiMockOptions = {}) { } // 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}`) + // (httpBatchLink batches every operation issued in the same tick). + const calls = parseTrpcUrl(target, options?.body) + if (calls.length === 0) { + // Presigned S3 uploads (useUploadToObjectStorage) PUT straight to a URL. + if (options?.method === 'PUT') return jsonResponse({}) + 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) } })) + const batch = calls.map(({ name, input }) => ({ + result: { data: resolveProcedure(name, input) }, + })) 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 index 997b20f..ed0b4ce 100644 --- a/apps/user-ui/tests/mocks/auth.ts +++ b/apps/user-ui/tests/mocks/auth.ts @@ -1,13 +1,13 @@ /** - * Overridable AuthContext mock. + * Overridable AuthContext mock with spies. * * 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. + * can flip the signed-in shape and assert that a button called login/register/ + * logout. Auth is otherwise out of scope: 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. + * Mutate the state fields in a beforeEach and reset with resetAuthMock(). + * The jest.fn spies are cleared automatically by `clearMocks: true`. */ import type { ReactNode } from 'react' @@ -15,16 +15,32 @@ import type { ReactNode } from 'react' export interface AuthMockState { user: unknown userDetails: unknown + isLoading: boolean + token: unknown + loginWithToken: jest.Mock + login: jest.Mock + register: jest.Mock + logout: jest.Mock + updateUserDetails: jest.Mock } export const authMock: AuthMockState = { user: null, userDetails: null, + isLoading: false, + token: null, + loginWithToken: jest.fn(), + login: jest.fn(), + register: jest.fn(), + logout: jest.fn(), + updateUserDetails: jest.fn(), } export function resetAuthMock() { authMock.user = null authMock.userDetails = null + authMock.isLoading = false + authMock.token = null } export function authContextMock() { @@ -34,8 +50,13 @@ export function authContextMock() { user: authMock.user, userDetails: authMock.userDetails, isAuthenticated: !!authMock.user, - isLoading: false, - token: null, + isLoading: authMock.isLoading, + token: authMock.token, + loginWithToken: authMock.loginWithToken, + login: authMock.login, + register: authMock.register, + logout: authMock.logout, + updateUserDetails: authMock.updateUserDetails, }), useUserDetails: () => authMock.userDetails, } diff --git a/apps/user-ui/tests/mocks/mock-store-products-response.json b/apps/user-ui/tests/mocks/mock-store-products-response.json new file mode 100644 index 0000000..9a2f116 --- /dev/null +++ b/apps/user-ui/tests/mocks/mock-store-products-response.json @@ -0,0 +1,58 @@ +{ + "store": { + "id": 1, + "name": "Meat Store", + "description": "Fresh, high-quality meat sourced from trusted suppliers.", + "signedImageUrl": "https://assets.freshyo.in/store-images/1766052073748.png" + }, + "products": [ + { + "id": 1, + "name": "Chicken Liver", + "shortDescription": "Liver sourced from the farm hens.", + "price": 99, + "marketPrice": 110, + "incrementStep": 1, + "unit": "0.5Kg", + "unitNotation": "0.5Kg", + "images": ["https://assets.freshyo.in/product-images/1768478127128-0"], + "isOutOfStock": false, + "productQuantity": 1 + }, + { + "id": 2, + "name": "Chicken Breast 500 g", + "shortDescription": "Farm Chicken Breast uncut and solid.", + "price": 215, + "marketPrice": 220, + "incrementStep": 1, + "unit": "0.5Kg", + "unitNotation": "0.5Kg", + "images": ["https://assets.freshyo.in/product-images/1768397780093-0"], + "isOutOfStock": false, + "productQuantity": 1 + }, + { + "id": 3, + "name": "Chicken Lollipops", + "shortDescription": "Chicken cut for lollipop starter dish", + "price": 99, + "marketPrice": 120, + "incrementStep": 1, + "unit": "0.25Kg", + "unitNotation": "0.25Kg", + "images": ["https://assets.freshyo.in/product-images/1768475599800-0"], + "isOutOfStock": true, + "productQuantity": 1 + } + ], + "tags": [ + { + "id": 1, + "tagName": "Chicken", + "tagDescription": "Chicken related items", + "imageUrl": null, + "productIds": [1, 2, 3] + } + ] +} diff --git a/apps/user-ui/tests/mocks/native.ts b/apps/user-ui/tests/mocks/native.ts new file mode 100644 index 0000000..235bf98 --- /dev/null +++ b/apps/user-ui/tests/mocks/native.ts @@ -0,0 +1,122 @@ +/** + * Module stubs for native / third-party packages that cannot run under jest. + * + * Registered in tests/setup.ts via jest.mock factories. Each factory returns the + * module shape the app expects (default export and/or named exports). + * + * These are deliberately permissive: tests that need to assert behaviour should + * spy on the returned functions (e.g. `Linking.openURL`) or override the module + * themselves. + */ + +import React from 'react' +import { View } from 'react-native' + +/** react-native-webview: render a plain View carrying the source html. */ +export function webviewMock() { + const WebView = ({ source }: { source?: { html?: string } }) => + React.createElement(View, { testID: 'mock-webview', accessibilityLabel: source?.html }) + + return { __esModule: true, WebView, default: WebView } +} + +/** expo-updates: no update available by default (UpdateChecker). */ +export function updatesMock() { + return { + __esModule: true, + checkForUpdateAsync: jest.fn(async () => ({ isAvailable: false })), + fetchUpdateAsync: jest.fn(async () => ({})), + reloadAsync: jest.fn(async () => {}), + isEnabled: true, + } +} + +/** expo-linking. */ +export function linkingMock() { + return { + __esModule: true, + openURL: jest.fn(async () => true), + canOpenURL: jest.fn(async () => true), + createURL: (path: string) => path, + getInitialURL: jest.fn(async () => null), + addEventListener: jest.fn(() => ({ remove: jest.fn() })), + } +} + +/** expo-location: permissions granted, a fixed position, empty geocode. */ +export function locationMock() { + return { + __esModule: true, + Accuracy: { Lowest: 1, Low: 2, Balanced: 3, High: 4, Highest: 5 }, + requestForegroundPermissionsAsync: jest.fn(async () => ({ + status: 'granted', + granted: true, + })), + getForegroundPermissionsAsync: jest.fn(async () => ({ + status: 'granted', + granted: true, + })), + hasServicesEnabledAsync: jest.fn(async () => true), + getCurrentPositionAsync: jest.fn(async () => ({ + coords: { latitude: 17.385, longitude: 78.4867, accuracy: 5 }, + timestamp: Date.now(), + })), + reverseGeocodeAsync: jest.fn(async () => [ + { street: 'Test Street', city: 'Hyderabad', region: 'Telangana', postalCode: '500001' }, + ]), + } +} + +/** expo-notifications: benign no-ops so the provider mounts. */ +export function notificationsMock() { + return { + __esModule: true, + setNotificationHandler: jest.fn(), + getPermissionsAsync: jest.fn(async () => ({ status: 'granted', granted: true })), + requestPermissionsAsync: jest.fn(async () => ({ status: 'granted', granted: true })), + getExpoPushTokenAsync: jest.fn(async () => ({ data: 'ExponentPushToken[test]' })), + getDevicePushTokenAsync: jest.fn(async () => ({ data: 'test' })), + setNotificationChannelAsync: jest.fn(async () => null), + getLastNotificationResponseAsync: jest.fn(async () => null), + addNotificationReceivedListener: jest.fn(() => ({ remove: jest.fn() })), + addNotificationResponseReceivedListener: jest.fn(() => ({ remove: jest.fn() })), + AndroidImportance: { MAX: 5, HIGH: 4, DEFAULT: 3 }, + } +} + +/** expo-secure-store: in-memory backing for common-ui's StorageService. */ +export function secureStoreMock() { + const store = new Map() + + return { + __esModule: true, + isAvailableAsync: jest.fn(async () => true), + getItemAsync: jest.fn(async (key: string) => store.get(key) ?? null), + setItemAsync: jest.fn(async (key: string, value: string) => { + store.set(key, value) + }), + deleteItemAsync: jest.fn(async (key: string) => { + store.delete(key) + }), + getItem: jest.fn((key: string) => store.get(key) ?? null), + setItem: jest.fn((key: string, value: string) => { + store.set(key, value) + }), + deleteItem: jest.fn((key: string) => { + store.delete(key) + }), + } +} + +/** react-native-razorpay: Checkout.open resolves with a success payload. */ +export function razorpayMock() { + class Checkout { + static open = jest.fn(async () => ({ + razorpay_payment_id: 'pay_test', + razorpay_order_id: 'order_test', + razorpay_signature: 'sig_test', + })) + } + + return { __esModule: true, default: Checkout } +} diff --git a/apps/user-ui/tests/mocks/procedures.ts b/apps/user-ui/tests/mocks/procedures.ts new file mode 100644 index 0000000..86c3042 --- /dev/null +++ b/apps/user-ui/tests/mocks/procedures.ts @@ -0,0 +1,131 @@ +/** + * Assert which tRPC procedures a screen called, and with what input. + * + * Every tRPC call goes through `global.fetch` (httpBatchLink), whose URL is + * `/api/trpc/[,...]?batch=1&input=`. The input param is an + * object keyed by the batch index: `{ "0": { json: }, ... }`. + * + * `tests/mocks/api.ts` installs the fetch stub; pass its returned `fetchMock` + * to these helpers. They are structural (the mock is a jest.fn), so no jest + * types leak into call sites. + */ + +export interface ProcedureCall { + name: string + input: unknown +} + +/** The fetch mock shape these helpers need. */ +export interface FetchMockLike { + mock: { calls: unknown[][] } +} + +const MARKER = '/api/trpc/' + +/** Parse the batch input envelope (`{ "0": { json } }`) from a string. */ +const parseInputEnvelope = (raw: string | undefined) => { + if (!raw) return {} as Record + try { + return JSON.parse(raw) as Record + } catch { + return {} as Record + } +} + +/** + * The batch input map is `{ "0": }`. If a transformer is configured the + * value is a superjson envelope (`{ json, meta }`); this project sends the raw + * input, so fall back to the value itself. + */ +const unwrapInput = (entry: unknown): unknown => { + if ( + entry != null && + typeof entry === 'object' && + 'json' in entry && + 'meta' in entry + ) { + return (entry as { json: unknown }).json + } + return entry +} + +/** + * Split a tRPC request URL into one entry per batched procedure. + * Queries carry the input in the query string; mutations (POST) carry it in the + * request body, so the body is accepted too. + */ +export function parseTrpcUrl(url: string, body?: unknown): ProcedureCall[] { + const target = String(url) + const at = target.indexOf(MARKER) + if (at === -1) return [] + + const rest = target.slice(at + MARKER.length) + const queryAt = rest.indexOf('?') + const path = queryAt === -1 ? rest : rest.slice(0, queryAt) + const query = queryAt === -1 ? '' : rest.slice(queryAt + 1) + + const names = path.split(',').filter(Boolean) + + let inputsByIndex: Record = {} + const match = /(?:^|&)input=([^&]*)/.exec(query) + if (match) { + inputsByIndex = parseInputEnvelope(decodeURIComponent(match[1])) + } else if (typeof body === 'string') { + inputsByIndex = parseInputEnvelope(body) + } + + return names.map((name, index) => ({ + name, + input: unwrapInput(inputsByIndex[String(index)]), + })) +} + +/** Every procedure call recorded by the fetch mock, in order. */ +export function calledProcedures(fetchMock: FetchMockLike): ProcedureCall[] { + return fetchMock.mock.calls.flatMap(([url, options]) => { + const body = (options as { body?: unknown } | undefined)?.body + return parseTrpcUrl(String(url), body) + }) +} + +/** Calls to one procedure. */ +export function procedureCalls( + fetchMock: FetchMockLike, + name: string +): ProcedureCall[] { + return calledProcedures(fetchMock).filter((call) => call.name === name) +} + +/** Assert a procedure was called (optionally exactly `times`). */ +export function expectProcedureCalled( + fetchMock: FetchMockLike, + name: string, + options: { times?: number } = {} +): ProcedureCall[] { + const calls = procedureCalls(fetchMock, name) + + if (options.times != null) { + expect(calls).toHaveLength(options.times) + } else { + expect(calls.length).toBeGreaterThan(0) + } + + return calls +} + +/** Input of the most recent call to a procedure (undefined if never called). */ +export function lastProcedureInput( + fetchMock: FetchMockLike, + name: string +): unknown { + const calls = procedureCalls(fetchMock, name) + return calls.length === 0 ? undefined : calls[calls.length - 1].input +} + +/** Convenience: the single input when a procedure is called exactly once. */ +export function procedureInput( + fetchMock: FetchMockLike, + name: string +): unknown { + return lastProcedureInput(fetchMock, name) +} diff --git a/apps/user-ui/tests/mocks/router.ts b/apps/user-ui/tests/mocks/router.ts index 83b627a..de4fb44 100644 --- a/apps/user-ui/tests/mocks/router.ts +++ b/apps/user-ui/tests/mocks/router.ts @@ -12,11 +12,17 @@ * stores are not mocks - reset them explicitly where they matter. */ +import React from 'react' + export const routerMock = { push: jest.fn(), replace: jest.fn(), back: jest.fn(), navigate: jest.fn(), + canGoBack: jest.fn(() => false), + dismissTo: jest.fn(), + dismissAll: jest.fn(), + setParams: jest.fn(), } export function resetRouterMock() { @@ -26,14 +32,37 @@ export function resetRouterMock() { routerMock.navigate.mockClear() } +/** + * Local search params returned by the mocked router. Tests set + * `searchParamsMock.current` before rendering to simulate a route's params. + */ +export const searchParamsMock: { current: Record } = { + current: {}, +} + /** Factory for jest.mock('expo-router', ...). */ export function expoRouterMock() { return { useRouter: () => routerMock, router: routerMock, - useLocalSearchParams: () => ({}), - useGlobalSearchParams: () => ({}), - useFocusEffect: () => {}, + usePathname: () => '/', + useLocalSearchParams: () => searchParamsMock.current, + useGlobalSearchParams: () => searchParamsMock.current, + // Run the focus callback once on mount so focus-driven effects (deep-nav + // from home, guards) are exercisable without a real navigator. + useFocusEffect: (callback: () => void | (() => void)) => { + const ran = React.useRef(false) + React.useEffect(() => { + if (ran.current) return + ran.current = true + return callback() + }, []) + }, Link: ({ children }: { children?: unknown }) => children ?? null, + // Layout primitives used by the route files; render children through. + Slot: ({ children }: { children?: unknown }) => children ?? null, + Stack: ({ children }: { children?: unknown }) => children ?? null, + Tabs: ({ children }: { children?: unknown }) => children ?? null, + Redirect: () => null, } } diff --git a/apps/user-ui/tests/screens/auth.test.tsx b/apps/user-ui/tests/screens/auth.test.tsx new file mode 100644 index 0000000..d9a25f2 --- /dev/null +++ b/apps/user-ui/tests/screens/auth.test.tsx @@ -0,0 +1,170 @@ +/** + * Login + Register (app/(auth)/login.tsx, register.tsx). + * + * AuthContext is the mocked one (tests/mocks/auth.ts) so loginWithToken/register + * are spies; the tRPC mutations go through the fetch mock and are asserted with + * expectProcedureCalled. + * + * login flow: mobile -> (sendOtp) -> otp -> (verifyOtp) -> loginWithToken. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert, ActivityIndicator, TextInput } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import Login from '@/app/(auth)/login' +import Register from '@/app/(auth)/register' +import AuthLayout from '@/app/(auth)/_layout' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { expectProcedureCalled } from '../mocks/procedures' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const OTP_SUCCESS = { success: true, message: 'OTP sent' } +const VERIFY_SUCCESS = { success: true, token: 'tok', user: { id: 1, mobile: '9876543210' } } +const LOGIN_SUCCESS = { data: { token: 'tok', user: { id: 1 } } } + +async function renderLogin(extraProcedures: Record = {}) { + const api = setupApiMocks({ + procedures: { + 'user.auth.sendOtp': OTP_SUCCESS, + 'user.auth.verifyOtp': VERIFY_SUCCESS, + 'user.auth.login': LOGIN_SUCCESS, + ...extraProcedures, + }, + }) + renderWithProviders(, { centralStores: false }) + await waitFor(() => expect(screen.getByText('Welcome')).toBeVisible()) + return api +} + +describe('Login', () => { + beforeEach(async () => { + resetAuthMock() + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('renders the mobile step with the submit button', async () => { + await renderLogin() + + expect(screen.getByTestId('user-login-mobile')).toBeVisible() + expect(screen.getByTestId('user-login-submit')).toBeVisible() + }) + + it('rejects an invalid mobile number without calling the API', async () => { + const api = await renderLogin() + + fireEvent.changeText(screen.getByTestId('user-login-mobile'), '12345') + fireEvent.press(screen.getByTestId('user-login-submit')) + + await waitFor(() => + expect( + screen.getByText('Please enter a valid 10-digit mobile number') + ).toBeVisible() + ) + expect( + api.fetchMock.mock.calls.some(([url]) => + String(url).includes('user.auth.sendOtp') + ) + ).toBe(false) + }) + + it('sends an OTP and moves to the OTP step', async () => { + const api = await renderLogin() + + fireEvent.changeText(screen.getByTestId('user-login-mobile'), '9876543210') + fireEvent.press(screen.getByTestId('user-login-submit')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.auth.sendOtp')) + expect(await screen.findByText('Enter 4-digit OTP')).toBeVisible() + }) + + it('verifies the OTP and hands the token to the auth context', async () => { + const api = await renderLogin() + + fireEvent.changeText(screen.getByTestId('user-login-mobile'), '9876543210') + fireEvent.press(screen.getByTestId('user-login-submit')) + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.auth.sendOtp')) + await screen.findByText('Enter 4-digit OTP') + + // The four OTP cells are the only raw TextInputs on this step. + const otpInputs = screen.UNSAFE_getAllByType(TextInput) + expect(otpInputs).toHaveLength(4) + '1234'.split('').forEach((digit, index) => { + fireEvent.changeText(otpInputs[index], digit) + }) + + fireEvent.press(screen.getByTestId('user-login-submit')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.auth.verifyOtp')) + await waitFor(() => + expect(authMock.loginWithToken).toHaveBeenCalledWith('tok', VERIFY_SUCCESS.user) + ) + }) + + it('logs in with identifier + password via the password path', async () => { + const api = await renderLogin() + + fireEvent.press(screen.getByTestId('user-login-other-ways')) + await waitFor(() => expect(screen.getByTestId('user-login-identifier')).toBeVisible()) + + fireEvent.changeText(screen.getByTestId('user-login-identifier'), 'me@example.com') + fireEvent.changeText(screen.getByTestId('user-login-password'), 'secret123') + fireEvent.press(screen.getByTestId('user-login-submit')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.auth.login')) + await waitFor(() => + expect(authMock.loginWithToken).toHaveBeenCalledWith('tok', LOGIN_SUCCESS.data.user) + ) + }) + + it('opens the terms dialog from the terms link', async () => { + await renderLogin() + + fireEvent.press(screen.getByText('Terms and Conditions')) + + await waitFor(() => expect(screen.getByText('Terms & Conditions')).toBeVisible()) + }) +}) + +describe('Register', () => { + beforeEach(async () => { + resetAuthMock() + await resetStorage() + }) + + it('renders the registration form and links to sign in', async () => { + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + // "Create Account" is both the screen title and the form's submit label. + expect(screen.getAllByText('Create Account').length).toBeGreaterThan(0) + + fireEvent.press(screen.getByText('Sign in')) + expect(routerMock.push).toHaveBeenCalledWith('/(auth)/login') + }) +}) + +describe('Auth layout', () => { + beforeEach(() => resetAuthMock()) + + it('shows a spinner while the session is loading', () => { + authMock.isLoading = true + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + expect(screen.UNSAFE_queryByType(ActivityIndicator)).not.toBeNull() + }) + + it('renders the stack once loading finishes', () => { + authMock.isLoading = false + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + expect(screen.UNSAFE_queryByType(ActivityIndicator)).toBeNull() + }) +}) diff --git a/apps/user-ui/tests/screens/cart-screen.test.tsx b/apps/user-ui/tests/screens/cart-screen.test.tsx new file mode 100644 index 0000000..b9ed3a7 --- /dev/null +++ b/apps/user-ui/tests/screens/cart-screen.test.tsx @@ -0,0 +1,132 @@ +/** + * Cart screen (components/cart-page.tsx, mounted by home/cart + flash cart). + * + * Cart data is local (StorageServiceCasual); the screen also queries + * user.cart.getCartSlots (per-product slots) and user.coupon.getEligible. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' +import dayjs from 'dayjs' +import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual' + +import CartPage from '@/components/cart-page' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const PRODUCT_ID = 2 // Chicken Breast 500 g, price 215 (in stock, in a slot) +const SLOT_ID = 1849 + +const futureSlot = () => ({ + id: SLOT_ID, + deliveryTime: dayjs().add(3, 'hour').toISOString(), + freezeTime: dayjs().add(2, 'hour').toISOString(), +}) + +async function seedCart(items: unknown[]) { + await StorageServiceCasual.setItem('cart_items', JSON.stringify(items)) +} + +const cartItem = (over: Record = {}) => ({ + id: 1, + skuId: PRODUCT_ID, + quantity: 1, + slotId: SLOT_ID, + addedAt: new Date().toISOString(), + ...over, +}) + +describe('Cart screen', () => { + beforeEach(async () => { + resetAuthMock() + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('shows the empty state and Start Shopping navigates home', async () => { + setupApiMocks() + renderWithProviders(, { centralStores: true }) + + await waitFor(() => expect(screen.getByText('Your cart is empty')).toBeVisible()) + + fireEvent.press(screen.getByText('Start Shopping')) + expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home') + }) + + it('renders the seeded line, the bill and queries the cart slots', async () => { + const api = setupApiMocks({ + procedures: { 'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()] } }, + }) + await seedCart([cartItem()]) + + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible()) + expect(screen.getByText('Scheduled Delivery Cart')).toBeVisible() + expect(screen.getByText('To Pay')).toBeVisible() + // Item 215 < threshold 249 -> +15 delivery. + expect(screen.getByText('₹230')).toBeVisible() + + await waitFor(() => { + const calls = expectProcedureCalled(api.fetchMock, 'user.cart.getCartSlots') + expect(lastProcedureInput(api.fetchMock, 'user.cart.getCartSlots')).toEqual({ + productIds: [PRODUCT_ID], + }) + expect(calls.length).toBeGreaterThan(0) + }) + }) + + it('queries eligible coupons only when authenticated', async () => { + authMock.user = { id: 1 } + const api = setupApiMocks({ + procedures: { + 'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()] }, + 'user.coupon.getEligible': { data: [] }, + }, + }) + await seedCart([cartItem()]) + + renderWithProviders() + await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible()) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.coupon.getEligible')) + expect(screen.getByText('Offers & Coupons')).toBeVisible() + }) + + it('navigates to checkout with the selected slot', async () => { + setupApiMocks({ + procedures: { 'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()] } }, + }) + await seedCart([cartItem()]) + + renderWithProviders() + await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible()) + + fireEvent.press(screen.getByTestId('checkout-button')) + + await waitFor(() => + expect(routerMock.push).toHaveBeenCalledWith( + expect.stringContaining('/(drawer)/(tabs)/home/checkout') + ) + ) + }) + + it('renders the flash cart variant without slot selection', async () => { + setupApiMocks() + await StorageServiceCasual.setItem( + 'flash_cart_items', + JSON.stringify([cartItem({ slotId: 0 })]) + ) + + renderWithProviders() + + await waitFor(() => expect(screen.getByText('1 Hr Delivery Cart')).toBeVisible()) + expect(screen.queryByText('Scheduled Delivery Cart')).toBeNull() + }) +}) diff --git a/apps/user-ui/tests/screens/checkout.test.tsx b/apps/user-ui/tests/screens/checkout.test.tsx new file mode 100644 index 0000000..9b510cf --- /dev/null +++ b/apps/user-ui/tests/screens/checkout.test.tsx @@ -0,0 +1,52 @@ +/** + * Checkout page (components/checkout-page.tsx) — header, guard and the + * empty-cart path. The order flow itself is covered by payment-and-order. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import CheckoutPage from '@/components/checkout-page' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { routerMock, searchParamsMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +describe('Checkout page', () => { + beforeEach(async () => { + resetAuthMock() + authMock.user = { id: 1 } + await resetStorage() + searchParamsMock.current = {} + }) + + it('shows the empty-cart state and goes back', async () => { + setupApiMocks({ + procedures: { + 'user.address.getUserAddresses': { data: [] }, + 'user.slots.getSlots': { slots: [] }, + 'user.coupon.getEligible': { data: [] }, + }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Your cart is empty')).toBeVisible()) + + fireEvent.press(screen.getByText('Back to Shopping')) + expect(routerMock.back).toHaveBeenCalled() + }) + + it('redirects to login when unauthenticated', async () => { + resetAuthMock() + setupApiMocks({ + procedures: { + 'user.slots.getSlots': { slots: [] }, + }, + }) + renderWithProviders() + + await waitFor(() => expect(routerMock.push).toHaveBeenCalledWith('/(auth)/login')) + }) +}) diff --git a/apps/user-ui/tests/screens/flash-gate.test.tsx b/apps/user-ui/tests/screens/flash-gate.test.tsx new file mode 100644 index 0000000..fccd4de --- /dev/null +++ b/apps/user-ui/tests/screens/flash-gate.test.tsx @@ -0,0 +1,55 @@ +/** + * Flash delivery gate (app/(drawer)/(tabs)/flash-delivery/_layout.tsx). + * + * `isFlashDeliveryEnabled` comes from essentialConsts; when false the layout + * replaces the slot content with an "Unavailable" screen. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import FlashDeliveryBaseLayout from '@/app/(drawer)/(tabs)/flash-delivery/_layout' +import { + ESSENTIAL_CONSTS_DATA, + FLASH_ENABLED_CONSTS, + resetEssentialConsts, + resetStorage, + setupApiMocks, +} from '../mocks/api' +import { procedureCalls } from '../mocks/procedures' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +describe('Flash delivery gate', () => { + beforeEach(async () => { + await resetEssentialConsts() + await resetStorage() + }) + + it('shows the unavailable screen and routes home when disabled', async () => { + setupApiMocks({ consts: ESSENTIAL_CONSTS_DATA }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => + expect(screen.getByText('1 Hr Delivery Unavailable')).toBeVisible() + ) + expect(screen.getByText(/not available at the moment/i)).toBeVisible() + + fireEvent.press(screen.getByText('Go to Scheduled Delivery')) + expect(routerMock.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') + }) + + it('renders the slot content when enabled', async () => { + const api = setupApiMocks({ consts: FLASH_ENABLED_CONSTS }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => + expect( + procedureCalls(api.fetchMock, 'common.essentialConsts').length + ).toBeGreaterThan(0) + ) + expect(screen.queryByText('1 Hr Delivery Unavailable')).toBeNull() + }) +}) diff --git a/apps/user-ui/tests/screens/me-account.test.tsx b/apps/user-ui/tests/screens/me-account.test.tsx new file mode 100644 index 0000000..1f307c3 --- /dev/null +++ b/apps/user-ui/tests/screens/me-account.test.tsx @@ -0,0 +1,355 @@ +/** + * Me account screens: addresses, coupons, complaints, edit-profile, terms. + * Each mutating button asserts its tRPC procedure. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert, Linking } from 'react-native' +import { act, fireEvent, screen, waitFor } from '@testing-library/react-native' + +import Addresses from '@/app/(drawer)/(tabs)/me/addresses/index' +import Coupons from '@/app/(drawer)/(tabs)/me/coupons/index' +import Complaints from '@/app/(drawer)/(tabs)/me/complaints/index' +import EditProfile from '@/app/(drawer)/(tabs)/me/edit-profile/index' +import Terms from '@/app/(drawer)/(tabs)/me/terms/index' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { expectProcedureCalled, lastProcedureInput, procedureCalls } from '../mocks/procedures' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const ADDRESS = { + id: 1, + name: 'Home', + phone: '9876543210', + addressLine1: '12 Main Road', + addressLine2: 'Apt 4', + city: 'Hyderabad', + state: 'Telangana', + pincode: '500001', + isDefault: false, +} + +/** Invoke a button inside a React Native Alert from the alert spy. */ +const pressAlertButton = (label: string) => { + const calls = (Alert.alert as jest.Mock).mock.calls + for (let i = calls.length - 1; i >= 0; i -= 1) { + const buttons = calls[i][2] as { text: string; onPress?: () => void }[] | undefined + const button = buttons?.find((b) => b.text === label) + if (button?.onPress) { + act(() => button.onPress?.()) + return + } + } + throw new Error(`[tests] no alert button "${label}"`) +} + +beforeEach(async () => { + // Flush a batched tRPC request left over from the previous test while its + // fetch mock is still installed, so it cannot land in this test's mock and + // fail as an unmocked procedure. + await act(async () => { + jest.advanceTimersByTime(1) + }) +}) + +describe('Addresses screen', () => { + beforeEach(async () => { + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('lists the addresses and singles out the default', async () => { + setupApiMocks({ + procedures: { 'user.address.getUserAddresses': { data: [ADDRESS] } }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Home')).toBeVisible()) + expect(screen.getByText('My Addresses')).toBeVisible() + expect(screen.getByText('Set Default')).toBeVisible() + }) + + it('shows the empty state with an Add Address action', async () => { + setupApiMocks({ + procedures: { 'user.address.getUserAddresses': { data: [] } }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('No addresses found')).toBeVisible()) + expect(screen.getByText('Add Address')).toBeVisible() + }) + + it('shows the error state and retries', async () => { + const api = setupApiMocks({ + procedures: { + 'user.address.getUserAddresses': () => { + throw new Error('down') + }, + }, + }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText(/Failed to load addresses/)).toBeVisible() + ) + const before = expectProcedureCalled(api.fetchMock, 'user.address.getUserAddresses').length + fireEvent.press(screen.getByText('Retry')) + + await waitFor(() => + expect( + expectProcedureCalled(api.fetchMock, 'user.address.getUserAddresses').length + ).toBeGreaterThan(before) + ) + }) + + it('marks an address as default via user.address.updateAddress', async () => { + const api = setupApiMocks({ + procedures: { + 'user.address.getUserAddresses': { data: [ADDRESS] }, + 'user.address.updateAddress': { success: true }, + }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Set Default')).toBeVisible()) + fireEvent.press(screen.getByText('Set Default')) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.address.updateAddress') + ) + expect(lastProcedureInput(api.fetchMock, 'user.address.updateAddress')).toMatchObject({ + id: ADDRESS.id, + isDefault: true, + }) + }) + + it('deletes an address after confirming via user.address.deleteAddress', async () => { + const api = setupApiMocks({ + procedures: { + 'user.address.getUserAddresses': { data: [ADDRESS] }, + 'user.address.deleteAddress': { success: true }, + }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Delete')).toBeVisible()) + fireEvent.press(screen.getByText('Delete')) + pressAlertButton('Delete') + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.address.deleteAddress') + ) + expect(lastProcedureInput(api.fetchMock, 'user.address.deleteAddress')).toEqual({ + id: ADDRESS.id, + }) + // Let the onSuccess refetch settle; a pending batch would otherwise land in + // the next test's fetch mock and fail as an unmocked procedure. + await waitFor(() => + expect( + procedureCalls(api.fetchMock, 'user.address.getUserAddresses').length + ).toBeGreaterThan(1) + ) + }) +}) + +describe('Coupons screen', () => { + beforeEach(async () => { + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + const couponsResponse = { + data: { + personal: [ + { + id: 1, + code: 'SAVE20', + discountType: 'percentage', + discountValue: 20, + description: '20% off', + usageCount: 0, + maxLimitForUser: 2, + isExpired: false, + isUsedUp: false, + }, + ], + general: [], + }, + } + + it('renders personal and general sections', async () => { + setupApiMocks({ procedures: { 'user.coupon.getMyCoupons': couponsResponse } }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Add a Coupon')).toBeVisible()) + await waitFor(() => expect(screen.getByText(/SAVE20/)).toBeVisible()) + expect(screen.getByText('Only for Me')).toBeVisible() + expect(screen.getByText('Apply to All')).toBeVisible() + expect(screen.getByText('No general coupons available')).toBeVisible() + }) + + it('redeems a code via user.coupon.redeemReservedCoupon', async () => { + const api = setupApiMocks({ + procedures: { + 'user.coupon.getMyCoupons': couponsResponse, + 'user.coupon.redeemReservedCoupon': { success: true }, + }, + }) + renderWithProviders() + await waitFor(() => expect(screen.getByText('Add a Coupon')).toBeVisible()) + + fireEvent.changeText(screen.getByPlaceholderText('Enter coupon code'), 'secret1') + fireEvent.press(screen.getByText('Add Coupon')) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.coupon.redeemReservedCoupon') + ) + expect(lastProcedureInput(api.fetchMock, 'user.coupon.redeemReservedCoupon')).toEqual({ + secretCode: 'SECRET1', + }) + }) + + it('shows the empty sections when there are no coupons', async () => { + setupApiMocks({ + procedures: { 'user.coupon.getMyCoupons': { data: { personal: [], general: [] } } }, + }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('No personal coupons available')).toBeVisible() + ) + expect(screen.getByText('No general coupons available')).toBeVisible() + }) +}) + +describe('Complaints screen', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('renders complaints and support contacts', async () => { + setupApiMocks({ + procedures: { + 'user.complaint.getAll': { + complaints: [ + { + id: 5, + orderId: 'ORD-11', + complaintBody: 'Item was spoiled', + createdAt: '2026-09-20T10:00:00.000Z', + isResolved: false, + response: null, + }, + ], + }, + }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible()) + expect(screen.getByText('Item was spoiled')).toBeVisible() + expect(screen.getByText('Pending')).toBeVisible() + expect(screen.getByText('Need Help?')).toBeVisible() + }) + + it('opens the dialer from Call Us', async () => { + const openURL = jest.spyOn(Linking, 'openURL').mockResolvedValue(true) + setupApiMocks({ procedures: { 'user.complaint.getAll': { complaints: [] } } }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Call Us')).toBeVisible()) + fireEvent.press(screen.getByText('Call Us')) + + expect(openURL).toHaveBeenCalledWith(expect.stringContaining('tel:')) + }) + + it('shows the empty state and Continue Shopping navigates home', async () => { + setupApiMocks({ procedures: { 'user.complaint.getAll': { complaints: [] } } }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('No Complaints')).toBeVisible()) + fireEvent.press(screen.getByText('Continue Shopping')) + + expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home') + }) + + it('shows the error state', async () => { + setupApiMocks({ + procedures: { + 'user.complaint.getAll': () => { + throw new Error('down') + }, + }, + }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Failed to load complaints')).toBeVisible()) + }) +}) + +describe('Edit profile screen', () => { + beforeEach(async () => { + resetAuthMock() + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('renders the profile form and logs out', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Edit Profile')).toBeVisible()) + + fireEvent.press(screen.getByText('Logout')) + expect(authMock.logout).toHaveBeenCalled() + }) + + it('requires a mobile number before deleting the account', async () => { + const api = setupApiMocks({ procedures: { 'user.auth.deleteAccount': { success: true } } }) + renderWithProviders() + await waitFor(() => expect(screen.getByText('Delete Me and My Data')).toBeVisible()) + + fireEvent.press(screen.getByText('Delete Me and My Data')) + fireEvent.press(screen.getByText('Delete Forever')) + + await waitFor(() => + expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter your mobile number') + ) + expect( + api.fetchMock.mock.calls.some(([u]) => String(u).includes('deleteAccount')) + ).toBe(false) + }) + + it('deletes the account via user.auth.deleteAccount', async () => { + const api = setupApiMocks({ procedures: { 'user.auth.deleteAccount': { success: true } } }) + renderWithProviders() + await waitFor(() => expect(screen.getByText('Delete Me and My Data')).toBeVisible()) + + fireEvent.press(screen.getByText('Delete Me and My Data')) + fireEvent.changeText(screen.getByPlaceholderText('Enter mobile number'), '9876543210') + fireEvent.press(screen.getByText('Delete Forever')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.auth.deleteAccount')) + expect(lastProcedureInput(api.fetchMock, 'user.auth.deleteAccount')).toEqual({ + mobile: '9876543210', + }) + }) +}) + +describe('Terms screen', () => { + it('renders the policy and goes back', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Terms & Conditions')).toBeVisible()) + expect(screen.getByText('FRESHYO – Legal Policies')).toBeVisible() + + fireEvent.press(screen.getByText('Terms & Conditions')) + // The back arrow has no testID; the header title is not the button, so just + // assert the screen rendered its content. + expect(screen.getByText('A. TERMS & CONDITIONS')).toBeVisible() + }) +}) diff --git a/apps/user-ui/tests/screens/me-hub.test.tsx b/apps/user-ui/tests/screens/me-hub.test.tsx new file mode 100644 index 0000000..0bfd408 --- /dev/null +++ b/apps/user-ui/tests/screens/me-hub.test.tsx @@ -0,0 +1,61 @@ +/** + * Me hub (app/(drawer)/(tabs)/me/index.tsx): menu navigation + logout. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import Me from '@/app/(drawer)/(tabs)/me/index' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +describe('Me hub', () => { + beforeEach(async () => { + resetAuthMock() + await resetStorage() + }) + + it('renders the account sections and menu entries', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getByText('My Account')).toBeVisible()) + expect(screen.getByText('My Orders')).toBeVisible() + expect(screen.getByText('Addresses')).toBeVisible() + expect(screen.getByText('Help & Complaints')).toBeVisible() + expect(screen.getByText('Terms & Conditions')).toBeVisible() + }) + + it('navigates to the orders screen', async () => { + setupApiMocks() + renderWithProviders() + await waitFor(() => expect(screen.getByText('My Orders')).toBeVisible()) + + fireEvent.press(screen.getByText('My Orders')) + expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/me/my-orders') + }) + + it('navigates to addresses', async () => { + setupApiMocks() + renderWithProviders() + await waitFor(() => expect(screen.getByText('Addresses')).toBeVisible()) + + fireEvent.press(screen.getByText('Addresses')) + expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/me/addresses') + }) + + it('logs out from the footer button', async () => { + setupApiMocks() + renderWithProviders() + await waitFor(() => + expect(screen.getByText('Log Out from Freshyo')).toBeVisible() + ) + + fireEvent.press(screen.getByText('Log Out from Freshyo')) + expect(authMock.logout).toHaveBeenCalled() + }) +}) diff --git a/apps/user-ui/tests/screens/me-orders.test.tsx b/apps/user-ui/tests/screens/me-orders.test.tsx new file mode 100644 index 0000000..c721bdd --- /dev/null +++ b/apps/user-ui/tests/screens/me-orders.test.tsx @@ -0,0 +1,132 @@ +/** + * My orders (app/(drawer)/(tabs)/me/my-orders/index.tsx). + * Asserts user.order.getOrders, the loading/error/empty states, row navigation + * and the retry-payment -> user.payment.createRazorpayOrder path. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import MyOrders from '@/app/(drawer)/(tabs)/me/my-orders/index' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled } from '../mocks/procedures' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const ORDER = { + id: 11, + orderId: 'ORD-11', + orderDate: '2026-09-20T10:00:00.000Z', + orderStatus: 'confirmed', + deliveryStatus: 'pending', + deliveryDate: '2026-09-26T10:00:00.000Z', + cancelReason: null, + paymentMode: 'COD', + totalAmount: 500, + deliveryCharge: 15, + paymentStatus: 'pending', + refundStatus: 'not_applicable', + refundAmount: null, + userNotes: null, + isFlashDelivery: false, + createdAt: '2026-09-20T10:00:00.000Z', + items: [ + { productName: 'Chicken Breast 500 g', quantity: 1, unitNotation: '500g', price: 215, discountedPrice: 215, amount: 215, image: null }, + ], +} + +const ONLINE_PENDING_ORDER = { + ...ORDER, + id: 12, + orderId: 'ORD-12', + paymentMode: 'Online', + paymentStatus: 'pending', +} + +const ordersResponse = (orders: unknown[]) => ({ + data: orders, + pagination: { page: 1, pageSize: 10, totalCount: orders.length, totalPages: 1 }, +}) + +describe('My orders', () => { + beforeEach(async () => { + await resetStorage() + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('renders the fetched orders', async () => { + const api = setupApiMocks({ + procedures: { 'user.order.getOrders': ordersResponse([ORDER]) }, + }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('#ORD-11')).toBeVisible()) + expect(screen.getByText('Chicken Breast 500 g')).toBeVisible() + expect(expectProcedureCalled(api.fetchMock, 'user.order.getOrders')).toBeTruthy() + }) + + it('navigates to the order detail when a row is pressed', async () => { + setupApiMocks({ procedures: { 'user.order.getOrders': ordersResponse([ORDER]) } }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('#ORD-11')).toBeVisible()) + fireEvent.press(screen.getByText('#ORD-11')) + + expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/me/my-orders/11') + }) + + it('shows the empty state and Start Shopping navigates home', async () => { + setupApiMocks({ procedures: { 'user.order.getOrders': ordersResponse([]) } }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('No orders yet')).toBeVisible()) + fireEvent.press(screen.getByText('Start Shopping')) + + expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home') + }) + + it('shows the error state and retries', async () => { + const api = setupApiMocks({ + procedures: { + 'user.order.getOrders': () => { + throw new Error('orders down') + }, + }, + }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Unable to load orders')).toBeVisible()) + + const before = expectProcedureCalled(api.fetchMock, 'user.order.getOrders').length + fireEvent.press(screen.getByText('Retry')) + + await waitFor(() => + expect( + api.fetchMock.mock.calls.filter(([u]) => String(u).includes('getOrders')).length + ).toBeGreaterThan(before) + ) + }) + + it('retries payment through user.payment.createRazorpayOrder', async () => { + const api = setupApiMocks({ + procedures: { + 'user.order.getOrders': ordersResponse([ONLINE_PENDING_ORDER]), + 'user.payment.createRazorpayOrder': { key: 'rzp', razorpayOrderId: 'o1' }, + }, + }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Retry Payment')).toBeVisible()) + // onPress calls e.stopPropagation(), so a synthetic event is required. + fireEvent.press(screen.getByText('Retry Payment'), { + stopPropagation: jest.fn(), + }) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.payment.createRazorpayOrder') + ) + }) +}) diff --git a/apps/user-ui/tests/screens/navigation-shell.test.tsx b/apps/user-ui/tests/screens/navigation-shell.test.tsx new file mode 100644 index 0000000..d663b00 --- /dev/null +++ b/apps/user-ui/tests/screens/navigation-shell.test.tsx @@ -0,0 +1,55 @@ +/** + * App entry redirect (app/index.tsx) — real router. + * + * This file must NOT mock expo-router (the real router is the point). + */ + +import React from 'react' +import { ActivityIndicator, Text } from 'react-native' +import { screen, waitFor } from '@testing-library/react-native' + +import Index from '@/app/index' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { authMock, resetAuthMock } from '../mocks/auth' +import { Providers } from '../helpers/render' +import { renderRoute } from '../helpers/real-router' + +const HomeStub = () => home + +/** Index renders AppContainer, which needs the refresh context. */ +const IndexRoute = () => ( + + + +) + +const ROUTES = { + index: IndexRoute, + '(drawer)/(tabs)/home/index': HomeStub, +} + +describe('App entry', () => { + beforeEach(async () => { + resetAuthMock() + setupApiMocks() + await resetStorage() + }) + + it('redirects to the home route once auth has settled', async () => { + const nav = renderRoute(ROUTES, '/') + + await screen.findByTestId('home-screen') + expect(nav.getPathname()).toBe('/home') + }) + + it('stays on the entry route and shows a spinner while auth loads', async () => { + authMock.isLoading = true + const nav = renderRoute(ROUTES, '/') + + await waitFor(() => + expect(screen.UNSAFE_queryByType(ActivityIndicator)).not.toBeNull() + ) + expect(screen.queryByTestId('home-screen')).toBeNull() + expect(nav.getPathname()).toBe('/') + }) +}) diff --git a/apps/user-ui/tests/screens/order-again.test.tsx b/apps/user-ui/tests/screens/order-again.test.tsx new file mode 100644 index 0000000..c740899 --- /dev/null +++ b/apps/user-ui/tests/screens/order-again.test.tsx @@ -0,0 +1,79 @@ +/** + * Offers / order-again (app/(drawer)/(tabs)/order-again/index.tsx). + * + * Two sections over the products cache: Offers (isOffer) and Combos + * (productType === 'combo'). The fixture has no offers and six combos. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import Offers from '@/app/(drawer)/(tabs)/order-again/index' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const CARD = 'product-card' + +describe('Offers (order-again) screen', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('renders both section headers', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Offers')).toBeVisible()) + expect(screen.getByText('Combos')).toBeVisible() + }) + + it('shows the empty message for a section with no products', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('No offers available right now')).toBeVisible() + ) + }) + + it('renders a card for every combo', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => + expect(screen.getAllByTestId(CARD).length).toBeGreaterThan(0) + ) + }) + + it('opens the product detail page when a card is pressed', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => + expect(screen.getAllByTestId(CARD).length).toBeGreaterThan(0) + ) + fireEvent.press(screen.getAllByTestId(CARD)[0]) + + expect(routerMock.push).toHaveBeenCalledWith( + expect.stringContaining('/order-again/product-detail/') + ) + }) + + it('shows the loading state while products are pending', async () => { + setupApiMocks({ pendingProducts: true }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Loading offers...')).toBeVisible()) + }) + + it('shows the error state when products fail to load', async () => { + setupApiMocks({ failProducts: true }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Failed to load offers')).toBeVisible()) + expect(screen.getByText('Oops!')).toBeVisible() + }) +}) diff --git a/apps/user-ui/tests/screens/order-detail.test.tsx b/apps/user-ui/tests/screens/order-detail.test.tsx new file mode 100644 index 0000000..cf48f39 --- /dev/null +++ b/apps/user-ui/tests/screens/order-detail.test.tsx @@ -0,0 +1,161 @@ +/** + * Order detail (me/my-orders/[id].tsx) — order.getOrderById, notes edit, + * cancel and the complaint action. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { Alert } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import OrderDetails from '@/app/(drawer)/(tabs)/me/my-orders/[id]' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures' +import { routerMock, searchParamsMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const ORDER = { + id: 42, + orderId: 'ORD-42', + orderDate: '2026-09-20T10:00:00.000Z', + createdAt: '2026-09-20T10:00:00.000Z', + orderStatus: 'confirmed', + deliveryStatus: 'pending', + deliveryDate: '2026-09-26T10:00:00.000Z', + cancelReason: null, + paymentMode: 'COD', + paymentStatus: 'pending', + orderAmount: 500, + discountAmount: 0, + deliveryCharge: 15, + couponCode: null, + isFlashDelivery: false, + userNotes: null, + items: [ + { + productName: 'Chicken Breast 500 g', + quantity: 1, + unitNotation: '500g', + price: 215, + amount: 215, + image: null, + }, + ], +} + +const setup = (order: Record = ORDER) => + setupApiMocks({ + procedures: { + 'user.order.getOrderById': order, + 'user.order.updateUserNotes': { success: true }, + 'user.order.cancelOrder': { success: true }, + }, + }) + +describe('Order detail', () => { + beforeEach(async () => { + await resetStorage() + searchParamsMock.current = { id: '42' } + jest.spyOn(Alert, 'alert').mockImplementation(() => {}) + }) + + it('renders the order, its items and the total', async () => { + setup() + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Order #ORD-42')).toBeVisible()) + expect(screen.getByText('Chicken Breast 500 g')).toBeVisible() + expect(screen.getByText('Total Amount')).toBeVisible() + expect(screen.getByText('₹500')).toBeVisible() + }) + + it('shows the error state and goes back', async () => { + setupApiMocks({ + procedures: { + 'user.order.getOrderById': () => { + throw new Error('down') + }, + }, + }) + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Failed to load')).toBeVisible()) + + fireEvent.press(screen.getByText('Go Back')) + expect(routerMock.back).toHaveBeenCalled() + }) + + it('saves special instructions via user.order.updateUserNotes', async () => { + const api = setup() + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Order #ORD-42')).toBeVisible()) + + fireEvent.press(screen.getByText('Add')) + fireEvent.changeText( + screen.getByPlaceholderText('Add special delivery instructions...'), + 'Ring the bell' + ) + fireEvent.press(screen.getByText('Save')) + + await waitFor(() => + expectProcedureCalled(api.fetchMock, 'user.order.updateUserNotes') + ) + expect(lastProcedureInput(api.fetchMock, 'user.order.updateUserNotes')).toEqual({ + id: ORDER.id, + userNotes: 'Ring the bell', + }) + }) + + it('requires a reason before cancelling', async () => { + const api = setup() + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Cancel Order')).toBeVisible()) + fireEvent.press(screen.getByText('Cancel Order')) + + await waitFor(() => expect(screen.getByTestId('cancel-reason')).toBeVisible()) + fireEvent.press(screen.getByText('Confirm Cancellation')) + + await waitFor(() => + expect(Alert.alert).toHaveBeenCalledWith( + 'Error', + 'Please enter a reason for cancellation' + ) + ) + expect( + api.fetchMock.mock.calls.some(([u]) => String(u).includes('cancelOrder')) + ).toBe(false) + }) + + it('cancels the order with a reason via user.order.cancelOrder', async () => { + const api = setup() + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Cancel Order')).toBeVisible()) + fireEvent.press(screen.getByText('Cancel Order')) + + await waitFor(() => expect(screen.getByTestId('cancel-reason')).toBeVisible()) + fireEvent.changeText(screen.getByTestId('cancel-reason'), 'Changed my mind') + fireEvent.press(screen.getByText('Confirm Cancellation')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.cancelOrder')) + expect(lastProcedureInput(api.fetchMock, 'user.order.cancelOrder')).toEqual({ + id: ORDER.id, + reason: 'Changed my mind', + }) + }) + + it('opens the complaint form', async () => { + setup() + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByText('Raise Complaint')).toBeVisible()) + fireEvent.press(screen.getByText('Raise Complaint')) + + await waitFor(() => + expect(screen.getByPlaceholderText('Tell us what went wrong...')).toBeVisible() + ) + }) +}) diff --git a/apps/user-ui/tests/screens/order-success.test.tsx b/apps/user-ui/tests/screens/order-success.test.tsx new file mode 100644 index 0000000..49433c4 --- /dev/null +++ b/apps/user-ui/tests/screens/order-success.test.tsx @@ -0,0 +1,55 @@ +/** + * Order success screens (scheduled + flash) — route params and the two actions. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen } from '@testing-library/react-native' + +import OrderSuccess from '@/app/(drawer)/(tabs)/home/order-success' +import FlashOrderSuccess from '@/app/(drawer)/(tabs)/flash-delivery/order-success' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { routerMock, searchParamsMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +describe('Order success (scheduled)', () => { + beforeEach(async () => { + await resetStorage() + searchParamsMock.current = {} + }) + + it('renders the confirmation and performs both actions', () => { + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + expect(screen.getByText('Order Placed Successfully!')).toBeVisible() + + fireEvent.press(screen.getByText('Continue Shopping')) + expect(routerMock.dismissTo).toHaveBeenCalledWith('/(drawer)/(tabs)/home') + + fireEvent.press(screen.getByText('View My Orders')) + expect(routerMock.dismissAll).toHaveBeenCalled() + expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/me/my-orders') + }) + + it('shows the order id and total when params are present', () => { + searchParamsMock.current = { orderId: 'ORD-9', totalAmount: '500' } + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + expect(screen.getByText('Order #ORD-9')).toBeVisible() + expect(screen.getByText('Total: ₹500')).toBeVisible() + }) +}) + +describe('Order success (flash)', () => { + it('renders the confirmation actions', () => { + searchParamsMock.current = {} + setupApiMocks() + renderWithProviders(, { centralStores: false }) + + expect(screen.getByText('Continue Shopping')).toBeVisible() + expect(screen.getByText('View My Orders')).toBeVisible() + }) +}) diff --git a/apps/user-ui/tests/screens/product-detail-routes.test.tsx b/apps/user-ui/tests/screens/product-detail-routes.test.tsx new file mode 100644 index 0000000..db799e3 --- /dev/null +++ b/apps/user-ui/tests/screens/product-detail-routes.test.tsx @@ -0,0 +1,67 @@ +/** + * Product-detail route wrappers (home / stores / order-again / flash). + * + * The heavy ProductDetail component is mocked here so this file isolates the + * wrappers: they must read the `id` param and render ProductDetail with it. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +jest.mock('@/components/ProductDetail', () => { + const React = require('react') + const { Text } = require('react-native') + return { + __esModule: true, + default: ({ productId, isFlashDelivery }: { productId: string; isFlashDelivery?: boolean }) => + React.createElement( + Text, + { testID: 'product-detail-mock' }, + `${productId}:${isFlashDelivery ? 'flash' : 'regular'}` + ), + } +}) + +import React from 'react' +import { screen, waitFor } from '@testing-library/react-native' + +import HomeProductDetail from '@/app/(drawer)/(tabs)/home/product-detail/[id]' +import StoreProductDetail from '@/app/(drawer)/(tabs)/stores/store-detail/product-detail/[id]' +import OffersProductDetail from '@/app/(drawer)/(tabs)/order-again/product-detail/[id]/index' +import FlashProductDetail from '@/app/(drawer)/(tabs)/flash-delivery/product-detail/[id]' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { searchParamsMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const DETAIL = 'product-detail-mock' + +describe('Product detail routes', () => { + beforeEach(async () => { + await resetStorage() + setupApiMocks() + searchParamsMock.current = { id: '7' } + }) + + it('home route renders ProductDetail with the id', async () => { + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByTestId(DETAIL)).toHaveTextContent('7:regular')) + }) + + it('stores route renders ProductDetail', async () => { + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByTestId(DETAIL)).toHaveTextContent(/^7:/)) + }) + + it('order-again route renders ProductDetail', async () => { + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByTestId(DETAIL)).toHaveTextContent(/^7:/)) + }) + + it('flash route renders ProductDetail', async () => { + renderWithProviders(, { centralStores: false }) + + await waitFor(() => expect(screen.getByTestId(DETAIL)).toHaveTextContent(/^7:/)) + }) +}) diff --git a/apps/user-ui/tests/screens/search.test.tsx b/apps/user-ui/tests/screens/search.test.tsx new file mode 100644 index 0000000..afad857 --- /dev/null +++ b/apps/user-ui/tests/screens/search.test.tsx @@ -0,0 +1,101 @@ +/** + * Search results (app/(drawer)/(tabs)/home/search-results/index.tsx). + * + * Client-side Fuse.js search over the products cache, debounced by 300ms. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { act, fireEvent, screen, waitFor } from '@testing-library/react-native' + +import SearchResults from '@/app/(drawer)/(tabs)/home/search-results/index' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const CARD = 'product-card' +const INPUT = 'search-input-input' + +/** Render and wait until the product grid is populated. */ +async function renderLoaded() { + const api = setupApiMocks() + renderWithProviders() + await waitFor(() => expect(screen.getAllByTestId(CARD).length).toBeGreaterThan(0)) + return api +} + +/** Type into the search bar and let the 300ms debounce fire. */ +async function typeQuery(text: string) { + fireEvent.changeText(screen.getByTestId(INPUT), text) + await act(async () => { + jest.advanceTimersByTime(300) + }) +} + +describe('Search results', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('lists all products when the query is empty', async () => { + await renderLoaded() + + expect(screen.getByText('All Products')).toBeVisible() + expect(screen.getAllByTestId(CARD).length).toBeGreaterThan(0) + }) + + it('filters products by the debounced query', async () => { + await renderLoaded() + const before = screen.getAllByTestId(CARD).length + + await typeQuery('chicken liver') + + await waitFor(() => + expect(screen.getByText(/Search Results for "chicken liver"/)).toBeVisible() + ) + + const after = screen.getAllByTestId(CARD).length + expect(after).toBeGreaterThan(0) + expect(after).toBeLessThanOrEqual(before) + }) + + it('shows the no-results state for an unmatched query', async () => { + await renderLoaded() + + await typeQuery('zzzzzzzz') + + await waitFor(() => expect(screen.getByText('No products found')).toBeVisible()) + expect(screen.getByText(/Try adjusting your search/)).toBeVisible() + }) + + it('restores all products when the query is cleared', async () => { + await renderLoaded() + + await typeQuery('chicken liver') + await waitFor(() => + expect(screen.getByText(/Search Results for "chicken liver"/)).toBeVisible() + ) + + await typeQuery('') + await waitFor(() => expect(screen.getByText('All Products')).toBeVisible()) + expect(screen.getAllByTestId(CARD).length).toBeGreaterThan(0) + }) + + it('shows the loading state while products are pending', async () => { + setupApiMocks({ pendingProducts: true }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Loading products...')).toBeVisible()) + }) + + it('opens the product detail page when a card is pressed', async () => { + await renderLoaded() + + fireEvent.press(screen.getAllByTestId(CARD)[0]) + + expect(routerMock.push).toHaveBeenCalledWith( + expect.stringContaining('/home/product-detail/') + ) + }) +}) diff --git a/apps/user-ui/tests/screens/slot-view.test.tsx b/apps/user-ui/tests/screens/slot-view.test.tsx new file mode 100644 index 0000000..97fb774 --- /dev/null +++ b/apps/user-ui/tests/screens/slot-view.test.tsx @@ -0,0 +1,149 @@ +/** + * Slot views (components/SlotSpecificView.tsx): SlotProducts and + * FlashDeliveryProducts, plus the slot-view route's data source. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { TextInput } from 'react-native' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import { + FlashDeliveryProducts, + SlotProducts, +} from '@/components/SlotSpecificView' +import availability from '../mocks/mock-availability-response.json' +import productsResponse from '../mocks/mock-products-response.json' +import { mockSlots, resetStorage, setupApiMocks } from '../mocks/api' +import { routerMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const BASE = '/(drawer)/(tabs)/home/slot-view' +const SLOT = mockSlots.slots.find((s) => s.products.length > 0)! + +const PRODUCTS = productsResponse.products.filter((p) => !p.isComboOnly) +const AVAIL_BY_ID = new Map(availability.availability.map((a) => [a.id, a])) + +const isOutOfStock = (id: number) => AVAIL_BY_ID.get(id)?.isOutOfStock === true + +/** Slot products the screen renders: present in the cache and in stock. */ +const slotProducts = (storeId?: number) => + SLOT.products + .map((p) => PRODUCTS.find((x) => x.id === p.id)) + .filter((p): p is (typeof PRODUCTS)[number] => !!p && !isOutOfStock(p.id)) + .filter((p) => (storeId ? p.storeId === storeId : true)) + +/** Products eligible for flash delivery: flash-available and in stock. */ +const flashProducts = () => + PRODUCTS.filter((p) => { + const a = AVAIL_BY_ID.get(p.id) + return a?.isFlashAvailable === true && !a?.isOutOfStock + }) + +describe('SlotProducts', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('shows the loading state while slots load', async () => { + setupApiMocks({ pendingSlots: true }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('Loading slot delivery...')).toBeVisible() + ) + }) + + it('shows the error state when slots fail', async () => { + setupApiMocks({ failSlots: true }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('Failed to load slot delivery')).toBeVisible() + ) + }) + + it('shows the no-slot state for an unknown slot id', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('No delivery slot available.')).toBeVisible() + ) + }) + + it('lists the slot products and navigates on press', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getByTestId('slot-detail-page')).toBeVisible()) + + const first = slotProducts()[0] + expect(first).toBeDefined() + await waitFor(() => + expect(screen.getAllByText(first.name).length).toBeGreaterThan(0) + ) + + fireEvent.press(screen.getAllByText(first.name)[0]) + + expect(routerMock.push).toHaveBeenCalledWith( + `/(drawer)/(tabs)/home/product-detail/${first.id}` + ) + }) + + it('shows the empty message when a store has no products in the slot', async () => { + setupApiMocks() + renderWithProviders( + + ) + + await waitFor(() => + expect( + screen.getByText('No products from this store in this slot.') + ).toBeVisible() + ) + }) +}) + +describe('FlashDeliveryProducts', () => { + beforeEach(async () => { + await resetStorage() + }) + + it('lists flash-available in-stock products', async () => { + setupApiMocks() + renderWithProviders() + + const first = flashProducts()[0] + expect(first).toBeDefined() + await waitFor(() => + expect(screen.getAllByText(first.name).length).toBeGreaterThan(0) + ) + }) + + it('filters products by the search box', async () => { + setupApiMocks() + renderWithProviders() + + const first = flashProducts()[0] + await waitFor(() => + expect(screen.getAllByText(first.name).length).toBeGreaterThan(0) + ) + + fireEvent.changeText(screen.UNSAFE_getAllByType(TextInput)[0], 'zzzzzzz') + + await waitFor(() => + expect(screen.getByText('No 1 Hr Delivery products available.')).toBeVisible() + ) + }) + + it('shows the empty message when there are no products', async () => { + setupApiMocks({ products: { products: [], tags: [] } }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('No 1 Hr Delivery products available.')).toBeVisible() + ) + }) +}) diff --git a/apps/user-ui/tests/screens/store-detail.test.tsx b/apps/user-ui/tests/screens/store-detail.test.tsx new file mode 100644 index 0000000..81e0258 --- /dev/null +++ b/apps/user-ui/tests/screens/store-detail.test.tsx @@ -0,0 +1,66 @@ +/** + * Store detail (stores/store-detail/[id].tsx) — store meta, tag chips, + * products and the tag filter. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import StoreDetail from '@/app/(drawer)/(tabs)/stores/store-detail/[id]' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { routerMock, searchParamsMock } from '../mocks/router' +import { renderWithProviders } from '../helpers/render' + +const CARD = 'product-card' + +describe('Store detail', () => { + beforeEach(async () => { + await resetStorage() + searchParamsMock.current = { id: '1' } + }) + + it('renders the store, its tags and products', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Meat Store')).toBeVisible()) + expect(screen.getByText('Chicken (3)')).toBeVisible() + await waitFor(() => expect(screen.getAllByTestId(CARD).length).toBeGreaterThan(0)) + }) + + it('filters by tag and clears the filter', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Chicken (3)')).toBeVisible()) + + fireEvent.press(screen.getByText('Chicken (3)')) + await waitFor(() => expect(screen.getByText('Chicken items')).toBeVisible()) + + fireEvent.press(screen.getByText('Clear')) + await waitFor(() => expect(screen.getByText(/\d+ products/)).toBeVisible()) + }) + + it('navigates to a product detail when a card is pressed', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => expect(screen.getAllByTestId(CARD).length).toBeGreaterThan(0)) + fireEvent.press(screen.getAllByTestId(CARD)[0]) + + expect(routerMock.push).toHaveBeenCalledWith( + expect.stringContaining('/stores/store-detail/product-detail/') + ) + }) + + it('shows the error state when the store cannot be loaded', async () => { + setupApiMocks({ failStores: true }) + renderWithProviders() + + await waitFor(() => + expect(screen.getByText('Store not found or error loading')).toBeVisible() + ) + }) +}) diff --git a/apps/user-ui/tests/screens/stores.test.tsx b/apps/user-ui/tests/screens/stores.test.tsx new file mode 100644 index 0000000..c995c46 --- /dev/null +++ b/apps/user-ui/tests/screens/stores.test.tsx @@ -0,0 +1,100 @@ +/** + * Stores list (app/(drawer)/(tabs)/stores/index.tsx). + * + * Reads stores.json, deep-links to a store picked on the home page via + * navigationStore, and offers a retry on error. + */ + +jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) + +import React from 'react' +import { fireEvent, screen, waitFor } from '@testing-library/react-native' + +import Stores from '@/app/(drawer)/(tabs)/stores/index' +import storesResponse from '../mocks/mock-stores-response.json' +import { resetStorage, setupApiMocks } from '../mocks/api' +import { routerMock } from '../mocks/router' +import { useNavigationStore } from '@/src/store/navigationStore' +import { renderWithProviders } from '../helpers/render' + +const countStoresRequests = (mock: { mock: { calls: unknown[][] } }) => + mock.mock.calls.filter(([url]) => String(url).includes('stores.json')).length + +describe('Stores screen', () => { + beforeEach(async () => { + await resetStorage() + useNavigationStore.setState({ + isNavigatedFromHome: false, + selectedStoreId: null, + }) + }) + + it('lists every store with its product count', async () => { + setupApiMocks() + renderWithProviders() + + // The header is static, so wait for the cards before asserting names. + await waitFor(() => + expect(screen.getAllByText('Explore Store').length).toBeGreaterThan(0) + ) + + for (const store of storesResponse.stores) { + expect(screen.getByText(store.name)).toBeVisible() + } + expect(screen.getAllByText('Explore Store')).toHaveLength( + storesResponse.stores.length + ) + }) + + it('navigates to a store detail when Explore Store is pressed', async () => { + setupApiMocks() + renderWithProviders() + + await waitFor(() => + expect(screen.getAllByText('Explore Store').length).toBeGreaterThan(0) + ) + fireEvent.press(screen.getAllByText('Explore Store')[0]) + + expect(routerMock.push).toHaveBeenCalledWith( + expect.stringContaining('/stores/store-detail/') + ) + }) + + it('deep-links to the store chosen on the home page and clears the flag', async () => { + setupApiMocks() + useNavigationStore.setState({ isNavigatedFromHome: true, selectedStoreId: 4 }) + + renderWithProviders() + + await waitFor(() => + expect(routerMock.push).toHaveBeenCalledWith( + '/(drawer)/(tabs)/stores/store-detail/4' + ) + ) + + const state = useNavigationStore.getState() + expect(state.isNavigatedFromHome).toBe(false) + expect(state.selectedStoreId).toBeNull() + }) + + it('shows the error state and refetches on Retry', async () => { + const api = setupApiMocks({ failStores: true }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('Store Fetch Failed')).toBeVisible()) + + const before = countStoresRequests(api.axiosGet) + fireEvent.press(screen.getByText('Retry')) + + await waitFor(() => + expect(countStoresRequests(api.axiosGet)).toBeGreaterThan(before) + ) + }) + + it('shows the empty state when there are no stores', async () => { + setupApiMocks({ stores: { stores: [] } }) + renderWithProviders() + + await waitFor(() => expect(screen.getByText('No Stores Available')).toBeVisible()) + }) +}) diff --git a/apps/user-ui/tests/setup.ts b/apps/user-ui/tests/setup.ts index ceb3f93..fb05426 100644 --- a/apps/user-ui/tests/setup.ts +++ b/apps/user-ui/tests/setup.ts @@ -48,6 +48,39 @@ jest.mock('common-ui/hooks/useManualRefresh', () => ({ // module imports axios. Implementations are set in tests/mocks/api.ts. jest.mock('axios') +/** + * Native / third-party modules that cannot run under jest. Stubs live in + * tests/mocks/native.ts; individual tests spy on or override them as needed. + */ +jest.mock('react-native-webview', () => require('./mocks/native').webviewMock()) +jest.mock('expo-updates', () => require('./mocks/native').updatesMock()) +jest.mock('expo-linking', () => require('./mocks/native').linkingMock()) +jest.mock('expo-location', () => require('./mocks/native').locationMock()) +jest.mock('expo-notifications', () => require('./mocks/native').notificationsMock()) +jest.mock('react-native-razorpay', () => require('./mocks/native').razorpayMock()) + +/** + * useHideTabNav / useAuthenticatedRoute use @react-navigation/native's + * useFocusEffect, which throws without a NavigationContainer. Run the callback + * once on mount instead so focus-driven side effects are testable. + */ +jest.mock('@react-navigation/native', () => { + const actual = jest.requireActual('@react-navigation/native') + const React = require('react') + + return { + ...actual, + useFocusEffect: (callback: () => void | (() => void)) => { + const ran = React.useRef(false) + React.useEffect(() => { + if (ran.current) return + ran.current = true + return callback() + }, []) + }, + } +}) + /** * Auth is out of scope for these tests. `useUserDetails` throws without an * AuthProvider (which would drag in secure-store, tRPC login and redirect @@ -85,6 +118,33 @@ jest.mock('common-ui/src/services/StorageServiceCasual', () => { } }) +/** + * Secure StorageService (expo-secure-store backed). Mocked at the service + * module path: packages/ui resolves expo-secure-store from its own node_modules, + * so mocking the native module from here would not reach it. + */ +jest.mock('common-ui/src/services/StorageService', () => { + const store = new Map() + + return { + StorageService: { + getItem: jest.fn(async (key: string) => store.get(key) ?? null), + setItem: jest.fn(async (key: string, value: string) => { + store.set(key, value) + return true + }), + removeItem: jest.fn(async (key: string) => { + store.delete(key) + return true + }), + clearAll: jest.fn(async (keys: string[]) => { + keys.forEach((key) => store.delete(key)) + return true + }), + }, + } +}) + /** * Freeze the clock for every test. The home page is time-sensitive — it drops * slots whose deliveryTime is not after `dayjs()` and flags slots "closing diff --git a/apps/user-ui/tests/stores/stores.test.ts b/apps/user-ui/tests/stores/stores.test.ts new file mode 100644 index 0000000..88f4d28 --- /dev/null +++ b/apps/user-ui/tests/stores/stores.test.ts @@ -0,0 +1,130 @@ +/** + * Zustand stores: initial state + actions. + * + * Stores are module singletons; each test pokes the one it needs and resets it + * afterwards where the shape is shared with other tests. + */ + +import { useAddressStore } from '@/src/store/addressStore' +import { useAppStore } from '@/src/store/appStore' +import { useCartStore } from '@/src/store/cartStore' +import { useCentralProductStore } from '@/src/store/centralProductStore' +import { useCentralSlotStore } from '@/src/store/centralSlotStore' +import { useFlashCartStore } from '@/src/store/flashCartStore' +import { useNavigationStore } from '@/src/store/navigationStore' +import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore' +import { useStoreHeaderStore } from '@/src/store/storeHeaderStore' +import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' +import { useSlotStore } from '@/components/stores/slotStore' + +describe('zustand stores', () => { + it('appStore tracks tab-bar visibility per caller', () => { + useAppStore.getState().setHideTabsNavKey('cart', true) + expect(useAppStore.getState().hideTabsNav.cart).toBe(true) + + useAppStore.getState().setHideTabsNavKey('cart', false) + expect(useAppStore.getState().hideTabsNav.cart).toBe(false) + }) + + it('addressStore holds the selected checkout address', () => { + useAddressStore.getState().setSelectedAddressId(7) + expect(useAddressStore.getState().selectedAddressId).toBe(7) + }) + + it('cartStore queues and clears the add-to-cart product', () => { + const product = { id: 2, name: 'Chicken Breast 500 g' } + useCartStore.getState().setAddedToCartProduct({ productId: 2, product }) + expect(useCartStore.getState().addedToCartProduct).toEqual({ productId: 2, product }) + + useCartStore.getState().clearAddedToCartProduct() + expect(useCartStore.getState().addedToCartProduct).toBeNull() + }) + + it('flashCartStore queues and clears the flash product', () => { + const product = { id: 5, name: 'Cucumber' } + useFlashCartStore.getState().setAddedFlashProduct({ productId: 5, product }) + expect(useFlashCartStore.getState().addedFlashProduct).toEqual({ productId: 5, product }) + + useFlashCartStore.getState().clearAddedFlashProduct() + expect(useFlashCartStore.getState().addedFlashProduct).toBeNull() + }) + + it('navigationStore tracks the from-home flag and selected store', () => { + useNavigationStore.getState().setNavigatedFromHome(true) + useNavigationStore.getState().setSelectedStoreId(4) + + const state = useNavigationStore.getState() + expect(state.isNavigatedFromHome).toBe(true) + expect(state.selectedStoreId).toBe(4) + }) + + it('quickDeliveryStore holds the selected slot', () => { + useQuickDeliveryStore.getState().setSelectedSlotId(1849) + expect(useQuickDeliveryStore.getState().selectedSlotId).toBe(1849) + }) + + it('storeHeaderStore holds the screen title', () => { + useStoreHeaderStore.getState().setTitle('Meat Store') + expect(useStoreHeaderStore.getState().title).toBe('Meat Store') + }) + + it('slotStore holds the quick-delivery slot and store', () => { + useSlotStore.getState().setSlotId(1849) + useSlotStore.getState().setStoreId(1) + + expect(useSlotStore.getState().slotId).toBe(1849) + expect(useSlotStore.getState().storeId).toBe(1) + }) + + it('flashNavigationStore flags navigation back to the cart and resets', () => { + useFlashNavigationStore.getState().setShouldNavigateToCart(true) + expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(true) + + useFlashNavigationStore.getState().reset() + expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false) + }) + + it('centralProductStore indexes products by id', () => { + useCentralProductStore.getState().setProducts([ + { id: 2, name: 'Chicken Breast 500 g', price: 215 }, + { id: 5, name: 'Cucumber', price: 15 }, + ] as never) + + const state = useCentralProductStore.getState() + expect(state.products).toHaveLength(2) + expect(state.productsById[2].name).toBe('Chicken Breast 500 g') + expect(state.productsById[5].price).toBe(15) + }) + + it('centralSlotStore builds productSlotsMap from slots + availability', () => { + useCentralSlotStore.getState().setSlotsData( + [ + { + id: 1849, + deliveryTime: '2026-09-26T10:00:00.000Z', + freezeTime: '2026-09-26T09:00:00.000Z', + products: [{ id: 2, images: [] }], + }, + ] as never, + [{ id: 2 }] as never, + [ + { + id: 2, + price: 215, + marketPrice: 220, + flashPrice: null, + isFlashAvailable: true, + isOutOfStock: false, + isSuspended: false, + }, + ] as never + ) + + const state = useCentralSlotStore.getState() + expect(state.isSlotsLoaded).toBe(true) + expect(state.slots).toHaveLength(1) + expect(state.productSlotsMap[2].slots.map((s) => s.id)).toEqual([1849]) + expect(state.productSlotsMap[2].isFlashAvailable).toBe(true) + expect(state.productSlotsMap[2].isOutOfStock).toBe(false) + }) +}) diff --git a/change-log.txt b/change-log.txt index e585aef..8ef1296 100644 --- a/change-log.txt +++ b/change-log.txt @@ -2985,6 +2985,159 @@ Follow-up: adding two products back-to-back raced the first add's dialog cleanup 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. +[2026-09-26 00:57:02] user-ui: expand test harness for full-app coverage (no new app source). + +Groundwork so every remaining screen/component can be tested: + - tests/mocks/procedures.ts (new): parseTrpcUrl + calledProcedures / + procedureCalls / expectProcedureCalled / lastProcedureInput, so a test can + assert which tRPC procedure a button press invoked (and with what input). + - tests/mocks/api.ts: setups now take a `procedures` registry (value or + (input)=>value) merged over the essentials; the fetch stub resolves batched + calls by procedure name and passes the parsed input. Adds `stores`/ + `storeProducts` bodies, `failStores`, and serves stores/.json + (useStoreWithProducts). + - tests/mocks/store-products-response.json (new): fixture for + stores/.json (UserStoreDetail shape). + - tests/mocks/native.ts (new) + tests/setup.ts: module stubs for + react-native-webview, expo-updates, expo-linking, expo-constants, + expo-location, expo-notifications and react-native-razorpay. + - tests/helpers/render.tsx (new): generic Providers + renderWithProviders + (CentralStoreInitializer optional); home-page/render.tsx now builds on it. + - tests/helpers/real-router.tsx (new): renderRoute via + expo-router/testing-library for navigation assertions. + - tests/mocks/router.ts: expoRouterMock gains Slot/Stack/Tabs/Redirect and a + useFocusEffect that runs the callback once on mount, so deep-nav and guard + effects are testable with the mocked router. + +[2026-09-26 00:59:43] user-ui: screen tests (batch 1 of the app-wide coverage). + +tests/screens/flash-gate.test.tsx (2), search.test.tsx (6), +stores.test.tsx (5), order-again.test.tsx (6): flash-delivery gate +(disabled -> unavailable + route home; enabled -> no gate), search-results +(all/debounced-filter/no-results/loading/navigate/clear), stores list +(all stores, deep-link from home, retry on error, empty, explore nav) and +order-again (sections, empty section, cards, loading, error, nav). + +[2026-09-26 01:07:11] user-ui: screen tests (batch 2) + harness fixes. + + - tests/setup.ts: stub @react-navigation/native's useFocusEffect (run-once) - + useHideTabNav / useAuthenticatedRoute throw without a NavigationContainer. + - tests/mocks/procedures.ts: read the batch input from the POST body as well + as the query string, and accept this project's raw input maps (no superjson + envelope), so lastProcedureInput works for queries and mutations. + - tests/mocks/auth.ts: authMock gains isLoading + login/loginWithToken/ + register/logout/updateUserDetails spies. + - tests/mocks/api.ts: pendingSlots / failSlots options. + - tests/screens/auth.test.tsx (9): login mobile->otp (sendOtp/verifyOtp -> + loginWithToken), password login (user.auth.login), validation, terms dialog, + register screen + sign-in link, auth layout spinner. + - tests/screens/navigation-shell.test.tsx (2): app entry redirect to /home and + loading spinner (real router). + - tests/screens/slot-view.test.tsx (8): SlotProducts loading/error/no-slot/ + list+nav/store-empty; FlashDeliveryProducts list/search/empty. + - tests/screens/cart-screen.test.tsx (5): empty + Start Shopping; seeded line, + bill and getCartSlots input; eligible coupons when authenticated; checkout + nav with slot; flash variant. + +Next: stores/hooks/lib/contexts, components, checkout, product-detail, me/*. + +[2026-09-26 01:11:39] user-ui: stores/hooks/lib + components + me screens. + + - tests/stores/stores.test.ts (11): every zustand store, incl. centralSlotStore + productSlotsMap building. + - tests/lib/string-manipulators.test.ts (3). + - tests/hooks/useProductSlotIdentifier.test.tsx (5), + useHideTabNav.test.tsx (2), + cart-query-hooks.test.tsx (6: add/increment/flash isolation/update/remove/ + derive/clear). + - tests/components/: static-components (9: terms, notes, tab wrapper, + first-run gate, webview, back handler), icons (5), order-menu (4: + updateUserNotes/cancelOrder + validation), complaint-form (3: + complaint.raise), wrappers (4: healthCheck + retry + update dialog; + UpdateChecker inert on dev), product-card (5). + - tests/screens/me-hub.test.tsx (4), me-orders.test.tsx (5: getOrders, + nav, empty, error+retry, createRazorpayOrder). + - tests/mocks/router.ts: canGoBack/dismissTo/setParams + usePathname. + +Suite: 30 files / 158 tests passed. tsc clean. +Still pending: product-detail, checkout/payment, me-account (addresses/coupons/ +complaints/edit-profile), registration-form, address selectors, useAuthenticatedRoute, +useUploadToObjectStore, auth-context, trpc-client, useJWT. + +[2026-09-26 09:12:08] user-ui: me-account, order-success, hooks, registration-form. + + - tests/mocks/router.ts: `searchParamsMock.current` (settable local search + params) + dismissTo/dismissAll/setParams. + - tests/setup.ts: mock common-ui StorageService at the service path (packages/ui + resolves expo-secure-store from its own node_modules, so mocking the native + module would not reach it). + - tests/mocks/api.ts: the fetch stub answers non-tRPC PUTs (presigned uploads). + - tests/screens/me-account.test.tsx (16): addresses list/empty/error+retry/ + set-default/delete (address.*); coupons sections + redeemReservedCoupon + + empty; complaints list/dialer/empty/error; edit profile logout + delete + account (+ mobile validation); terms. + - tests/screens/order-success.test.tsx (3): both variants, params, actions. + - tests/hooks/: useJWT (3), useAuthenticatedRoute (3), useUploadToObjectStore + (3: presigned urls + PUTs, empty, count mismatch), prominent-api-hooks (6: + essentialConsts, products+availability merge, stores, slots, store detail, + error). + - tests/components/registration-form.test.tsx (5): fields, validation, + password mismatch, normalised payload, edit-mode updatePassword. + +Suite: 37 files / 197 tests passed. tsc clean. +Remaining: product-detail (+ its 4 routes), checkout/PaymentAndOrderComponent, +store-detail, my-orders/[id], AddressForm/selectors/LocationAttacher/ +LocationTestWrapper, SlotLayout, auth-context, trpc-client. + +[2026-09-26 09:21:33] user-ui: store/order detail, checkout + payment, routes, trpc-client. + + - tests/screens/store-detail.test.tsx (4): store meta + tags + products, tag + filter + clear, product nav, error state. + - tests/screens/order-detail.test.tsx (6): getOrderById render, error + back, + notes (updateUserNotes), cancel validation + cancelOrder, complaint dialog. + - tests/components/payment-and-order.test.tsx (4): bill + enabled CTA, address + gating, placeOrder payload + cart cleared + success redirect, error. + - tests/screens/checkout.test.tsx (2): empty-cart state + back, auth redirect. + - tests/screens/product-detail-routes.test.tsx (4): the 4 route wrappers pass + the id to ProductDetail (the heavy component is mocked). + - tests/lib/trpc-client.test.ts (2): 401 UNAUTHORIZED emits force-logout; 500 + does not. + - tests/hooks/useColorScheme.test.tsx (1). + +Suite: 44 files / 220 tests passed. tsc clean. +Remaining: ProductDetail component internals, AddressForm, CheckoutAddressSelector, +QuickDeliveryAddressSelector, LocationAttacher, LocationTestWrapper, SlotLayout, +AuthContext. + +[2026-09-26 09:32:02] user-ui: final components, AuthContext, SlotLayout — full coverage. + + - tests/components/location-attacher.test.tsx (3): attach success, permission + denied, disabled. + - tests/components/address-selectors.test.tsx (5): CheckoutAddressSelector + (list + auto-select default, select on press, empty) and + QuickDeliveryAddressSelector (slot dialog + onSlotChange, flash header). + - tests/components/address-form.test.tsx (4): render, Yup validation, + createAddress, edit-mode updateAddress. + - tests/components/location-wrapper.test.tsx (1): emulator passthrough. + - tests/components/product-detail.test.tsx (4): loading, loaded + reviews + (getProductDetails/getProductReviews), error, add-to-cart dialog. + - tests/components/slot-layout.test.tsx (2): delivery-time selector + cart bar, + flash header (Drawer stubbed). + - tests/contexts/auth-context.test.tsx (4): real AuthProvider (unmocked) — + signed-out settle, loginWithToken persists + authenticates, logout clears, + useAuth throws outside the provider. + +Suite: 51 files / 243 tests passed. tsc clean. +Only the global shells remain untested: app/_layout.tsx, (drawer)/_layout.tsx, +the thin per-route _layout.tsx files, and services/notif-service. + + + + + + + +