This commit is contained in:
shafi54 2026-10-18 21:51:01 +05:30
parent ba2cfd1224
commit 94decd863f
129 changed files with 27341 additions and 1067 deletions

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,340 +0,0 @@
# backend — API test case info
HTTP/API tests that drive a **running** backend (not unit tests): they log in with
real credentials, create data through the API, and pull the generated static JSON
cache the apps consume.
- **Runner**: jest + ts-jest, node environment, serial (`--runInBand`)
- **Total**: **22 suites / 107 tests** — all green (`bun run test:api`, ~2.5 min)
- Tests live in `apps/backend/tests/`; they do not import server runtime code beyond
the `AppRouter` type.
## Run
```bash
# 1. start the backend (wrangler dev, port 8787)
cd apps/backend && bun run dev
# 2. fill in credentials (git-ignored)
cp apps/backend/tests/.env.example apps/backend/tests/.env # then edit
# 3. run
cd apps/backend && bun run test:api
bun run test:api:typecheck # tsc over tests/
```
`API_BASE_URL` defaults to `http://localhost:8787`; override it in `tests/.env`.
## Environment notes
- **Auth**: `admin.staffUser.login` (staff) and `user.auth.login` (user). Login, not OTP —
OTP requires a real SMS. The user must exist in the **local** D1.
- **Preconditions are not seeded** (only config/constants are): the suites create a store,
a one-SKU product and a future slot through the **admin** API, plus an address for the user.
Data is **left behind**; names carry a unique suffix so reruns stay valid.
- **Cache files** are written through the R2 S3 API to the real dev bucket and read back from
the **assets domain** (`assetsDomain` from `common.essentialConsts`, e.g.
`https://assets2.freshyo.in`). The machine therefore needs network access to both.
- **Trigger timing** decides the suite layout: `slots.json` and `availability.json` are
regenerated **synchronously** inside their mutations; `products.json` / `stores/<id>.json`
are rebuilt ~30 s later by the `CACHE_CREATOR` Durable Object → those tests poll.
- Test slots must be in the **future** and not at capacity — the public slots payload filters
to future, non-full slots.
## Findings from the first green run
- **`availability.json` is keyed by SKU id**, not product id (`id: stat.skuId`), and its
`isOutOfStock` comes from `product_market_stats`. `admin.product.toggleOutOfStock` takes a
**product** id and flips `product_market_stats` for all of that product's SKUs, so it *is*
app-visible — but look the entry up by `skuId`.
- **The cache rebuild writes files in parallel (non-atomic).** After `cacheVersion` advances,
`products.json` can be readable while `stores/<id>.json` is still uploading (observed: 404 at
the new version, 200 moments later). The tests therefore poll for each individual file.
- **`placeOrder` accepts a non-existent `slotId`.** It only checks slot *capacity*; there is no
FK/validity check, so a bogus id is stored verbatim. Case 17 documents this gap — it will need
updating if the backend adds validation.
- **Admin *reads* are not staff-guarded.** `protectedProcedure` only requires *some* identity, so a
plain user token can call `admin.product.getProducts` (documented by the authorization suite).
Staff-guarded writes (e.g. `admin.slots.createSlot`) do check `ctx.staffUser`.
- **`availability.json` and `slots.json` can lead `products.json`.** Both are bumped synchronously
(stock toggle / slot mutation) while `products.json` only rebuilds ~30 s later, so for a window
the cache references product ids that the product file doesn't have yet. The consistency checks
poll for convergence and assert the stable parts.
- **`essential-consts.json` embeds a version snapshot** taken when it was written, so its
`slotsVersionNum`/`availabilityVersionNum` can lag the live values (slots bump independently).
Consumers get versions from `common.essentialConsts` (tRPC), not from this file.
- **`updateProduct` requires a SKU feature literally named `quantity`** ("Every SKU must have a
quantity feature") — the same rule as the create path.
- **`admin.order.updateAddressCoords` succeeds but is not visible to the user.** The
user-facing `address.getUserAddresses` still returns `latitude` null/0, so the admin write and
the user read disagree. The test asserts the mutation contract only.
- **`admin.order.cancelOrder` refuses an already-delivered order**; the test cancels a freshly
placed one instead.
- **`admin.order.*` id types are inconsistent**: `getOrderDetails` / `updateNotes` /
`removeDeliveryCharge` / `cancelOrder` take a **number**; `updatePackaged` / `updateDelivered` /
`getSlotOrders` take a **string**.
- **`admin.coupon.create` returns an array** (`Coupon[]`) — take `[0].id`. `update` takes
`{ id, updates }` and merges partially (fields present win). `delete` **soft-invalidates**
("Coupon invalidated successfully"): `getById` still returns the row, but it vanishes from
`coupon.getEligible` and `placeOrder` rejects it. Creating with **both** `discountPercent` and
`flatDiscount` is rejected.
- **`admin.user.getUserDetails` breaks once a user has a long order history.** It builds an
unchunked `select … from order_status where order_id in (…)` over every order the user ever
placed; at ~110 orders the query fails outright (`Failed query`). Reproduction: call it for the
shared test account after a few runs. The suite now exercises it against a fresh user. Same
unchunked pattern is used for the order stats in `admin.user.getAllUsers`.
- **`admin.product.deleteProduct` fails for a product that has SKUs.** It issues a hard
`delete from product_info … returning …`, which trips the FK from the product's SKUs /
market stats; the API returns a raw "Failed query" instead of a 404/409. There is no
soft-delete path reachable through this procedure. The test asserts the rejection.
- **`admin.store.deleteStore` takes `{ storeId }`**, unlike its siblings
(`product.deleteProduct`, `banner.deleteBanner`, `product.deleteProductTag`) which take `{ id }`.
Mismatched shape → zod `invalid_type` on `storeId`.
- **`admin.slots.getAll` returns at most 20 slots** (hard-coded limit) and keeps returning them as
runs accumulate data, so a freshly created slot is not guaranteed to be inside that window. The
membership assertion moved to the unbounded public `user.slots.getSlots`; the cap itself is now
asserted.
- **`vendorSnippets.getOrdersBySnippet` requires the snippet to be linked to a slot** —
otherwise it throws "Vendor snippet not associated with a slot", because it resolves orders
through the slot. `snippetCode` is also **required** on create.
- **`admin.banner.createBanner` needs a URL-shaped `imageUrl`** (`z.string().url()`) and extracts an
object key from it; a plausible assets-domain URL is accepted without any upload.
- **Suspension is a live precondition for ordering.** `placeOrder` rejects a suspended user
("Unable to place order"), so the admin-ops suite unsuspends the shared test user in
`beforeAll` and the suspension test restores the flag in a `finally`.
- **`stores/<id>.json` can land in a *later* cache version than the one captured after a write.**
`cacheVersion` advances on every admin write while the ~30 s rebuild writes the per-store files
separately, so the store-detail test resolves the current version on each poll attempt instead
of pinning it.
- **A presigned upload URL is usable by any client, with no R2 credentials.** The signature
travels in the query string and `Content-Type` is deliberately left unsigned (see the comment
in `generateUploadUrl`), so the test process can PUT bytes straight to R2 and read the object
back from the public assets domain. `X-Amz-Expires` is 180 s.
- **The object key is `${folder}/${Date.now()}${extension}`** (`common.generateUploadUrls`), with
the folder chosen from `contextString` (product-images, tags, store-images, review-images,
review-response-images, complaint-images, profile-images) and the extension from the mime type
(jpg/png/gif, jpg fallback). Two files with the *same* mime type in one call share a
millisecond and therefore a key — one pending-status row, two URLs, one object. Deliberately
not covered here.
- **Every presign writes a `pending` status row** (`createUploadUrlStatus`), and `claimUploadUrl`
flips it to claimed — throwing `Failed to claim upload URL` when the row is absent or already
claimed. The admin create paths that accept `uploadUrls` (product SKU images, tag image,
review response) depend on it. Not covered here: claim/re-claim, and `deleteImageUtil` on image
replacement (store update, tag update/delete, product update).
## Suites
### `api/health.test.ts` — 3 (no auth)
| # | Test | Request → assert |
| --- | --- | --- |
| 1 | GET /api/health responds 200 | `GET /api/health` → 200 + ok |
| 2 | common.healthCheck resolves over tRPC | `common.healthCheck` → truthy |
| 3 | common.essentialConsts returns the runtime config | numeric `freeDeliveryThreshold`, string `assetsDomain`/`apiCacheKey`, numeric `cacheVersion`/`slotsVersionNum` |
### `api/auth.test.ts` — 3
| # | Test | Request → assert |
| --- | --- | --- |
| 4 | staff login returns a token and staff id | `admin.staffUser.login` → token, `staff.id > 0` |
| 5 | user login returns a token and user id | `user.auth.login` → token, `user.id > 0` |
| 6 | each token authenticates its own protected procedures | staff → `admin.product.getProducts`; user → `user.address.getUserAddresses` |
### `api/admin.test.ts` — 2
| # | Test | Request → assert |
| --- | --- | --- |
| 7 | admin.product.getProducts includes the created SKU | created product found with the created sku id |
| 8 | admin.slots.getAll includes the created slot | created slot id present |
### `api/order-flow.test.ts` — 5 (the requested flow)
| # | Test | Request → assert |
| --- | --- | --- |
| 9 | lists the created slot via user.slots.getSlots | created slot id present |
| 10 | places a COD order and echoes the total | `user.order.placeOrder` (cod) → one order, id/total > 0 |
| 11 | returns the new order from user.order.getOrders | order id present, `deliveryStatus: 'pending'`, 1 item, `pagination.totalCount > 0` |
| 12 | returns the same order from user.order.getOrderById | id/amount match, 1 item |
| 13 | places an online order with a pending payment | `paymentMethod:'online'` → `paymentMode: 'Online'`, `paymentStatus: 'pending'` |
### `api/order-edge-cases.test.ts` — 4
| # | Test | Request → assert |
| --- | --- | --- |
| 14 | rejects an unauthenticated request | no token → UNAUTHORIZED |
| 15 | rejects an address that is not the user's | bogus addressId → "Invalid address" |
| 16 | rejects an unknown skuId | bogus skuId → "not found" |
| 17 | accepts a non-existent slotId (known gap) | bogus slotId → order is created and `slotId` stored verbatim (no validity/FK check) — documents the gap |
### `api/cache-slots.test.ts` — 3 (synchronous cache)
| # | Test | Request → assert |
| --- | --- | --- |
| 18 | exposes a numeric slotsVersionNum | `common.essentialConsts` → number > 0 |
| 19 | contains a newly created slot | create slot → GET `slots/v-<sv>/slots.json` → slot id present, deliveryTime matches |
| 20 | bumps the version and rewrites the file for a second slot | `slotsVersionNum` increases; the new file contains the second slot |
### `api/cache-availability.test.ts` — 2 (synchronous cache)
| # | Test | Request → assert |
| --- | --- | --- |
| 21 | reflects an out-of-stock toggle for the new SKU | `admin.product.toggleOutOfStock({id})` → `isOutOfStock: true` in the response, `availabilityVersionNum` increases → GET `av-<av>/availability.json` → entry (keyed by **skuId**) `isOutOfStock: true` |
| 22 | has a count matching the number of entries | `count === availability.length` |
### `api/cache-products.test.ts` — 2 (eventual cache, polls ~30–120 s)
| # | Test | Request → assert |
| --- | --- | --- |
| 23 | lists the new product in products.json | poll `cacheVersion` past the baseline → GET `<apiCacheKey>/v-<cv>/products.json` → new product id present |
| 24 | writes stores/&lt;id&gt;.json for the new store | GET `<apiCacheKey>/v-<cv>/stores/<id>.json` → `store.id` matches |
### `api/authorization.test.ts` — 5
| # | Test | Request → assert |
| --- | --- | --- |
| 25 | rejects anonymous requests | no token → UNAUTHORIZED |
| 26 | a staff token cannot act as a user (no ctx.user) | staff token → `user.order.getOrders` rejects |
| 27 | a user token cannot use staff-guarded admin writes | user token → `admin.slots.createSlot` rejected |
| 28 | DOCUMENTS: a user token CAN read `admin.product.getProducts` | no staff guard on admin reads — documents the gap |
| 29 | one user cannot see another user's addresses | registered user B's list excludes user A's address |
### `api/order-rules.test.ts` — 6
Uses a tiny-priced SKU (5) so one unit is below `minRegularOrderValue`.
| # | Test | Request → assert |
| --- | --- | --- |
| 30 | adds the configured delivery charge below the minimum order value | qty 1 → `deliveryCharge === deliveryCharge` const |
| 31 | waives the delivery charge at or above the minimum order value | qty to exceed min → `deliveryCharge === '0'` |
| 32 | groups items from different slots into one order per slot, charging once | 2 slots → 2 orders, exactly 1 charged |
| 33 | rejects an order for a full slot | `updateSlotCapacity(true)` → 403 "capacity"; capacity restored |
| 34 | rejects flash delivery while it is disabled | `isFlashDeliveryEnabled` forced off → 403 "flash"; restored |
| 35 | rejects an invalid quantity | `quantity: 0` → zod rejection |
### `api/order-lifecycle.test.ts` — 5
| # | Test | Request → assert |
| --- | --- | --- |
| 36 | persists special instructions | `updateUserNotes` → `getOrderById.userNotes` |
| 37 | cancels the order with a reason and reflects it in the list | `cancelOrder` → `cancelReason` + cancelled status in `getOrders` |
| 38 | rejects a cancellation without a reason | empty reason → zod rejection |
| 39 | rejects a readable order id ("ORD&lt;id&gt;") | numeric-string contract |
| 40 | paginates orders and rejects an oversized page size | page 1 vs 2 differ; `pageSize: 51` → rejection |
### `api/user-surface.test.ts` — 7
| # | Test | Request → assert |
| --- | --- | --- |
| 41 | returns the product detail for a product id | `product.getProductDetails` |
| 42 | creates a review and returns it from getProductReviews | `createReview` → listed |
| 43 | returns presigned upload URLs | `common.generateUploadUrls` → 1 URL |
| 44 | exposes eligible and owned coupons | `coupon.getEligible` + `getMyCoupons` arrays |
| 45 | rejects redeeming an unknown coupon code | bogus `secretCode` → 400 |
| 46 | returns the signed-in user profile | `user.user.getSelfData.data.user.id` |
| 47 | raises a complaint that staff can resolve | `complaint.raise` → `getAll` → admin `complaint.resolve` → `isResolved` |
### `api/cache-consistency.test.ts` — 5 (cross-file invariants)
| # | Test | Request → assert |
| --- | --- | --- |
| 48 | every availability entry maps to a product in products.json | 0 orphan ids (polls — availability can lead) |
| 49 | availability count matches the number of entries | `count === availability.length` |
| 50 | every product referenced by slots.json exists in products.json | 0 orphans (polls) |
| 51 | essential-consts.json is self-consistent with the version in its path | file's `cacheVersion` == path; other versions numeric |
| 52 | stores.json productCount matches each store detail file | `productCount === detail.products.length` |
### `api/admin-catalog.test.ts` — 9
| # | Test | Request → assert |
| --- | --- | --- |
| 53 | getStoreById returns the created store | `{ id }` → store.id |
| 54 | updateStore renames the store | update → getStoreById reflects the new name |
| 55 | getProductById returns the product with its SKU | product id + sku id present |
| 56 | updateProduct renames the product | update (sku feature `quantity`) → getProducts reflects the new name |
| 57 | getGroups lists product groups | `groups` array |
| 58 | createGroup adds a group that getGroups returns | group name present |
| 59 | coupon.getAll returns a coupons array | `coupons` array |
| 60 | vendorSnippets.getAll returns an array | array |
| 61 | complaint.getAll returns a complaints array | `complaints` array |
### `api/admin-orders.test.ts` — 10
| # | Test | Request → assert |
| --- | --- | --- |
| 62 | getAll returns recent orders | `{ limit: 5 }` → `orders` array |
| 63 | getOrderDetails returns the order | `{ orderId: number }` → id matches |
| 64 | getSlotOrders lists the orders for a slot (string slotId) | `{ slotId: string }` → truthy |
| 65 | updateNotes stores admin notes on the order | `{ orderId, adminNotes }` → details reflect |
| 66 | marks the order packaged | `{ orderId: string, isPackaged: true }` → success |
| 67 | marks the order delivered and the user sees "success" | user's `getOrderById.deliveryStatus === 'success'` |
| 68 | removes the delivery charge | user's `deliveryCharge === 0` |
| 69 | updates the address coordinates | mutation succeeds (coords not exposed to the user read — documented) |
| 70 | cancels a fresh order as staff and the user sees it cancelled | new order → `cancelOrder` → status cancelled |
| 71 | rebalances the orders for a slot | `{ slotIds: [id] }` → truthy |
### `api/coupons.test.ts` — 7 (admin CRUD → user applies it)
| # | Test | Request → assert |
| --- | --- | --- |
| 72 | creates the coupon and getById returns it | `coupon.create` (flat 2, minOrder 1, apply-for-all) → `[0].id`; getById code + discount |
| 73 | updates the coupon | `coupon.update({ id, updates })` → getById reflects |
| 74 | is eligible for the user | `user.coupon.getEligible` contains the coupon |
| 75 | reduces the order amount when the user applies it | `placeOrder({ couponId })` → `getOrderById.couponCode` + `discountAmount === 2` |
| 76 | deleting the coupon invalidates it for the user | `coupon.delete` → no longer in `getEligible` |
| 77 | rejects applying the invalidated coupon to an order | `placeOrder({ couponId })` → invalid/expired error |
| 78 | rejects a coupon with both discount types | `coupon.create({ discountPercent, flatDiscount })` → rejected |
### `api/admin-users.test.ts` — 8 (admin user surface)
| # | Test | Request → assert |
| --- | --- | --- |
| 79 | getEssentials returns the dashboard counters | `user.getEssentials` → numeric `unresolvedComplaints` |
| 80 | getAllUsers returns users | `user.getAllUsers({ limit: 5 })` → `users` array |
| 81 | getUserDetails returns the user | `user.getUserDetails({ userId })` → id matches a fresh user |
| 82 | getStaff lists the staff | `staffUser.getStaff` → includes the logged-in staff id |
| 83 | adds a user incident that getUserIncidents returns | `addUserIncident({ userId, adminComment })` → the comment comes back |
| 84 | getUsersForNotification returns a users array | `{ search: '' }` → array |
| 85 | suspends and unsuspends the user | `updateUserSuspension(true/false)` → `getUserDetails` reflects each |
| 86 | sendNotification tolerates a recipient with no push token | `{ userIds: [fresh] }` → resolves (nothing delivered) |
### `api/admin-banners.test.ts` — 4
| # | Test | Request → assert |
| --- | --- | --- |
| 87 | getBanners returns a banners array | `banner.getBanners` → array |
| 88 | createBanner creates a banner that getBanner returns | `createBanner({ name, imageUrl })` → `getBanner({ id }).name` |
| 89 | updateBanner renames the banner | `updateBanner({ id, name })` → `getBanner` reflects |
| 90 | deleteBanner removes it | `deleteBanner({ id })` → `getBanner` is null |
### `api/admin-tags.test.ts` — 4
| # | Test | Request → assert |
| --- | --- | --- |
| 91 | creates a tag that getProductTags returns | `createProductTag({ tagName, isDashboardTag })` → new id in `getProductTags` |
| 92 | getProductTagById returns the tag | `getProductTagById({ id })` → tagName matches |
| 93 | updateProductTag renames the tag | `updateProductTag({ id, tagName })` → reflected |
| 94 | deleteProductTag removes it | `deleteProductTag({ id })` → gone from `getProductTags` |
### `api/admin-vendor-snippets.test.ts` — 4
| # | Test | Request → assert |
| --- | --- | --- |
| 95 | creates a snippet that getAll returns | `vendorSnippets.create({ snippetCode, slotId, skuIds, isPermanent })` → id in `getAll` |
| 96 | updates the snippet | `update({ id, updates: { validTill } })` → still listed |
| 97 | returns the orders for the snippet code | `getOrdersBySnippet({ snippetCode })` → resolves (needs a slot) |
| 98 | deletes the snippet | `delete({ id })` → gone from `getAll` |
### `api/admin-ops.test.ts` — 5 (config, lifecycle, concurrency)
| # | Test | Request → assert |
| --- | --- | --- |
| 99 | round-trips a constant through updateConstants | `updateConstants(minOrderAmountForCoupon = 123)` → `getConstants` shows 123 → restored |
| 100 | updates and deletes a product group | `createGroup` → `updateGroup({ id, group_name })` visible in `getGroups` → `deleteGroup({ id })` removes it |
| 101 | deleteProduct rejects for a product that still has SKUs | `deleteProduct({ id })` → rejected (FK on the hard delete) |
| 102 | deletes a store | `store.createStore` → `deleteStore({ storeId })` → `getStoreById` no longer resolves |
| 103 | places two concurrent orders for different slots | two `placeOrder` calls in parallel → two distinct, persisted order ids |
### `api/uploads.test.ts` — 4 (image upload round trip)
The presigned PUT is self-signed, so these cases upload real bytes without any R2 credentials and
read them back from the public assets domain (`common.essentialConsts.assetsDomain`, the same
source the app renders from). Objects stay in the dev bucket.
| # | Test | Request → assert |
| --- | --- | --- |
| 104 | stores exactly the bytes that were uploaded | `common.generateUploadUrls({contextString:'product_info'})` → PUT a 1×1 PNG → GET `<assetsDomain>/<key>` → same length, byte-equal, same sha256 |
| 105 | keeps two uploads distinct — each URL serves its own object | presign in two folders (product-images, tags) → different keys → each serves its own PNG, shas differ |
| 106 | gives every mime type in one call a usable URL | one call with `['image/png','image/jpeg']` → 2 distinct keys → both objects hold their own bytes |
| 107 | returns 404 for an object that was never uploaded | guards the read-back: a passing comparison must mean the object really exists |
## Harness reference
| Path | Purpose |
| --- | --- |
| `tests/jest.config.js` | jest project (ts-jest, node env, `runInBand`, clearMocks) |
| `tests/tsconfig.json` | typecheck scope for tests (`bun run test:api:typecheck`) |
| `tests/setup.ts` | loads `tests/.env` before the suites |
| `tests/.env.example` | credentials template (copy to `tests/.env`, git-ignored) |
| `tests/helpers/env.ts` | `API_BASE_URL` + credentials with actionable errors |
| `tests/helpers/api.ts` | tRPC client (`httpBatchLink`) + bearer token, `health()`, `assertServerUp()`, `uniqueSuffix()` |
| `tests/helpers/sessions.ts` | staff/user login with cached tokens |
| `tests/helpers/fixtures.ts` | `createStoreWithSku` (optional price), `createFutureSlot`, `ensureUserAddress`, `registerThrowawayUser` |
| `tests/helpers/consts.ts` | `getConstants` (normalised), `setConst` (used to flip the flash gate, always restored), `asNumber` |
| `tests/helpers/cache.ts` | `essentialConsts`, versioned cache URLs (products/stores/slots/availability/essential-consts), `fetchCacheJson`, `pollUntil` |

File diff suppressed because it is too large Load diff

View file

@ -372,6 +372,7 @@ function Login() {
{[0, 1, 2, 3].map((i) => (
<TextInput
key={i}
testID={`user-login-otp-${i}`}
ref={(ref) => { inputRefs.current[i] = ref; }}
style={tw`w-14 h-14 ${errors.otp ? 'border-red-500' : 'border-gray-200'} border-2 rounded-xl text-center text-2xl font-bold ${otpCells[i] ? 'bg-blue-50 border-brand500 text-brand700' : 'bg-gray-50'}`}
keyboardType="numeric"
@ -515,6 +516,7 @@ function Login() {
{/* Terms and Conditions Checkbox */}
<View style={tw`flex-row items-center mt-4 mb-2`}>
<Checkbox
testID="user-login-terms-checkbox"
checked={termsAccepted}
onPress={() => setTermsAccepted(!termsAccepted)}
size={20}

View file

@ -40,12 +40,12 @@ export default function FlashDeliveryOrderSuccess() {
{/* Order Details (if available) */}
{orderId && (
<View style={tw`bg-gray-50 px-4 py-3 rounded-lg mb-8`}>
<MyText style={tw`text-sm text-gray-600 text-center`}>
<View testID="order-success-details" style={tw`bg-gray-50 px-4 py-3 rounded-lg mb-8`}>
<MyText testID="order-success-order-id" style={tw`text-sm text-gray-600 text-center`}>
1 Hr Order #{orderId}
</MyText>
{totalAmount && (
<MyText weight="semibold" style={tw`text-lg text-gray-900 text-center mt-1`}>
<MyText testID="order-success-total" weight="semibold" style={tw`text-lg text-gray-900 text-center mt-1`}>
Total: ₹{totalAmount}
</MyText>
)}
@ -55,6 +55,7 @@ export default function FlashDeliveryOrderSuccess() {
{/* Action Buttons */}
<View style={tw`w-full gap-3`}>
<MyButton
testID="order-success-continue"
textContent="Continue Shopping"
onPress={() => router.dismissTo("/(drawer)/(tabs)/flash-delivery")}
fillColor="brand500"
@ -63,6 +64,7 @@ export default function FlashDeliveryOrderSuccess() {
/>
<MyButton
testID="order-success-view-orders"
textContent="View My Orders"
onPress={() => {
router.dismissAll();

View file

@ -40,12 +40,12 @@ export default function OrderSuccess() {
{/* Order Details (if available) */}
{orderId && (
<View style={tw`bg-gray-50 px-4 py-3 rounded-lg mb-8`}>
<MyText style={tw`text-sm text-gray-600 text-center`}>
<View testID="order-success-details" style={tw`bg-gray-50 px-4 py-3 rounded-lg mb-8`}>
<MyText testID="order-success-order-id" style={tw`text-sm text-gray-600 text-center`}>
Order #{orderId}
</MyText>
{totalAmount && (
<MyText weight="semibold" style={tw`text-lg text-gray-900 text-center mt-1`}>
<MyText testID="order-success-total" weight="semibold" style={tw`text-lg text-gray-900 text-center mt-1`}>
Total: ₹{totalAmount}
</MyText>
)}
@ -55,6 +55,7 @@ export default function OrderSuccess() {
{/* Action Buttons */}
<View style={tw`w-full gap-3`}>
<MyButton
testID="order-success-continue"
textContent="Continue Shopping"
onPress={() => router.dismissTo("/(drawer)/(tabs)/home")}
fillColor="brand500"
@ -63,6 +64,7 @@ export default function OrderSuccess() {
/>
<MyButton
testID="order-success-view-orders"
textContent="View My Orders"
onPress={() => {
router.dismissAll();

View file

@ -29,7 +29,10 @@ function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
};
return (
<View style={tw`bg-white rounded-lg p-4 mb-3 shadow-sm border border-gray-100`}>
<View
testID={`address-card-${address.id}`}
style={tw`bg-white rounded-lg p-4 mb-3 shadow-sm border border-gray-100`}
>
<View style={tw`flex-row justify-between items-start mb-2`}>
<View style={tw`flex-1`}>
<View style={tw`flex-row items-center mb-1`}>
@ -54,6 +57,7 @@ function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
<View style={tw`flex-row justify-end mt-3 space-x-2`}>
{!address.isDefault && (
<MyTouchableOpacity
testID={`address-set-default-${address.id}`}
style={tw`bg-gray-500 px-3 py-2 rounded mr-2`}
onPress={() => onSetDefault(address.id)}
>
@ -61,12 +65,14 @@ function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
</MyTouchableOpacity>
)}
<MyTouchableOpacity
testID={`address-edit-${address.id}`}
style={tw`bg-blue-500 px-3 py-2 rounded mr-2`}
onPress={() => onEdit(address)}
>
<MyText style={tw`text-white text-xs font-medium`}>Edit</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID={`address-delete-${address.id}`}
style={tw`bg-red-500 px-3 py-2 rounded ${isDeleting ? 'opacity-50' : ''}`}
onPress={() => onDelete(address.id)}
disabled={isDeleting}
@ -201,6 +207,7 @@ export default function Addresses() {
Failed to load addresses. Please try again.
</MyText>
<MyTouchableOpacity
testID="addresses-retry-button"
style={tw`bg-blue-500 px-4 py-2 rounded`}
onPress={() => refetch()}
>
@ -230,6 +237,7 @@ export default function Addresses() {
My Addresses
</MyText>
<MyTouchableOpacity
testID="addresses-add-button"
style={tw`bg-blue-500 p-2 rounded-full`}
onPress={handleAddAddress}
>
@ -247,6 +255,7 @@ export default function Addresses() {
Add your first delivery address
</MyText>
<MyTouchableOpacity
testID="addresses-empty-add-button"
style={tw`bg-blue-500 px-6 py-3 rounded-lg`}
onPress={handleAddAddress}
>
@ -289,6 +298,7 @@ export default function Addresses() {
</View>
<MyText style={tw`text-sm text-slate-600 mb-5`}>{deleteError}</MyText>
<MyTouchableOpacity
testID="address-delete-error-ok"
onPress={() => setDeleteError(null)}
style={tw`bg-brand500 py-3.5 rounded-xl items-center`}
>

View file

@ -10,7 +10,7 @@ import { useRouter } from 'expo-router';
import type { ComplaintItemProps } from '@packages/shared';
const ComplaintItem: React.FC<ComplaintItemProps> = ({ item }) => (
<View style={tw`bg-white rounded-2xl p-5 mb-4 shadow-sm border border-gray-100`}>
<View testID={`complaint-item-${item.id}`} style={tw`bg-white rounded-2xl p-5 mb-4 shadow-sm border border-gray-100`}>
{/* Header: ID, Date, Status */}
<View style={tw`flex-row justify-between items-start mb-3`}>
<View>
@ -109,6 +109,7 @@ export default function Complaints() {
return (
<View style={tw`flex-1 bg-gray-50`}>
<MyFlatList
testID="complaints-list"
data={complaints}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => <ComplaintItem item={item} />}
@ -124,6 +125,7 @@ export default function Complaints() {
<View style={tw`flex-col`}>
<TouchableOpacity
testID="complaints-call-button"
style={tw`w-full bg-white rounded-xl p-3 mb-3 flex-row items-center`}
onPress={() => {
const phone = constsData?.supportMobile || '8688182552';
@ -142,6 +144,7 @@ export default function Complaints() {
</TouchableOpacity>
<TouchableOpacity
testID="complaints-email-button"
style={tw`w-full bg-white rounded-xl p-3 flex-row items-center`}
onPress={() => {
const email = constsData?.supportEmail || 'qushammohd@gmail.com';
@ -171,6 +174,7 @@ export default function Complaints() {
You haven&apos;t raised any complaints yet. That&apos;s great!
</MyText>
<MyTouchableOpacity
testID="complaints-continue-shopping"
onPress={() => router.push('/(drawer)/(tabs)/home')}
style={tw`mt-8 bg-brand500 px-6 py-3 rounded-xl shadow-sm`}
>

View file

@ -44,7 +44,7 @@ function CouponCard({ coupon }: CouponCardProps) {
};
return (
<View style={tw`bg-white rounded-lg p-4 mb-3 shadow-sm border border-gray-100`}>
<View testID={`coupon-card-${coupon.id}`} style={tw`bg-white rounded-lg p-4 mb-3 shadow-sm border border-gray-100`}>
<View style={tw`flex-row justify-between items-start mb-2`}>
<View style={tw`flex-1`}>
<MyText weight="semibold" style={tw`text-lg text-gray-800 mb-1`}>
@ -55,11 +55,11 @@ function CouponCard({ coupon }: CouponCardProps) {
</MyText>
</View>
<View style={tw`items-end`}>
<MyText style={tw`${getStatusColor()} text-sm font-medium mb-1`}>
<MyText testID={`coupon-status-${coupon.id}`} style={tw`${getStatusColor()} text-sm font-medium mb-1`}>
{getStatusText()}
</MyText>
{coupon.maxLimitForUser && (
<MyText style={tw`text-xs text-gray-500`}>
<MyText testID={`coupon-usage-${coupon.id}`} style={tw`text-xs text-gray-500`}>
Used: {coupon.usageCount}/{coupon.maxLimitForUser}
</MyText>
)}
@ -67,10 +67,11 @@ function CouponCard({ coupon }: CouponCardProps) {
</View>
<View style={tw`flex-row justify-between items-center`}>
<MyText style={tw`text-xs text-gray-500`}>
<MyText testID={`coupon-validity-${coupon.id}`} style={tw`text-xs text-gray-500`}>
Valid till: {formatDate(coupon.validTill)}
</MyText>
<MyTouchableOpacity
testID={`coupon-apply-${coupon.id}`}
style={tw`bg-blue-500 px-3 py-1 rounded-full`}
disabled={coupon.isExpired || coupon.isUsedUp}
>
@ -180,6 +181,7 @@ export default function Coupons() {
<View style={tw`flex-1 p-4`}>
{from === 'cart' && (
<MyTouchableOpacity
testID="coupon-back"
onPress={() => router.navigate('/(drawer)/(tabs)/home/cart')}
style={tw`p-2 -ml-2 mr-1 mb-2 self-start`}
activeOpacity={0.7}
@ -192,12 +194,14 @@ export default function Coupons() {
Add a Coupon
</MyText>
<MyTextInput
testID="coupon-code-input"
placeholder="Enter coupon code"
value={couponCode}
onChangeText={setCouponCode}
style={tw`mb-4`}
/>
<MyTouchableOpacity
testID="coupon-add"
style={tw`bg-blue-500 px-4 py-3 rounded-lg items-center ${
redeemCouponMutation.isPending || couponCode.trim().length < 4 ? 'opacity-50' : ''
}`}

View file

@ -103,6 +103,7 @@ function EditProfile() {
<View style={tw`mt-8`}>
<MyButton
testID="edit-profile-logout-button"
textContent="Logout"
onPress={logout}
fillColor="gray1"
@ -113,6 +114,7 @@ function EditProfile() {
<View style={tw`mt-4`}>
<MyButton
testID="delete-account-button"
textContent="Delete Me and My Data"
onPress={handleDeleteAccount}
fillColor="error"
@ -126,7 +128,7 @@ function EditProfile() {
onClose={() => setShowDeleteModal(false)}
enableDismiss={false}
>
<View style={tw`p-4`}>
<View testID="delete-account-dialog" style={tw`p-4`}>
<MyText weight="bold" style={tw`text-xl mb-4 text-center text-red-600`}>
⚠️ Delete Account Permanently
</MyText>
@ -141,6 +143,7 @@ function EditProfile() {
<View style={tw`mb-6`}>
<TextInput
testID="delete-account-mobile-input"
value={mobileInputValue}
onChangeText={setEnteredMobile}
placeholder="Enter mobile number"
@ -155,6 +158,7 @@ function EditProfile() {
<View style={tw`flex-row gap-3`}>
<View style={tw`flex-1`}>
<MyButton
testID="delete-account-cancel-button"
textContent="Cancel"
onPress={() => setShowDeleteModal(false)}
fillColor="gray1"
@ -164,6 +168,7 @@ function EditProfile() {
</View>
<View style={tw`flex-1`}>
<MyButton
testID="delete-account-confirm-button"
textContent="Delete Forever"
onPress={confirmDeleteAccount}
fillColor="error"

View file

@ -122,6 +122,7 @@ export default function Me() {
</MyText>
</View>
<MyTouchableOpacity
testID="me-settings"
style={tw`bg-gray-100 p-3 rounded-2xl`}
onPress={() => router.push('/(drawer)/(tabs)/me/edit-profile')}
>
@ -143,6 +144,7 @@ export default function Me() {
{section.items.map((item, iIndex) => (
<MyTouchableOpacity
key={iIndex}
testID={`me-menu-${item.title.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`}
onPress={item.onPress}
style={tw`flex-row items-center p-4.5 ${iIndex !== section.items.length - 1 ? 'border-b border-gray-50' : ''}`}
>
@ -164,6 +166,7 @@ export default function Me() {
{/* Footer / Logout */}
<MyTouchableOpacity
testID="me-logout"
style={tw`flex-row items-center justify-center p-5 bg-white rounded-[24px] border border-red-50 shadow-sm mt-2`}
onPress={() => logout()}
>
@ -171,7 +174,7 @@ export default function Me() {
<MyText style={tw`text-rose-500 font-bold text-base`}>Log Out from Freshyo</MyText>
</MyTouchableOpacity>
<MyText style={tw`text-center text-gray-300 text-[10px] mt-12 uppercase tracking-[3px]`}>
<MyText testID="me-version" style={tw`text-center text-gray-300 text-[10px] mt-12 uppercase tracking-[3px]`}>
Version 1.2.0 • Freshyo App
</MyText>
</View>

View file

@ -78,7 +78,7 @@ export default function OrderDetails() {
if (isLoading) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center bg-white`}>
<View testID="order-detail-loading" style={tw`flex-1 justify-center items-center bg-white`}>
<MyText style={tw`text-slate-400 font-medium`}>Loading details...</MyText>
</View>
</AppContainer>
@ -88,10 +88,11 @@ export default function OrderDetails() {
if (error || !orderData) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center p-8 bg-white`}>
<View testID="order-detail-error" style={tw`flex-1 justify-center items-center p-8 bg-white`}>
<MaterialIcons name="error-outline" size={48} color={theme.colors.red1} />
<MyText style={tw`text-slate-900 text-lg font-bold mt-4`}>Failed to load</MyText>
<MyTouchableOpacity
testID="order-detail-go-back"
onPress={() => router.back()}
style={tw`mt-6 bg-slate-900 px-6 py-2 rounded-xl`}
>
@ -134,6 +135,7 @@ export default function OrderDetails() {
<View style={tw`bg-white px-6 pt-4 pb-4 border-b border-slate-100 flex-row items-center justify-between`}>
<View style={tw`flex-row items-center`}>
<MyTouchableOpacity
testID="order-detail-header-back"
onPress={() => router.back()}
style={tw`mr-3 p-2 -ml-2`}
>
@ -154,7 +156,7 @@ export default function OrderDetails() {
</View>
</View>
<View style={tw`flex-row items-center gap-2`}>
<View style={[tw`px-3 py-1 rounded-full`, { backgroundColor: statusConfig.color + '10' }]}>
<View testID="order-detail-status" style={[tw`px-3 py-1 rounded-full`, { backgroundColor: statusConfig.color + '10' }]}>
<MyText style={[tw`text-[10px] font-bold uppercase`, { color: statusConfig.color }]}>
{orderStatusManipulator(statusConfig.label)}
</MyText>
@ -170,7 +172,7 @@ export default function OrderDetails() {
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={tw`p-4 pb-12`}>
{/* 1 Hr Delivery Banner */}
{order.isFlashDelivery && (
<View style={tw`bg-gradient-to-r from-amber-50 to-yellow-50 border border-amber-200 rounded-2xl p-4 mb-4`}>
<View testID="order-flash-banner" style={tw`bg-gradient-to-r from-amber-50 to-yellow-50 border border-amber-200 rounded-2xl p-4 mb-4`}>
<View style={tw`flex-row items-center`}>
<MaterialIcons name="bolt" size={24} color="#D97706" />
<View style={tw`ml-3 flex-1`}>
@ -192,7 +194,7 @@ export default function OrderDetails() {
{/* Main Info Card */}
<View style={tw`bg-white rounded-2xl p-5 mb-4 border border-slate-100`}>
{(order.deliveryDate || order.isFlashDelivery) && ["delivered", "success"].includes(order.deliveryStatus?.toLowerCase() || "") && (
<View style={tw`flex-row items-center pt-4 border-t border-slate-50`}>
<View testID="order-delivered-row" style={tw`flex-row items-center pt-4 border-t border-slate-50`}>
{order.isFlashDelivery ? (
<MaterialIcons name="bolt" size={18} color="#D97706" />
) : (
@ -225,6 +227,7 @@ export default function OrderDetails() {
{isEditingNotes ? (
<View style={tw`flex-row gap-2`}>
<MyTouchableOpacity
testID="order-notes-cancel"
onPress={() => {
setIsEditingNotes(false);
setNotesInput(notesText);
@ -234,6 +237,7 @@ export default function OrderDetails() {
<MyText style={tw`text-slate-600 text-xs font-bold`}>Cancel</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="order-notes-save"
onPress={() => {
updateNotesMutation.mutate({ id: order.id, userNotes: notesInput });
}}
@ -247,6 +251,7 @@ export default function OrderDetails() {
</View>
) : (
<MyTouchableOpacity
testID="order-notes-edit"
onPress={() => {
setNotesInput(notesText || "");
setIsEditingNotes(true);
@ -262,6 +267,7 @@ export default function OrderDetails() {
</View>
{isEditingNotes ? (
<TextInput
testID="order-notes-input"
style={tw`bg-slate-50 border border-slate-200 rounded-xl p-3 min-h-20 text-sm text-slate-700`}
value={notesInput}
onChangeText={setNotesInput}
@ -272,7 +278,7 @@ export default function OrderDetails() {
textAlignVertical="top"
/>
) : (
<MyText style={tw`text-slate-700 text-sm leading-5`}>
<MyText testID="order-notes-text" style={tw`text-slate-700 text-sm leading-5`}>
{notesText || "No instructions added"}
</MyText>
)}
@ -326,35 +332,37 @@ export default function OrderDetails() {
<View style={tw`bg-white rounded-2xl p-5 mb-6 border border-slate-100`}>
<View style={tw`flex-row justify-between mb-3`}>
<MyText style={tw`text-slate-500 text-sm`}>Subtotal</MyText>
<MyText style={tw`text-slate-900 font-medium`}>₹{subtotal}</MyText>
<MyText testID="order-summary-subtotal" style={tw`text-slate-900 font-medium`}>₹{subtotal}</MyText>
</View>
{discountAmount > 0 && (
<View style={tw`flex-row justify-between mb-3`}>
<MyText style={tw`text-emerald-600 text-sm`}>Discount</MyText>
<MyText style={tw`text-emerald-600 font-medium`}>-₹{discountAmount}</MyText>
<MyText testID="order-summary-discount" style={tw`text-emerald-600 font-medium`}>-₹{discountAmount}</MyText>
</View>
)}
<View style={tw`flex-row justify-between mb-3`}>
<MyText style={tw`text-slate-500 text-sm`}>Delivery</MyText>
<MyText style={tw`text-slate-900 font-medium`}>
<MyText testID="order-summary-delivery" style={tw`text-slate-900 font-medium`}>
{deliveryCharge > 0 ? `₹${deliveryCharge}` : 'Free'}
</MyText>
</View>
<View style={tw`pt-4 border-t border-slate-50 flex-row justify-between items-center`}>
<MyText style={tw`text-slate-900 font-bold text-base`}>Total Amount</MyText>
<MyText style={tw`text-slate-900 font-bold text-xl`}>₹{totalAmount}</MyText>
<MyText testID="order-summary-total" style={tw`text-slate-900 font-bold text-xl`}>₹{totalAmount}</MyText>
</View>
</View>
{/* Footer Actions */}
<View style={tw`flex-row gap-3`}>
<MyTouchableOpacity
testID="order-detail-back"
onPress={() => router.replace('/(drawer)/(tabs)/me')}
style={tw`flex-1 bg-slate-100 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-slate-600 font-bold`}>Back</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="order-raise-complaint"
onPress={() => setComplaintDialogOpen(true)}
style={[tw`flex-1 py-3.5 rounded-xl items-center`, { backgroundColor: theme.colors.brand600 }]}
>
@ -366,6 +374,7 @@ export default function OrderDetails() {
<View style={tw`mt-4`}>
{order.deliveryStatus !== 'success' && order.deliveryStatus !== 'cancelled' && (
<MyTouchableOpacity
testID="order-cancel-order"
onPress={() => setCancelDialogOpen(true)}
style={tw`bg-red-50 border border-red-100 py-3.5 rounded-xl items-center flex-row justify-center`}
>
@ -407,6 +416,7 @@ export default function OrderDetails() {
/>
<MyTouchableOpacity
testID="order-cancel-confirm"
style={tw`bg-red-600 py-4 rounded-xl shadow-sm items-center ${cancelOrderMutation.isPending ? 'opacity-70' : ''}`}
onPress={handleCancelOrder}
disabled={cancelOrderMutation.isPending}

View file

@ -30,7 +30,7 @@ const OrderFooter: React.FC<OrderFooterProps> = ({
}) => {
if (isLoadingMore) {
return (
<View style={tw`py-6 items-center`}>
<View testID="orders-loading-more" style={tw`py-6 items-center`}>
<ActivityIndicator size="small" color="#3B82F6" />
<MyText style={tw`text-gray-500 mt-2 text-sm`}>Loading more orders...</MyText>
</View>
@ -39,9 +39,10 @@ const OrderFooter: React.FC<OrderFooterProps> = ({
if (loadMoreError) {
return (
<View style={tw`py-6 items-center`}>
<View testID="orders-load-more-error" style={tw`py-6 items-center`}>
<MyText style={tw`text-red-500 text-sm mb-2`}>{loadMoreError}</MyText>
<MyTouchableOpacity
testID="orders-retry-more"
onPress={onRetryLoadMore}
style={tw`bg-blue-500 px-4 py-2 rounded-lg`}
>
@ -53,7 +54,7 @@ const OrderFooter: React.FC<OrderFooterProps> = ({
if (!hasNextPage && allOrders.length > 0) {
return (
<View style={tw`py-6 items-center`}>
<View testID="orders-end-of-list" style={tw`py-6 items-center`}>
<MyText style={tw`text-gray-400 text-xs`}>End of list</MyText>
</View>
);
@ -85,6 +86,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
return (
<MyTouchableOpacity
testID={`order-card-${item.orderId}`}
style={tw`bg-white rounded-[28px] mb-6 border border-slate-100 shadow-sm overflow-hidden`}
onPress={() => onPress(item.id)}
activeOpacity={0.95}
@ -101,7 +103,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
<View style={tw`flex-row items-center gap-2`}>
{item.orderStatus.toLowerCase() === 'cancelled' && (
<View style={[tw`flex-row items-center px-3 py-1.5 rounded-full border ${mainStatus.bg} ${mainStatus.border}`]}>
<View testID={`order-status-chip-${item.orderId}`} style={[tw`flex-row items-center px-3 py-1.5 rounded-full border ${mainStatus.bg} ${mainStatus.border}`]}>
<MaterialIcons name={mainStatus.icon as any} size={14} color={mainStatus.color} />
<MyText style={[tw`text-[11px] font-bold ml-1.5 uppercase tracking-wide`, { color: mainStatus.color }]}>
{orderStatusManipulator(mainStatus.label)}
@ -214,6 +216,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
{item.items.length > 2 && (
<MyTouchableOpacity
testID={`order-more-items-${item.orderId}`}
style={tw`mt-2 pt-2 border-t border-slate-100 items-center`}
onPress={() => onViewMoreItems(item.id)}
>
@ -237,7 +240,7 @@ const OrderItem: React.FC<OrderItemProps> = ({
<MyText style={tw`text-[10px] font-bold text-slate-400 uppercase mr-2`}>
{item.isFlashDelivery ? "1 Hr Delivery:" : "Shipping Status:"}
</MyText>
<MyText style={[tw`text-xs font-bold`, item.isFlashDelivery ? tw`text-amber-700` : { color: deliveryStatus.color }]} numberOfLines={1}>
<MyText testID={`order-delivery-status-${item.orderId}`} style={[tw`text-xs font-bold`, item.isFlashDelivery ? tw`text-amber-700` : { color: deliveryStatus.color }]} numberOfLines={1}>
{orderStatusManipulator(item.deliveryStatus)}
</MyText>
</View>
@ -455,7 +458,7 @@ export default function MyOrders() {
if (isLoading && currentPage === 1) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<View testID="orders-loading" style={tw`flex-1 justify-center items-center bg-gray-50`}>
<ActivityIndicator size="large" color="#3B82F6" />
<MyText style={tw`text-gray-500 mt-4 font-medium`}>Loading your orders...</MyText>
</View>
@ -464,13 +467,14 @@ export default function MyOrders() {
if (error) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50 p-6`}>
<View testID="orders-error" style={tw`flex-1 justify-center items-center bg-gray-50 p-6`}>
<View style={tw`bg-white p-6 rounded-full shadow-sm mb-4`}>
<MaterialIcons name="error-outline" size={48} color="#EF4444" />
</View>
<MyText style={tw`text-gray-900 text-xl font-bold mt-2`}>Unable to load orders</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 mb-6`}>Please check your connection and try again</MyText>
<MyTouchableOpacity
testID="orders-retry"
onPress={() => refetch()}
style={tw`bg-blue-600 px-8 py-3 rounded-full shadow-md`}
>
@ -483,6 +487,7 @@ export default function MyOrders() {
return (
<View style={tw`flex-1 bg-gray-50`}>
<MyFlatList
testID="orders-list"
style={tw`flex-1`}
contentContainerStyle={tw`px-4 py-6`}
data={allOrders}
@ -513,13 +518,14 @@ export default function MyOrders() {
/>
}
ListEmptyComponent={
<View style={tw`flex-1 justify-center items-center py-20`}>
<View testID="orders-empty" style={tw`flex-1 justify-center items-center py-20`}>
<View style={tw`bg-white p-6 rounded-full shadow-sm mb-4`}>
<MaterialIcons name="shopping-bag" size={64} color="#E5E7EB" />
</View>
<MyText style={tw`text-gray-900 text-lg font-bold mt-2`}>No orders yet</MyText>
<MyText style={tw`text-gray-500 text-center mt-2`}>Your order history will appear here</MyText>
<MyTouchableOpacity
testID="orders-start-shopping"
style={tw`mt-6 bg-blue-600 px-6 py-3 rounded-full`}
onPress={() => router.push('/(drawer)/(tabs)/home')}
>

View file

@ -14,6 +14,7 @@ export default function TermsAndConditions() {
{/* Header */}
<View style={tw`flex-row items-center px-4 py-4 bg-white border-b border-gray-100`}>
<MyTouchableOpacity
testID="terms-back"
onPress={() => router.back()}
style={tw`p-2 -ml-2`}
>

View file

@ -41,11 +41,12 @@ const StoreCard = ({
return (
<View
testID="store-card"
style={tw`bg-white rounded-[24px] mb-4 shadow-lg shadow-slate-200 border border-slate-200 overflow-hidden`}
>
{/* Meat Store Images - Show at top if store name contains 'meat' */}
{isMeatStore && (
<View style={tw`flex-row h-16`}>
<View style={tw`flex-row h-16`} testID="store-meat-banner">
<Image
source={{ uri: `${ASSETS_BASE_URL}/halal.jpg` }}
style={tw`flex-1 h-full`}
@ -62,6 +63,7 @@ const StoreCard = ({
{/* Top Header Section - Touchable */}
<MyTouchableOpacity
testID="store-card-header"
onPress={navigateToStore}
activeOpacity={0.7}
style={tw`p-4 pb-0`}
@ -74,20 +76,20 @@ const StoreCard = ({
contentFit="cover"
/>
{!item.signedImageUrl && (
<View style={tw`absolute inset-0 items-center justify-center`}>
<View style={tw`absolute inset-0 items-center justify-center`} testID="store-image-fallback">
<MaterialIcons name="storefront" size={20} color="#94A3B8" />
</View>
)}
</View>
<View style={tw`flex-1 ml-3`}>
<MyText style={tw`text-slate-900 font-extrabold text-lg`} numberOfLines={1}>
<MyText testID="store-card-name" style={tw`text-slate-900 font-extrabold text-lg`} numberOfLines={1}>
{item.name}
</MyText>
</View>
<View style={tw`bg-brand50 px-2.5 py-1.5 rounded-xl border border-brand100 items-center justify-center`}>
<MyText style={tw`text-brand700 text-sm font-black`}>{item.productCount}</MyText>
<MyText testID="store-card-count" style={tw`text-brand700 text-sm font-black`}>{item.productCount}</MyText>
<MyText style={tw`text-brand600 text-[8px] font-black uppercase tracking-tighter`}>Items</MyText>
</View>
</View>
@ -103,6 +105,7 @@ const StoreCard = ({
keyExtractor={(product) => product.id.toString()}
renderItem={({ item: product }) => (
<MyTouchableOpacity
testID="store-sample-product"
onPress={navigateToStore}
activeOpacity={0.85}
style={tw`mr-3 items-center w-24`}
@ -123,6 +126,7 @@ const StoreCard = ({
ListFooterComponent={remainingCount > 0 ? (
<View style={tw`items-center justify-center`}>
<MyTouchableOpacity
testID="store-discover-more"
onPress={navigateToStore}
style={tw`bg-slate-900 w-24 h-24 rounded-2xl items-center justify-center shadow-md`}
>
@ -138,6 +142,7 @@ const StoreCard = ({
<View style={tw`px-4 pb-4`}>
<MyTouchableOpacity
testID="store-explore"
onPress={navigateToStore}
activeOpacity={0.9}
style={tw`bg-brand600 py-3 rounded-[18px] flex-row items-center justify-center shadow-lg shadow-brand200`}
@ -177,7 +182,7 @@ export default function Stores() {
if (isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-slate-50`}>
<View style={tw`flex-1 justify-center items-center bg-slate-50`} testID="stores-loading">
<View style={tw`w-20 h-20 items-center justify-center`}>
<MaterialIcons name="storefront" size={48} color={theme.colors.brand200} />
</View>
@ -188,7 +193,7 @@ export default function Stores() {
if (error) {
return (
<View style={tw`flex-1 justify-center items-center bg-slate-50 p-10`}>
<View style={tw`flex-1 justify-center items-center bg-slate-50 p-10`} testID="stores-error">
<View style={tw`w-20 h-20 bg-rose-50 rounded-full items-center justify-center mb-6`}>
<MaterialIcons name="error-outline" size={32} color={theme.colors.red1} />
</View>
@ -197,6 +202,7 @@ export default function Stores() {
We couldn't reach our vendor network.
</MyText>
<MyTouchableOpacity
testID="stores-retry"
onPress={() => refetch()}
style={tw`bg-brand600 px-8 py-3 rounded-2xl shadow-lg shadow-brand200`}
>
@ -210,6 +216,7 @@ export default function Stores() {
<TabLayoutWrapper>
<View style={tw`flex-1 bg-slate-50 relative`}>
<MyFlatList
testID="stores-list"
data={stores}
renderItem={({ item }) => <StoreCard item={item} router={router} />}
keyExtractor={(item) => item.id.toString()}
@ -240,7 +247,7 @@ export default function Stores() {
</View>
}
ListEmptyComponent={
<View style={tw`flex-1 justify-center items-center py-20`}>
<View style={tw`flex-1 justify-center items-center py-20`} testID="stores-empty">
<View style={tw`w-24 h-24 bg-white rounded-full items-center justify-center mb-6 shadow-sm`}>
<Ionicons name="storefront-outline" size={48} color="#94A3B8" />
</View>

View file

@ -27,6 +27,7 @@ const Chip: React.FC<TagChipProps> = ({ tag, isSelected, onPress }) => {
return (
<TouchableOpacity
testID="store-tag-chip"
onPress={onPress}
style={tw`px-4 py-2 rounded-lg border ${
isSelected
@ -99,7 +100,7 @@ export default function StoreDetail() {
if (isLoading || isProductsLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<View style={tw`flex-1 justify-center items-center bg-gray-50`} testID="store-detail-loading">
<MyText style={tw`text-gray-500 font-medium`}>
{isLoading ? 'Loading store...' : 'Loading products...'}
</MyText>
@ -109,7 +110,7 @@ export default function StoreDetail() {
if (error || !storeData) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<View style={tw`flex-1 justify-center items-center bg-gray-50`} testID="store-detail-error">
<MaterialIcons name="error-outline" size={48} color="#EF4444" />
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
<MyText style={tw`text-gray-500 mt-2`}>
@ -122,6 +123,7 @@ export default function StoreDetail() {
return (
<View style={tw`flex-1 bg-gray-50 relative`}>
<MyFlatList
testID="store-detail-list"
data={filteredProducts}
numColumns={2}
renderItem={({ item }) => (
@ -145,7 +147,7 @@ export default function StoreDetail() {
<View style={tw`pt-4 pb-6`}>
{/* Meat Store Images - Show at top if store name contains 'meat' */}
{storeData?.store?.name?.toLowerCase().includes('meat') && (
<View style={tw`flex-row h-16 mb-4`}>
<View style={tw`flex-row h-16 mb-4`} testID="store-detail-meat-banner">
<Image
source={{ uri: 'http://localhost:4000/assets/halal.jpg' }}
style={tw`flex-1 h-full`}
@ -172,12 +174,14 @@ export default function StoreDetail() {
/>
</View>
<MyText
testID="store-detail-name"
style={tw`text-2xl font-bold text-gray-900 text-center mb-2`}
>
{storeData?.store?.name}
</MyText>
{storeData?.store?.description && (
<MyText
testID="store-detail-description"
style={tw`text-gray-500 text-center leading-5 px-4`}
>
{storeData?.store?.description}
@ -187,6 +191,7 @@ export default function StoreDetail() {
{/* Tags Section */}
{storeData?.tags && storeData.tags.length > 0 && (
<ScrollView
testID="store-detail-tags"
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={tw`gap-2 mt-6`}
@ -205,7 +210,7 @@ export default function StoreDetail() {
<View style={tw`flex-row items-center justify-between mt-6 mb-2`}>
<View style={tw`flex-row items-center`}>
<MaterialIcons name="grid-view" size={20} color="#374151" />
<MyText style={tw`text-lg font-bold text-gray-900 ml-2`}>
<MyText testID="store-detail-heading" style={tw`text-lg font-bold text-gray-900 ml-2`}>
{selectedTagId
? `${storeData?.tags.find(t => t.id === selectedTagId)?.tagName} items`
: `${filteredProducts.length} products`}
@ -213,6 +218,7 @@ export default function StoreDetail() {
</View>
{selectedTagId && (
<TouchableOpacity
testID="store-detail-clear"
onPress={() => setSelectedTagId(null)}
style={tw`flex-row items-center`}
>

View file

@ -53,7 +53,7 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) =>
<View style={tw`flex-1 bg-gray-50`}>
<View style={tw`bg-white px-4 py-3 border-b border-gray-100 mt-6`}>
<View style={tw`flex-row items-center`}>
<MyTouchableOpacity onPress={onBack} style={tw`p-2 -ml-2 mr-1`} activeOpacity={0.7}>
<MyTouchableOpacity testID="cart-address-gate-back" onPress={onBack} style={tw`p-2 -ml-2 mr-1`} activeOpacity={0.7}>
<MaterialIcons name="chevron-left" size={28} color="#374151" />
</MyTouchableOpacity>
<MyText style={tw`text-lg font-bold text-gray-900`}>Add Delivery Address</MyText>

View file

@ -26,7 +26,7 @@ const CheckoutAddressDisplay: React.FC = () => {
null
return (
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<View testID="checkout-address" style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<View style={tw`flex-row items-center mb-3`}>
<View style={tw`w-8 h-8 bg-blue-50 rounded-full items-center justify-center mr-3`}>
<MaterialIcons name="location-on" size={18} color="#3B82F6" />
@ -35,7 +35,7 @@ const CheckoutAddressDisplay: React.FC = () => {
</View>
{isLoading ? (
<MyText style={tw`text-gray-500`}>Loading address...</MyText>
<MyText testID="checkout-address-loading" style={tw`text-gray-500`}>Loading address...</MyText>
) : address ? (
<View style={tw`bg-gray-50 p-4 rounded-xl border border-gray-200`}>
<View style={tw`flex-row items-center mb-2`}>
@ -50,7 +50,7 @@ const CheckoutAddressDisplay: React.FC = () => {
size={20}
color="#6B7280"
/>
<MyText style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText>
<MyText testID="checkout-address-name" style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText>
</View>
<MyText style={tw`text-gray-600 text-sm leading-5 mb-1`} numberOfLines={2}>
{address.addressLine1}
@ -63,6 +63,7 @@ const CheckoutAddressDisplay: React.FC = () => {
</View>
) : (
<View
testID="checkout-address-empty"
style={tw`bg-gray-50 p-6 rounded-xl border border-gray-200 border-dashed items-center justify-center`}
>
<MaterialIcons name="location-off" size={32} color="#9CA3AF" />

View file

@ -180,7 +180,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
Delivery Address
</Text>
</View>
<TouchableOpacity onPress={() => setShowAddAddress(true)}>
<TouchableOpacity testID="add-new-address" onPress={() => setShowAddAddress(true)}>
<Text style={tw`text-brand500 font-bold text-sm`}>+ Add New</Text>
</TouchableOpacity>
</View>
@ -189,12 +189,13 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
<View style={tw`bg-gray-50 p-6 rounded-xl border border-gray-200 border-dashed items-center justify-center`}>
<MaterialIcons name="location-off" size={32} color="#9CA3AF" />
<Text style={tw`text-gray-500 mt-2`}>No addresses found</Text>
<TouchableOpacity onPress={() => setShowAddAddress(true)} style={tw`mt-3 bg-brand500 px-4 py-2 rounded-lg`}>
<TouchableOpacity testID="add-address-empty" onPress={() => setShowAddAddress(true)} style={tw`mt-3 bg-brand500 px-4 py-2 rounded-lg`}>
<Text style={tw`text-white font-bold text-sm`}>Add Address</Text>
</TouchableOpacity>
</View>
) : (
<ScrollView
testID="address-scroll"
ref={scrollViewRef}
horizontal
showsHorizontalScrollIndicator={false}
@ -250,6 +251,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
{sortedAddresses.map((_, index: number) => (
<View
key={index}
testID={`address-dot-${index}`}
style={tw`w-2 h-2 rounded-full mx-1 ${
index === currentIndex ? 'bg-brand500' : 'bg-gray-300'
}`}
@ -267,6 +269,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
No Location is attached to address
</MyText>
<TouchableOpacity
testID="attach-location"
onPress={() => handleAttachLocation(selectedAddr)}
disabled={locationLoading && editingLocationAddressId === selectedAddr.id}
style={tw`mt-2 py-2 px-3 bg-blue-50 rounded-lg self-start`}

View file

@ -80,13 +80,14 @@ export default function ComplaintForm({ open, onClose, orderId }: ComplaintFormP
<View style={tw`p-6`}>
<View style={tw`flex-row justify-between items-center mb-4`}>
<MyText style={tw`text-xl font-bold text-gray-900`}>Raise Complaint</MyText>
<MyTouchableOpacity onPress={onClose}>
<MyTouchableOpacity testID="complaint-close" onPress={onClose}>
<MaterialIcons name="close" size={24} color="#9CA3AF" />
</MyTouchableOpacity>
</View>
<MyText style={tw`text-gray-700 font-medium mb-2`}>Describe the issue</MyText>
<TextInput
testID="complaint-body"
style={tw`bg-gray-50 border border-gray-200 rounded-xl p-4 min-h-32 text-base text-gray-800 mb-4`}
value={complaintBody}
onChangeText={setComplaintBody}
@ -98,18 +99,20 @@ export default function ComplaintForm({ open, onClose, orderId }: ComplaintFormP
/>
<ImageUploaderNeo
testID="complaint-images"
images={complaintImages}
onImageAdd={handleAddImages}
onImageRemove={handleRemoveImage}
/>
<MyTouchableOpacity
testID="complaint-submit"
style={tw`bg-yellow-500 py-4 rounded-xl shadow-sm items-center mt-4 ${raiseComplaintMutation.isPending || isUploading ? 'opacity-70' : ''}`}
onPress={handleSubmit}
disabled={raiseComplaintMutation.isPending || isUploading}
>
{raiseComplaintMutation.isPending || isUploading ? (
<ActivityIndicator color="white" />
<ActivityIndicator testID="complaint-submit-spinner" color="white" />
) : (
<MyText style={tw`text-white font-bold text-lg`}>Submit Complaint</MyText>
)}

View file

@ -11,7 +11,7 @@ import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow
const LOCATION_POLL_MS = 3000
const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
<View style={tw`flex-1 justify-center items-center bg-white`}>
<View testID="location-loading" style={tw`flex-1 justify-center items-center bg-white`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
{label ? <MyText style={tw`text-gray-500 mt-4`}>{label}</MyText> : null}
</View>

View file

@ -41,20 +41,21 @@ const LoginWall: React.FC<LoginWallProps> = ({
}
return (
<View style={tw`flex-1 bg-gray-50 justify-center items-center px-6`}>
<View testID="login-wall" style={tw`flex-1 bg-gray-50 justify-center items-center px-6`}>
<View style={tw`w-20 h-20 bg-blue-50 rounded-full items-center justify-center mb-4`}>
<MaterialIcons name="lock-outline" size={36} color="#2563EB" />
</View>
<MyText style={tw`text-lg font-bold text-gray-900`}>{title}</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 mb-6`}>{message}</MyText>
<MyTouchableOpacity
testID="login-wall-login"
style={tw`bg-brand500 px-6 py-3 rounded-xl`}
onPress={handleLogIn}
>
<MyText style={tw`text-white font-bold`}>Log In</MyText>
</MyTouchableOpacity>
{onBack && (
<MyTouchableOpacity style={tw`mt-4`} onPress={onBack}>
<MyTouchableOpacity testID="login-wall-back" style={tw`mt-4`} onPress={onBack}>
<MyText style={tw`text-gray-500 font-medium`}>Go Back</MyText>
</MyTouchableOpacity>
)}

View file

@ -40,6 +40,7 @@ function OrderCard({ order, onPress, supportMobile }: OrderCardProps) {
: dayjs(order.deliveryDate).format("DD MMM");
return (
<TouchableOpacity
testID={`next-order-card-${order.id}`}
style={{ width: CARD_WIDTH, marginRight: 24 }}
onPress={onPress}
activeOpacity={0.8}
@ -100,6 +101,7 @@ function OrderCard({ order, onPress, supportMobile }: OrderCardProps) {
{/* Support Mobile Number */}
{supportMobile && (
<TouchableOpacity
testID="next-order-support-call"
style={tw`flex-row items-center mt-3 pt-3 border-t border-amber-200`}
onPress={() => Linking.openURL(`tel:${supportMobile}`)}
>
@ -170,7 +172,7 @@ export default function NextOrderGlimpse() {
if (ordersLoading) {
return (
<View style={tw`px-6 mb-4`}>
<View testID="next-order-loading" style={tw`px-6 mb-4`}>
<View style={tw`bg-white rounded-2xl p-4 border border-gray-100`}>
<ActivityIndicator size="small" color="#3B82F6" />
</View>
@ -183,8 +185,9 @@ export default function NextOrderGlimpse() {
}
return (
<View style={tw`mb-4`}>
<View testID="next-order-glimpse" style={tw`mb-4`}>
<ScrollView
testID="next-order-scroll"
ref={scrollViewRef}
horizontal
showsHorizontalScrollIndicator={false}
@ -211,6 +214,7 @@ export default function NextOrderGlimpse() {
{upcomingOrders.map((_, index) => (
<View
key={index}
testID={`next-order-dot-${index}`}
style={tw`mx-1 w-2 h-2 rounded-full ${index === currentIndex ? 'bg-amber-500' : 'bg-amber-200'}`}
/>
))}

View file

@ -72,6 +72,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
<>
{/* Menu Trigger */}
<MyTouchableOpacity
testID="order-menu-trigger"
style={tw`w-10 h-10 rounded-full bg-white border border-slate-200 items-center justify-center shadow-sm`}
onPress={() => setOpen(true)}
>
@ -90,6 +91,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
<View style={tw`space-y-3`}>
<MyTouchableOpacity
testID="order-menu-view-details"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl shadow-sm`}
onPress={() => {
setOpen(false);
@ -107,6 +109,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="order-menu-edit-notes"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl shadow-sm`}
onPress={() => {
setOpen(false);
@ -127,6 +130,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="order-menu-raise-complaint"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl shadow-sm`}
onPress={() => setComplaintDialogOpen(true)}
>
@ -141,6 +145,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="order-menu-cancel-order"
style={tw`flex-row items-center p-4 bg-white border border-gray-100 rounded-xl shadow-sm`}
onPress={() => {
setOpen(false);
@ -172,6 +177,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
</View>
<TextInput
testID="order-menu-notes-input"
style={tw`bg-gray-50 border border-gray-200 rounded-xl p-4 min-h-32 text-base text-gray-800 mb-6`}
value={editNotes}
onChangeText={setEditNotes}
@ -183,6 +189,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
/>
<MyTouchableOpacity
testID="order-menu-save-notes"
style={tw`bg-blue-600 py-4 rounded-xl shadow-sm items-center ${updateNotesMutation.isPending ? 'opacity-70' : ''}`}
onPress={handleEditNotes}
disabled={updateNotesMutation.isPending}
@ -216,6 +223,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
<MyText style={tw`text-gray-700 font-medium mb-2`}>Reason for cancellation</MyText>
<TextInput
testID="order-menu-cancel-reason-input"
style={tw`bg-gray-50 border border-gray-200 rounded-xl p-4 min-h-24 text-base text-gray-800 mb-6`}
value={cancelReason}
onChangeText={setCancelReason}
@ -227,6 +235,7 @@ const OrderMenu: React.FC<OrderMenuProps> = ({ orderId, postActionHandler }) =>
/>
<MyTouchableOpacity
testID="order-menu-confirm-cancel"
style={tw`bg-red-600 py-4 rounded-xl shadow-sm items-center ${cancelOrderMutation.isPending ? 'opacity-70' : ''}`}
onPress={handleCancelOrder}
disabled={cancelOrderMutation.isPending}

View file

@ -49,12 +49,18 @@ export default function OrderStatusTracker({
return (
<View key={label} style={tw`flex-1 items-center`}>
<View style={tw`flex-row items-center w-full`}>
<View style={[tw`flex-1 h-0.5 rounded-full`, { backgroundColor: leftLine }]} />
<View
testID={`order-status-line-left-${label.toLowerCase()}`}
style={[tw`flex-1 h-0.5 rounded-full`, { backgroundColor: leftLine }]}
/>
<View
testID={`order-status-dot-${label.toLowerCase()}`}
style={[tw`w-3 h-3 rounded-full`, { backgroundColor: dotColor }]}
/>
<View style={[tw`flex-1 h-0.5 rounded-full`, { backgroundColor: rightLine }]} />
<View
testID={`order-status-line-right-${label.toLowerCase()}`}
style={[tw`flex-1 h-0.5 rounded-full`, { backgroundColor: rightLine }]}
/>
</View>
<MyText
style={[

View file

@ -173,6 +173,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
{onCancel && (
<View style={tw`bg-white p-4 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<MyTouchableOpacity
testID="payment-cancel"
onPress={onCancel}
style={tw`flex-row items-center`}
>
@ -187,6 +188,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
<MyText style={tw`text-lg font-bold text-gray-900 mb-4`}>Payment Method</MyText>
<MyTouchableOpacity
testID="payment-online-row"
disabled={true}
style={tw`flex-row items-center p-4 rounded-xl border mb-3 opacity-50 bg-gray-100`}
>
@ -203,6 +205,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
</MyTouchableOpacity>
<View
testID="payment-cod-row"
style={tw`flex-row items-center p-4 rounded-xl border border-brand500 bg-blue-50`}
>
<View style={tw`w-5 h-5 rounded-full border-2 border-brand500 items-center justify-center mr-3`}>
@ -236,14 +239,14 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
{/* Item Total */}
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`text-gray-500`}>Item Total</MyText>
<MyText style={tw`text-gray-900 font-medium`}>₹{Math.trunc(totalPrice)}</MyText>
<MyText testID="bill-item-total-amount" style={tw`text-gray-900 font-medium`}>₹{Math.trunc(totalPrice)}</MyText>
</View>
{/* Total Savings */}
{totalSavings > 1 && (
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`text-gray-500`}>Total Savings</MyText>
<MyText style={tw`text-green-600 font-medium`}>₹{Math.trunc(totalSavings)}</MyText>
<MyText testID="bill-total-savings-amount" style={tw`text-green-600 font-medium`}>₹{Math.trunc(totalSavings)}</MyText>
</View>
)}
@ -251,7 +254,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
{discountAmount > 0 && (
<View style={tw`flex-row justify-between items-center mb-2`}>
<MyText style={tw`text-gray-500`}>Product Discount</MyText>
<MyText style={tw`text-green-600 font-medium`}>-₹{Math.trunc(discountAmount)}</MyText>
<MyText testID="bill-product-discount-amount" style={tw`text-green-600 font-medium`}>-₹{Math.trunc(discountAmount)}</MyText>
</View>
)}
@ -265,17 +268,17 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
{deliveryCharge === 0 && (
isFlashDelivery
? (constsData?.flashDeliveryCharge > 0 && (
<MyText style={tw`text-gray-400 line-through mr-2 text-xs`}>
<MyText testID="bill-delivery-strike" style={tw`text-gray-400 line-through mr-2 text-xs`}>
₹{constsData?.flashDeliveryCharge}
</MyText>
))
: (constsData?.deliveryCharge > 0 && (
<MyText style={tw`text-gray-400 line-through mr-2 text-xs`}>
<MyText testID="bill-delivery-strike" style={tw`text-gray-400 line-through mr-2 text-xs`}>
₹{constsData?.deliveryCharge}
</MyText>
))
)}
<MyText style={tw`${deliveryCharge === 0 ? 'text-green-600' : 'text-gray-900'} font-medium`}>
<MyText testID="bill-delivery-amount" style={tw`${deliveryCharge === 0 ? 'text-green-600' : 'text-gray-900'} font-medium`}>
{deliveryCharge === 0 ? 'Free' : `₹${deliveryCharge}`}
</MyText>
</View>
@ -287,7 +290,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
? constsData?.flashFreeDeliveryThreshold
: constsData?.freeDeliveryThreshold;
return threshold > 0 && finalTotal < threshold && (
<View style={tw`bg-blue-50 p-2.5 rounded-lg mb-2 flex-row items-center`}>
<View testID="bill-nudge" style={tw`bg-blue-50 p-2.5 rounded-lg mb-2 flex-row items-center`}>
<MaterialIcons name="shopping-bag" size={16} color="#2563EB" style={tw`mr-2`} />
<MyText style={tw`text-blue-700 text-xs font-medium flex-1`}>
Add products worth ₹{(threshold - finalTotal).toFixed(0)} for free delivery
@ -302,14 +305,14 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
{/* Grand Total */}
<View style={tw`flex-row justify-between items-center`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>To Pay</MyText>
<MyText style={tw`text-xl font-bold text-gray-900`}>₹{finalTotalWithDelivery}</MyText>
<MyText testID="bill-to-pay-amount" style={tw`text-xl font-bold text-gray-900`}>₹{finalTotalWithDelivery}</MyText>
</View>
{/* Savings Banner */}
{(discountAmount > 0 || deliveryCharge === 0 || totalSavings > 1) && (
<View style={tw`bg-green-50 rounded-lg p-2 mt-4 flex-row justify-center items-center`}>
<View testID="bill-savings-banner" style={tw`bg-green-50 rounded-lg p-2 mt-4 flex-row justify-center items-center`}>
<MaterialIcons name="stars" size={16} color="#059669" style={tw`mr-1.5`} />
<MyText style={tw`text-green-700 text-xs font-bold`}>
<MyText testID="bill-savings-text" style={tw`text-green-700 text-xs font-bold`}>
You saved ₹{Math.trunc(discountAmount + totalSavings + (deliveryCharge === 0 ? (
isFlashDelivery
? constsData?.flashDeliveryCharge

View file

@ -219,7 +219,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
if (activeRegionId == null || isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<View testID="product-detail-loading" style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MyText style={tw`text-gray-500 font-medium`}>Loading product details...</MyText>
</View>
);
@ -227,7 +227,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
if (error || !productDetail) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<View testID="product-detail-error" style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MaterialIcons name="error-outline" size={48} color="#EF4444" />
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
<MyText style={tw`text-gray-500 mt-2`}>Product not found or error loading</MyText>
@ -267,13 +267,13 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
<MyText style={tw`text-2xl font-bold text-gray-900 flex-1 mr-2`}>{productDetail.name}</MyText>
<View style={tw`flex-row gap-2`}>
{productAvailability?.isFlashAvailable && (
<View style={tw`bg-pink-100 px-3 py-1 rounded-full flex-row items-center`}>
<View testID="product-flash-badge" style={tw`bg-pink-100 px-3 py-1 rounded-full flex-row items-center`}>
<MaterialIcons name="bolt" size={12} color="#EC4899" style={tw`mr-1`} />
<MyText style={tw`text-pink-700 text-xs font-bold`}>1 Hr Delivery</MyText>
</View>
)}
{productAvailability?.isOutOfStock && (
<View style={tw`bg-red-100 px-3 py-1 rounded-full`}>
<View testID="product-out-of-stock-badge" style={tw`bg-red-100 px-3 py-1 rounded-full`}>
<MyText style={tw`text-red-700 text-xs font-bold`}>Out of Stock</MyText>
</View>
)}
@ -294,7 +294,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
{/* Show market price discount if available */}
{productDetail.marketPrice && (
<View style={tw`ml-3 mb-1 flex-row items-center`}>
<View testID="product-discount" style={tw`ml-3 mb-1 flex-row items-center`}>
<MyText style={tw`text-gray-400 text-base line-through mr-2`}>₹{productDetail.marketPrice}</MyText>
<View style={tw`bg-green-100 px-2 py-0.5 rounded`}>
<MyText style={tw`text-green-700 text-xs font-bold`}>{discountPercentage}% OFF</MyText>
@ -305,7 +305,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
{/* Flash price on separate line - smaller and less prominent */}
{productAvailability?.isFlashAvailable && productDetail.flashPrice && productDetail.flashPrice !== productDetail.price && (
<View style={tw`mt-1`}>
<View testID="product-flash-price" style={tw`mt-1`}>
<MyText style={tw`text-pink-600 text-lg font-bold`}>
1 Hr Delivery: ₹{productDetail.flashPrice}{productDetail.productType !== 'combo' ? ` / ${productDetail.unitNotation}` : ''}
</MyText>
@ -330,6 +330,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
) : (
// Show "Add to Cart" button when not in cart
<MyTouchableOpacity
testID="product-add-to-cart"
style={[tw`flex-1 py-3.5 rounded-xl items-center border`, {
borderColor: (productAvailability?.isOutOfStock || (isFlashDelivery && !productAvailability?.isFlashAvailable)) ? '#9ca3af' : theme.colors.brand500,
backgroundColor: 'white'
@ -356,6 +357,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
{isFlashDelivery ? (
<MyTouchableOpacity
testID="product-buy-now"
style={[tw`flex-1 py-3.5 rounded-xl items-center shadow-md`, {
backgroundColor: (productAvailability?.isOutOfStock || !productAvailability?.isFlashAvailable) ? '#9ca3af' : '#FDF2F8'
}]}
@ -369,6 +371,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
</MyTouchableOpacity>
) : productAvailability?.isFlashAvailable ? (
<MyTouchableOpacity
testID="product-buy-now"
style={[tw`flex-1 py-3.5 rounded-xl items-center shadow-md`, {
backgroundColor: sortedDeliverySlots.length === 0 ? '#9ca3af' : '#FDF2F8'
}]}
@ -388,7 +391,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
{/* Combo Items */}
{productDetail.productType === 'combo' && productDetail.comboItems && productDetail.comboItems.length > 0 && (
<View style={tw`px-4 mb-4`}>
<View testID="product-combo-items" style={tw`px-4 mb-4`}>
<View style={tw`bg-white p-5 rounded-2xl shadow-sm border border-gray-100`}>
<View style={tw`flex-row items-center mb-4`}>
<View style={tw`w-8 h-8 bg-brand50 rounded-full items-center justify-center mr-3`}>
@ -400,6 +403,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
{productDetail.comboItems.map((comboItem, index) => (
<View
key={comboItem.skuId}
testID={`combo-item-${comboItem.skuId}`}
style={tw`flex-row items-center py-2 ${index !== productDetail.comboItems.length - 1 ? 'border-b border-gray-50' : ''}`}
>
<View style={tw`w-12 h-12 bg-gray-100 rounded-lg overflow-hidden items-center justify-center mr-3`}>
@ -451,6 +455,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
{sortedDeliverySlots.slice(0, 2).map((slot, index) => (
<MyTouchableOpacity
key={index}
testID={`product-slot-${slot.id}`}
style={tw`flex-row items-start mb-4 bg-gray-50 p-3 rounded-xl border border-gray-100`}
onPress={() => handleSlotAddToCart(productDetail.id, slot.id)}
disabled={productAvailability?.isOutOfStock}
@ -470,6 +475,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
))}
{sortedDeliverySlots.length > 2 && (
<MyTouchableOpacity
testID="product-view-all-slots"
onPress={() => setShowAllSlots(true)}
style={tw`items-center py-2`}
>
@ -663,6 +669,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
{sortedDeliverySlots.map((slot, index) => (
<MyTouchableOpacity
key={index}
testID={`product-all-slot-${slot.id}`}
style={tw`flex-row items-start mb-4 bg-gray-50 p-4 rounded-xl border border-gray-100`}
onPress={() => handleSlotAddToCart(productDetail.id, slot.id)}
disabled={productAvailability?.isOutOfStock}
@ -683,6 +690,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
</ScrollView>
<MyTouchableOpacity
testID="product-slots-dialog-close"
style={tw`mt-4 bg-gray-900 py-3.5 rounded-xl items-center`}
onPress={() => setShowAllSlots(false)}
>

View file

@ -155,6 +155,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
<>
<View style={tw`flex-row items-center px-4 pt-2`}>
<MyTouchableOpacity
testID="quick-delivery-flash-back"
onPress={() => router.back()}
style={tw`p-2 -ml-2`}
activeOpacity={0.7}
@ -175,6 +176,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
<>
<View style={tw`flex-1 flex-row items-center gap-2`}>
<MyTouchableOpacity
testID="quick-delivery-regular-back"
onPress={() => router.back()}
style={tw`p-1`}
activeOpacity={0.7}
@ -184,6 +186,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
<View style={tw`flex-1 gap-1`}>
<MyTouchableOpacity
testID="quick-delivery-slot-button"
onPress={() => setDialogOpen(true)}
style={tw`flex-row items-center bg-brand50 border border-brand100 rounded-lg px-3 py-2`}
activeOpacity={0.7}
@ -215,6 +218,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
{foreignAddress && (
<MyTouchableOpacity
testID="quick-delivery-foreign-warning"
onPress={handleForeignAddressSwitch}
activeOpacity={0.8}
style={tw`mt-1 p-2.5 bg-amber-50 border border-amber-200 rounded-lg flex-row items-center`}
@ -254,6 +258,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
slotOptions.map(slot => (
<MyTouchableOpacity
key={slot.id}
testID={`quick-delivery-slot-${slot.id}`}
style={tw`p-3 border border-gray-200 rounded-lg mb-2 ${
slot.id === (slotId || earliestSlot?.id) ? 'bg-brand50 border-brand500' : 'bg-white'
}`}

View file

@ -270,6 +270,7 @@ const CompactProductCard = ({
return (
<MyTouchableOpacity
testID="compact-product-card"
style={[
tw`bg-white rounded-lg shadow-sm mb-2 overflow-hidden border border-gray-100`,
{ width: itemWidth },
@ -298,6 +299,7 @@ const CompactProductCard = ({
/>
) : (
<MyTouchableOpacity
testID="compact-card-add"
style={tw`w-8 h-8 rounded-full bg-white items-center justify-center shadow-md`}
onPress={() => handleQuantityChange(1)}
activeOpacity={0.8}
@ -525,6 +527,7 @@ export function FlashDeliveryProducts({ storeId:storeIdParent, baseUrl, onProduc
ListHeaderComponent={
<View style={tw`px-4 pt-2`}>
<SearchBar
testID="flash-product-search"
value={searchQuery}
onChangeText={setSearchQuery}
placeholder="Search products in this store..."

View file

@ -10,7 +10,7 @@ interface TabLayoutWrapperProps {
export default function TabLayoutWrapper({ children, style }: TabLayoutWrapperProps) {
return (
<SafeAreaView edges={['top']} style={[tw`flex-1 bg-white`, style]}>
<SafeAreaView testID="tab-layout-wrapper" edges={['top']} style={[tw`flex-1 bg-white`, style]}>
{children}
</SafeAreaView>
);

View file

@ -16,7 +16,7 @@ export const TermsAndConditionsContent: React.FC<TermsAndConditionsContentProps>
const subheadingStyle = compact ? tw`text-xs font-semibold text-gray-800` : tw`text-sm font-semibold text-gray-800`;
return (
<View>
<View testID="terms-content">
{showTitle && (
<>
<MyText style={headingStyle}>FRESHYO – Legal Policies</MyText>

View file

@ -5,7 +5,7 @@ import { MyText, tw } from "common-ui";
const TestingPhaseNote: React.FC = () => {
return (
<View style={tw`mx-4 my-2 p-4 bg-amber-50 rounded-xl border border-amber-200`}>
<View testID="testing-phase-note" style={tw`mx-4 my-2 p-4 bg-amber-50 rounded-xl border border-amber-200`}>
<View style={tw`flex-row items-center mb-2`}>
<MaterialIcons name="info" size={20} color="#D97706" />
<MyText style={tw`ml-2 text-amber-800 font-bold text-base`}>

View file

@ -29,6 +29,7 @@ export default function WebViewWrapper({ children }: ReactParentComponent) {
{isWebviewClosable && (
<View style={{ position: 'absolute', top: 40, right: 20 }}>
<MyTouchableOpacity
testID="webview-close"
onPress={() => setIsClosed(true)}
style={{
backgroundColor: 'rgba(0,0,0,0.5)',

View file

@ -235,13 +235,13 @@ function DeliverySlotSummary({
</View>
<BottomDialog open={!!openGroup} onClose={() => setOpenGroup(null)}>
<View style={tw`p-6`}>
<View testID="delivery-slot-group-dialog" style={tw`p-6`}>
<View style={tw`flex-row items-start justify-between mb-4`}>
<View style={tw`flex-1 mr-3`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>Items</MyText>
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>{openGroup?.label}</MyText>
</View>
<MyTouchableOpacity onPress={() => setOpenGroup(null)} style={tw`p-1`}>
<MyTouchableOpacity testID="delivery-slot-group-close" onPress={() => setOpenGroup(null)} style={tw`p-1`}>
<MaterialIcons name="close" size={22} color="#9CA3AF" />
</MyTouchableOpacity>
</View>
@ -899,6 +899,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
<View style={tw`bg-white px-4 py-3 border-b border-gray-100 mt-6`}>
<View style={tw`flex-row items-center`}>
<MyTouchableOpacity
testID="cart-header-back"
onPress={() => router.back()}
style={tw`p-2 -ml-2 mr-1`}
activeOpacity={0.7}
@ -941,6 +942,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
Looks like you haven&apos;t added anything to your cart yet.
</MyText>
<MyTouchableOpacity
testID="cart-start-shopping"
style={tw`mt-6 bg-brand500 px-6 py-3 rounded-xl`}
onPress={() => router.push("/(drawer)/(tabs)/home")}
>
@ -984,6 +986,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
<View style={tw`p-4`}>
<View style={tw`flex-row items-center mb-2`}>
<MyTouchableOpacity
testID={`cart-item-image-${item.id}`}
onPress={() =>
router.push(
isFlashDelivery
@ -1000,6 +1003,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
</MyTouchableOpacity>
<MyTouchableOpacity
testID={`cart-item-name-${item.id}`}
onPress={() =>
router.push(
isFlashDelivery
@ -1087,6 +1091,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
<View style={tw`flex flex-row items-center justify-between mt-2`}>
<View style={tw`flex-1 mr-4`}>
<BottomDropdown
testID={`slot-dropdown-${item.id}`}
label="Select Delivery Slot"
options={productSlots}
value={selectedSlotForItem || ""}
@ -1120,6 +1125,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
: "Choose delivery slot")}
</MyText>
<MyTouchableOpacity
testID={`cart-item-slot-${item.id}`}
onPress={onPress}
disabled={disabled}
activeOpacity={0.7}
@ -1139,6 +1145,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
₹{itemPrice}
</MyText>
<TouchableOpacity
testID={`cart-item-delete-${item.id}`}
onPress={() => {
Alert.alert(
"Remove Item",
@ -1190,6 +1197,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
₹{itemPrice}
</MyText>
<TouchableOpacity
testID={`cart-item-delete-${item.id}`}
onPress={() => {
Alert.alert(
"Remove Item",
@ -1393,6 +1401,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
{selectedCouponIds.length > 0 && (
<MyTouchableOpacity
testID="remove-coupons"
style={tw`mt-3 self-end`}
onPress={() => setSelectedCouponIds([])}
>
@ -1416,6 +1425,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
{/* Link to add coupons to account */}
<MyTouchableOpacity
testID="add-coupons-to-account"
style={tw`mt-2 ml-1`}
onPress={() => router.push("/(drawer)/(tabs)/me/coupons?from=cart")}
>
@ -1430,6 +1440,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<MyText style={tw`text-base font-bold text-gray-900 mb-3`}>Delivery Instructions</MyText>
<MyTextInput
testID="delivery-instructions"
value={userNotes}
onChangeText={setUserNotes}
placeholder="Any special instructions for the delivery partner..."
@ -1476,6 +1487,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
>
<View style={tw`flex-row items-center flex-1 mr-2`}>
<MyTouchableOpacity
testID={`coupon-bill-${coupon.id}`}
style={tw`flex-row items-center`}
onPress={() => setCouponDialogOpen(true)}
activeOpacity={0.7}
@ -1557,6 +1569,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
<View style={tw`p-4 border-t border-gray-100 bg-gray-50`}>
<View style={tw`flex-row gap-3`}>
<MyTouchableOpacity
testID="shop-more-button"
style={tw`flex-1 bg-white border border-gray-200 py-3.5 rounded-xl items-center shadow-sm`}
onPress={() => router.push(isFlashDelivery ? "/(drawer)/(tabs)/flash-delivery" : "/(drawer)/(tabs)/home")}
>
@ -1682,7 +1695,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
open={couponDialogOpen}
onClose={() => setCouponDialogOpen(false)}
>
<View style={tw`p-6`}>
<View testID="coupon-details-dialog" style={tw`p-6`}>
<View style={tw`flex-row items-center mb-6`}>
<View
style={tw`w-10 h-10 bg-pink-50 rounded-full items-center justify-center mr-3`}
@ -1725,6 +1738,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
))}
<MyTouchableOpacity
testID="coupon-details-close"
style={tw`mt-4 bg-gray-900 py-3.5 rounded-xl items-center`}
onPress={() => setCouponDialogOpen(false)}
>

View file

@ -294,12 +294,12 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
// violation: the coupon query and the four memos above sat below this guard).
if (selectedItems.length === 0) {
return (
<View style={tw`flex-1 bg-gray-50 items-center justify-center p-6`}>
<View testID="checkout-empty" style={tw`flex-1 bg-gray-50 items-center justify-center p-6`}>
<MaterialIcons name="shopping-cart" size={64} color="#9CA3AF" />
<MyText style={tw`text-xl font-semibold text-gray-900 mt-4 text-center`}>
<MyText testID="checkout-empty-title" style={tw`text-xl font-semibold text-gray-900 mt-4 text-center`}>
{cartItems.length === 0 ? "Your cart is empty" : "No items to checkout"}
</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 mb-6`}>
<MyText testID="checkout-empty-copy" style={tw`text-gray-500 text-center mt-2 mb-6`}>
{cartItems.length === 0
? "Add some delicious items to your cart before checking out"
: isFlashDelivery
@ -308,6 +308,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
}
</MyText>
<MyTouchableOpacity
testID="checkout-empty-back"
style={tw`bg-brand500 py-3 px-6 rounded-lg`}
onPress={() => router.back()}
>
@ -324,9 +325,10 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
<View style={tw`flex-1 bg-gray-50`}>
{/* Checkout Type Header */}
<View style={tw`bg-white px-4 py-3 mb-4 border-b border-gray-100 mt-6`}>
<View testID="checkout-header" style={tw`bg-white px-4 py-3 mb-4 border-b border-gray-100 mt-6`}>
<View style={tw`flex-row items-center`}>
<MyTouchableOpacity
testID="checkout-header-back"
onPress={() => router.back()}
style={tw`p-2 -ml-2 mr-1`}
activeOpacity={0.7}
@ -338,7 +340,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
size={24}
color={isFlashDelivery ? "#f81260" : "#374151"}
/>
<MyText style={[
<MyText testID="checkout-header-title" style={[
tw`text-lg font-bold ml-2`,
{ color: isFlashDelivery ? '#f81260' : '#374151' }
]}>
@ -353,12 +355,13 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
showsVerticalScrollIndicator={false}
>
{/* Items (grouped by delivery slot) */}
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<View testID="checkout-items-section" style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<MyText style={tw`text-base font-bold text-gray-900 mb-3`}>Items</MyText>
{groupedItems.map((group) => (
<View key={group.slotId ?? 'flash'}>
<View key={group.slotId ?? 'flash'} testID={`checkout-slot-group-${group.slotId ?? 'flash'}`}>
{group.label && (
<View
testID={`checkout-slot-label-${group.slotId ?? 'flash'}`}
style={tw`flex-row items-center self-start mt-3 mb-1 rounded-full bg-gray-100 px-2.5 py-1`}
>
<MaterialIcons name="schedule" size={13} color="#1570EF" style={tw`mr-1`} />
@ -375,6 +378,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
return (
<View
key={item.id}
testID={`checkout-item-${item.id}`}
style={tw`flex-row items-center justify-between py-2 border-b border-gray-50`}
>
<View style={tw`flex-1 mr-3`}>
@ -400,10 +404,10 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
{/* Coupon */}
{(selectedCoupons.length > 0 || droppedCoupons.length > 0) && (
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<View testID="checkout-coupon-section" style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<MyText style={tw`text-base font-bold text-gray-900 mb-3`}>Coupon</MyText>
{selectedCoupons.map((coupon) => (
<View key={coupon.id} style={tw`flex-row items-center justify-between py-2`}>
<View key={coupon.id} testID={`checkout-coupon-${coupon.id}`} style={tw`flex-row items-center justify-between py-2`}>
<View style={tw`flex-row items-center flex-1 mr-2`}>
<MyText style={tw`text-sm font-medium text-gray-900`}>{coupon.code}</MyText>
{/* Product-specific coupon: the per-product split behind it. */}
@ -418,7 +422,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
</MyTouchableOpacity>
)}
</View>
<MyText style={tw`text-sm font-bold text-green-600`}>
<MyText testID={`checkout-coupon-value-${coupon.id}`} style={tw`text-sm font-bold text-green-600`}>
{coupon.discountType === 'percentage'
? `${coupon.discountValue}% off`
: `₹${coupon.discountValue} off`}
@ -428,7 +432,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
{/* Picked in the cart but no longer applicable to this order — shown with
the reason instead of vanishing (the cart has the full picker). */}
{droppedCoupons.map((coupon) => (
<View key={coupon.id} style={tw`py-2`}>
<View key={coupon.id} testID={`checkout-coupon-dropped-${coupon.id}`} style={tw`py-2`}>
<View style={tw`flex-row items-center justify-between`}>
<MyText style={tw`text-sm font-medium text-gray-400 line-through`}>
{coupon.code}
@ -436,7 +440,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
<MyText style={tw`text-sm text-gray-400`}>Not applied</MyText>
</View>
{!!coupon.ineligibilityReason && (
<MyText style={tw`text-xs text-gray-400 mt-0.5`}>
<MyText testID={`checkout-coupon-reason-${coupon.id}`} style={tw`text-xs text-gray-400 mt-0.5`}>
{coupon.ineligibilityReason}
</MyText>
)}

View file

@ -327,6 +327,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
{item.slotId && slotsData && productSlotsMap[item.skuId] && (
<BottomDropdown
label="Select Delivery Slot"
testID="cart-slot-dropdown"
value={item.slotId}
options={(productSlotsMap[item.skuId]?.slots || []).map((slot) => {
return {
@ -351,6 +352,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
}}
triggerComponent={({ onPress, displayText }) => (
<MyTouchableOpacity
testID="cart-slot-trigger"
onPress={onPress}
style={tw`flex-row items-center bg-blue-50 px-2 py-1 rounded-lg border border-blue-100`}
>

View file

@ -244,6 +244,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
render={({ field: { onChange, onBlur, value } }) => (
<View style={tw`mb-5`}>
<MyTextInput
testID="registration-name-input"
topLabel="Full Name"
placeholder="Enter your full name"
value={value}
@ -270,6 +271,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
render={({ field: { onChange, onBlur, value } }) => (
<View style={tw`mb-5`}>
<MyTextInput
testID="registration-email-input"
topLabel="Email Address"
placeholder="Enter your email address"
value={value}
@ -298,6 +300,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
render={({ field: { onChange, onBlur, value } }) => (
<View style={tw`mb-5`}>
<MyTextInput
testID="registration-mobile-input"
topLabel="Mobile Number"
placeholder="Enter your mobile number"
value={value}
@ -333,6 +336,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
<View style={tw`mb-5`}>
<MyTextInput
topLabel="Password"
testID="registration-password-input"
placeholder="Create a password"
value={value}
onChangeText={onChange}
@ -358,6 +362,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
<View style={tw`mb-5`}>
<MyTextInput
topLabel="Confirm Password"
testID="registration-confirm-password-input"
placeholder="Confirm your password"
value={value}
onChangeText={onChange}
@ -383,6 +388,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
<View style={tw`mb-6`}>
<MyTouchableOpacity
style={tw`flex-row items-center`}
testID="registration-terms-toggle"
onPress={() => onChange(!value)}
>
<View
@ -419,6 +425,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
)}
<MyButton
testID="registration-submit-button"
onPress={handleSubmit(handleFormSubmit)}
fillColor="brand500"
textColor="white1"
@ -436,6 +443,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
{isEdit && (
<View style={tw`mt-4`}>
<MyButton
testID="registration-update-password-button"
textContent="Update Password"
onPress={() => setIsPasswordDialogOpen(true)}
fillColor="brand500"
@ -453,6 +461,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
Update Password
</MyText>
<TextInput
testID="password-dialog-password-input"
style={{
borderWidth: 1,
borderColor: '#ccc',
@ -467,6 +476,7 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
onChangeText={setPassword}
/>
<TextInput
testID="password-dialog-confirm-password-input"
style={{
borderWidth: 1,
borderColor: '#ccc',
@ -482,12 +492,14 @@ function RegistrationForm({ onSubmit, isLoading = false, initialValues, isEdit =
/>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<MyButton
testID="password-dialog-cancel-button"
textContent="Cancel"
onPress={() => setIsPasswordDialogOpen(false)}
fillColor="gray1"
textColor="white1"
/>
<MyButton
testID="password-dialog-update-button"
textContent="Update"
onPress={handleUpdatePassword}
fillColor="brand500"

View file

@ -232,6 +232,7 @@ export default function AddToCartDialog() {
{showFlashOption && (
<MyTouchableOpacity
key="flash-delivery"
testID="flash-delivery-option"
style={tw`flex-row items-center mb-4 bg-pink-50 p-4 rounded-xl border ${selectedFlashDelivery ? 'border-pink-500' : 'border-pink-200'
}`}
onPress={() => {

View file

@ -323,6 +323,7 @@ const AddressForm: React.FC<AddressFormProps> = ({
{touched.addressLine1 && errors.addressLine1 && <MyText style={tw`text-red-500 mb-2`}>{errors.addressLine1}</MyText>}
<MyTextInput
testID="address-line2"
placeholder="Address Line 2 (Optional)"
shrunkPadding={true}
onChangeText={handleChange('addressLine2')}
@ -385,6 +386,7 @@ const AddressForm: React.FC<AddressFormProps> = ({
</View>
<MyTextInput
testID="address-state"
placeholder="State"
shrunkPadding={true}
onChangeText={handleChange('state')}
@ -441,6 +443,7 @@ const AddressForm: React.FC<AddressFormProps> = ({
<View style={tw`flex-row items-center mb-4 mt-2`}>
<Checkbox
testID="address-default-checkbox"
checked={values.isDefault}
onPress={() => setFieldValue('isDefault', !values.isDefault)}
/>

View file

@ -114,6 +114,7 @@ const CouponBreakdownDialog: React.FC<CouponBreakdownDialogProps> = ({
</MyText>
<MyTouchableOpacity
testID="coupon-breakdown-close"
style={tw`mt-4 bg-gray-900 py-3.5 rounded-xl items-center`}
onPress={onClose}
>

View file

@ -117,6 +117,7 @@ export const LocationAttacher: React.FC<LocationAttacherProps> = ({
</View>
) : (
<MyTouchableOpacity
testID="attach-current-location"
onPress={() => attachCurrentLocation()}
disabled={locationLoading || disabled}
style={tw`mb-4`}
@ -131,6 +132,7 @@ export const LocationAttacher: React.FC<LocationAttacherProps> = ({
{showGoogleMapsOption && onGoogleMapsUrlChange === undefined && (
<>
<MyTouchableOpacity
testID="attach-google-maps"
onPress={() => setShowGoogleMapsField(true)}
disabled={disabled}
style={tw`mb-1`}

View file

@ -211,6 +211,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
return (
<View style={tw`flex-1 bg-white`}>
<MyTouchableOpacity
testID="location-add-back"
onPress={() => setMode('choose')}
style={tw`px-5 pt-12 pb-2 flex-row items-center`}
>
@ -288,7 +289,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
style={tw`border rounded-2xl p-4 mb-3 shadow-sm ${isActive ? 'bg-brand50 border-brand500' : 'bg-white border-gray-100'
}`}
>
<MyTouchableOpacity disabled={busy} onPress={() => handleSelect(address)}>
<MyTouchableOpacity testID={`location-address-${address.id}`} disabled={busy} onPress={() => handleSelect(address)}>
<View style={tw`flex-row items-center mb-1`}>
<MyText style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText>
{address.isDefault && (
@ -297,7 +298,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
</View>
)}
{isActive && (
<View style={tw`ml-auto bg-brand500 w-5 h-5 rounded-full items-center justify-center`}>
<View testID="location-address-active" style={tw`ml-auto bg-brand500 w-5 h-5 rounded-full items-center justify-center`}>
<MaterialIcons name="check" size={14} color="white" />
</View>
)}
@ -326,6 +327,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
)}
<MyTouchableOpacity
testID="location-add-address"
onPress={() => setMode('add')}
style={tw`bg-white border border-dashed border-gray-300 rounded-2xl p-4 flex-row items-center`}
>
@ -354,7 +356,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
)}
{busy && (
<View style={tw`absolute inset-0 bg-black/20 items-center justify-center`}>
<View testID="location-busy-overlay" style={tw`absolute inset-0 bg-black/20 items-center justify-center`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
</View>
)}

View file

@ -1,622 +0,0 @@
# 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**: **66 suites / 347 tests** (counted from the files after the region-test sync; not re-run in that pass)
- Per-group counts below are counted from the files (`it`/`test` lines); jest expands
`it.each` cases, so a run reports a few more than the sum of these tables.
- 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, '<proc>')`, `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/<id>` |
| 15 | opens the product detail page from the main list | push `…/product-detail/<id>` |
| 16 | opens the slot detail page when a slot card is tapped | push `…/slot-view?slotId=<id>` |
| 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/`) — 133
### `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/<id>` |
| 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/<id>` |
| 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/<id>` |
### `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/<id>` |
| 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` — 11
Signed in by default (login wall when signed out; first-address gate when there are no addresses).
| # | 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 | shows an enabled merge row when every item can use the majority slot | `delivery-slot-merge` → apply → hidden |
| 6 | hides the merge row when one item cannot use the majority slot | no merge row |
| 7 | hides the merge row when only one slot is selected | no merge row |
| 8 | renders the flash cart variant without slot selection | "1 Hr Delivery Cart" |
| 9 | shows the login wall when signed out | "Please log in" + "Log In"; no cart line |
| 10 | shows the add-address gate before the cart when the user has no addresses | "Where should we deliver?" + `cart-address-other`; cart line hidden |
| 11 | shows the add-address gate even when the cart is empty | gate, not "Your cart is empty" |
### `cart-coupons.test.tsx` — 12 (coupon application + discount calculation)
Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryCharge 15.
| # | Test | Asserts |
| --- | --- | --- |
| 1 | shows the item total and free delivery before a coupon is applied | no `Product Discount` row, "Free" |
| 2 | offers the coupon with its computed saving | option label carries `Save ₹43` (10% of 430) |
| 3 | applies a percentage discount and shows the applied code | `Product Discount -₹43`, `Coupon Applied SAVE10`, To Pay ₹387 |
| 4 | caps a percentage discount at maxValue | 50% of 430 = 215 capped to `-₹50`, ₹380 |
| 5 | applies a flat discount | `-₹100`, ₹330 |
| 6 | caps a flat discount at the item total | flat 1000 on a 430 cart → `-₹430` (never negative) |
| 7 | re-adds the delivery fee when the discount drops the total below the threshold | 430 − 200 = 230 < 249 → ₹245, no "Free" |
| 8 | removes the coupon and the discount again | `Remove coupon` → both rows gone |
| 9 | lists a min-order coupon as ineligible and does not apply it | label carries `Min order ₹1000`; pressing it applies nothing |
| 10 | hides a coupon that has hit its per-user usage limit | "No coupons available" + empty copy |
| 11 | drops the discount when a quantity change takes the cart below the minOrder | select a minOrder-300 coupon at ₹430, decrement to ₹215 → discount gone (`cart-item-1-decrement` / `-value`) |
| 12 | sends the selected coupon id to checkout | push URL contains `&coupons=77` |
### `checkout-crash.test.tsx` — 4 (checkout guards + the resolved bill)
The last case is the regression guard for the Rules-of-Hooks crash that used to make the screen
unrenderable: it asserted the thrown error until the hooks were moved above the guard, and now
asserts the bill instead.
| # | Test | Asserts |
| --- | --- | --- |
| 1 | asks for delivery slots when the cart lines have none | "No items to checkout" + "Please select delivery slots for your items" |
| 2 | reports flash-unavailable lines on the flash checkout | "None of your cart items are available for flash delivery" |
| 3 | shows the empty-cart state when there is nothing to pay for | "Your cart is empty" |
| 4 | renders the bill once the cart resolves to slotted items | header + Item Total ₹215 + To Pay ₹230, no discount (used to throw) |
### `checkout-coupons.test.tsx` — 10 (coupon application + discount calculation)
Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryCharge 15.
| # | Test | Asserts |
| --- | --- | --- |
| 1 | applies a percentage discount to the item total | `-₹43`, To Pay ₹387, "Free", "You saved ₹68 on this order" |
| 2 | caps a percentage discount at maxValue | 50% of 430 = 215 capped to `-₹50`, ₹380 |
| 3 | applies a flat discount | `-₹100`, ₹330 |
| 4 | caps a flat discount at maxValue | `-₹150`, ₹280 |
| 5 | never discounts below zero — capped at the item total | flat 1000 on a 430 cart → `-₹430` |
| 6 | charges delivery again when the discount drops the total below the threshold | 430 − 200 = 230 < 249 → ₹245 + "Add products worth ₹19 for free delivery" |
| 7 | does not apply a coupon whose minOrder is not met, even from the URL | no `Product Discount` row, "Free" |
| 8 | ignores a coupon that has hit its per-user usage limit | no `Product Discount` row |
| 9 | shows no discount when the URL carries no coupon | no `Product Discount`, "Free" |
| 10 | sends the selected coupon id with the order | `placeOrder` payload `couponId: 77`; `replace('…totalAmount=387')` |
### `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` — 4
| # | 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 |
### `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/`) — 70
### `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` — 6
| # | 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 |
| 5 | renders the product discount and the savings banner when a coupon is applied | `Product Discount -₹43`, ₹387, "You saved ₹58 on this order" |
| 6 | sends the selected coupon id with the order | `placeOrder` payload `couponId: 77` |
### `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` — 6
Coordinates are mandatory, so most cases seed the device location (`useLocationStore`) before rendering.
| # | Test | Asserts |
| --- | --- | --- |
| 1 | renders the add-address form without a service-area notice | title + name field; no "We currently serve" |
| 2 | keeps Add Address disabled until a location is attached | disabled CTA + "Attach a location to add address" after the first field is touched |
| 3 | shows the device-source heading once a location is attached | "Current Location Attached" + "Choose Another Location in Map" |
| 4 | validates the required fields | name/phone/line1 errors |
| 5 | creates an address with the region and coordinates derived from the location | `createAddress` payload carries `regionId`, `latitude`/`longitude` and the City name |
| 6 | updates an address in edit mode via user.address.updateAddress | `{id, regionId}` |
### `address-selectors.test.tsx` — 6
| # | Test | Asserts |
| --- | --- | --- |
| 1 | lists the addresses and auto-selects the default | both cards + `onAddressSelect(2)` |
| 2 | selects an address on press | `onAddressSelect(1)` |
| 3 | refreshes the addresses after attaching the current location | `updateAddress` gets the mocked coords, then `getUserAddresses` is fetched a **second** time (fails with the old dotted-string invalidation) |
| 4 | shows the empty state | empty copy + Add Address |
| 5 | shows the earliest slot and changes it from the dialog | slot options → `onSlotChange` |
| 6 | 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` — 3
| # | Test | Asserts |
| --- | --- | --- |
| 1 | renders its children once a region is selected | passthrough |
| 2 | shows a spinner while the region is still resolving | "Finding your region..." |
| 3 | asks for an address with a location notice when the location is denied | chooser + "Location access is not granted..." + `open-location-settings` |
### `cart-address-gate.test.tsx` — 3
| # | Test | Asserts |
| --- | --- | --- |
| 1 | offers the current-location and map options | both option cards; current enabled with a device fix |
| 2 | disables the current-location option without a device fix | disabled card + "Turn on location to use this option" |
| 3 | opens the address form from the map option | `address-name` visible |
### `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 — 90 (hooks 40, stores 23, contexts 14, lib 13)
### `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 |
### `stores/region-store.test.ts` — 4
| # | Test | Asserts |
| --- | --- | --- |
| 1 | stores the selected region and bound and bumps the generation | id/region/bound + generation 1 |
| 2 | does not bump the generation for an identical selection | generation stays 1 |
| 3 | clears the region and bumps the generation | nulls + generation 2 |
| 4 | is memory-only (no persist middleware) | `persist` undefined |
### `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/pending-address.test.ts` — 4
| # | Test | Asserts |
| --- | --- | --- |
| 1 | round-trips a signed-out draft | save → get equals the draft |
| 2 | returns null when there is no draft | null |
| 3 | clears the draft | null after clear |
| 4 | returns null for corrupt stored JSON | null |
### `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 |
### `lib/query-invalidation-keys.test.tsx` — 1
| # | Test | Asserts |
| --- | --- | --- |
| 1 | matches the array path form and ignores the dotted string form | the stored key is `[['user','address','getUserAddresses'], {type}]`; `findAll({queryKey:['user.address.getUserAddresses']})` matches 0, the array form matches 1 (pins the stale-data bug in `CheckoutAddressSelector`) |
### `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`.
**Coupon discount on the checkout page.** FIXED in this pass. `components/checkout-page.tsx`
used to call `trpc.user.coupon.getEligible.useQuery` and four `useMemo`s *after* its
`if (selectedItems.length === 0) return …` guard, so the hook count changed (4 → 9) as soon as
`useGetCart` resolved from `[]` to slotted lines and React threw *"Rendered more hooks than
during the previous render."* — the screen could not render at all with slotted items. The
hooks now sit above the guard, so the `?coupons=<id>` path is reachable and covered by
`checkout-coupons.test.tsx` (10 cases). Eligibility is honoured on both sides — the
`selectedCoupons` memo in each page filters on `isEligible`, so a coupon the cart cannot use is
ignored rather than silently discounted (including one that drifts out of eligibility after
selection, covered by `cart-coupons.test.tsx` case 11).
If you mount this page in a test without an error boundary and it ever throws again, the
runner wedges instead of failing (no output, ~0% CPU, no jest timeout); wrap it as
`checkout-crash.test.tsx` does.
Suites added alongside the parallel review — `cart-money`, `cart-storage`, `order-amounts`,
`product-detail-flash-flag`, `payment-and-order-money`, `force-logout`, `store-staleness`,
`auth-lifecycle` — are documented case-by-case in `tests/KNOWN-GAPS.md`; they are included in
the totals above but not yet in the per-suite tables below.
## Harness reference
| Path | Purpose |
| --- | --- |
| `tests/setup.ts` | Global stubs: axios, native modules (webview/updates/linking/location/notifications/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) |

View file

@ -0,0 +1,166 @@
# user-ui test suite
Runnable implementation of the cases catalogued in
[`../JEST-TEST-CASES.md`](../JEST-TEST-CASES.md).
```bash
cd apps/user-ui
bun run test -- tests/pages/home.test.tsx # a single file
bun run test # everything
```
Runner: `jest-expo` + `@testing-library/react-native`. Application code (stores,
hooks, components) runs for real; only network and native modules are mocked.
---
## Layout
```
tests/
jest.config.js preset, aliases, native-module mocks
setup.ts globals (fetch, console, act env)
fixtures/index.ts backend-shaped fixtures + cache URL builders
helpers/
test-utils.tsx render helpers, seeding helpers
reset.ts resetAllMocks() for beforeEach
mocks/
trpc-client.ts procedure-registry mock (queries + mutations + utils)
trpc-defaults.ts default payload per procedure
fetch-json.ts URL-keyed CDN JSON mock
expo-router-mock.tsx recorded router + layout primitives
secure-store-mock.ts in-memory SecureStore (StorageService*)
expo-location-mock.ts configurable device location
expo-notifications-mock.ts configurable push + listener emitters
auth-context.tsx deterministic AuthContext replacement
native/* native-module shims
```
## Standard test shape
```tsx
import { waitFor, fireEvent } from '@testing-library/react-native'
import Home from '@/app/(drawer)/(tabs)/home/index'
import { renderWithProviders, seedBoot, flush } from '../../helpers/test-utils'
import { resetAllMocks } from '../../helpers/reset'
import { setProcedure, lastProcedureInput } from '../../mocks/trpc-client'
describe('Home', () => {
beforeEach(() => resetAllMocks())
it('HOME-01: shows the loading copy while products are pending', async () => {
seedBoot()
setProcedure('common.essentialConsts', { mode: 'pending' })
const { getByText } = renderWithProviders(<Home />, { auth: 'in' })
expect(getByText('Loading products...')).toBeTruthy()
})
})
```
Rules:
1. One `it()` per catalogue row, prefixed with the row id (`HOME-01: ...`).
2. `resetAllMocks()` in `beforeEach`.
3. Assert the procedure + exact input for every mutation
(`lastProcedureInput('user.order.placeOrder')`).
4. Prefer `getByTestId` / `queryByTestId` over text matching. If a component is
missing a testID, **add only the `testID` attribute** to the component (never
change behaviour) and report it. Every added id is recorded in
`change-log.txt`.
5. Fake timers only for debounce / countdown / modal-delay cases.
## Render helpers
| Helper | Purpose |
| --- | --- |
| `renderWithProviders(ui, opts)` | QueryClient + RefreshProvider + real `AuthProvider` |
| `renderAndFlush(ui, opts)` | same, then `await flush()` |
| `flush(times = 1)` | drain microtasks/macrotasks inside `act` |
| `createTestQueryClient()` | fresh client (retry off, infinite gc) |
`opts`: `auth` = `'in' | 'out' | false` (default `'out'`; `false` skips
`AuthProvider`, for trees that only use `useAuthOptional`), `queryClient`,
`withRefresh`, `userId`, `token`.
## Seeding
| Helper | Effect |
| --- | --- |
| `seedJsonCache(overrides)` | products/availability/slots/stores/store-detail CDN docs |
| `seedCentralStores(overrides)` | central product + slot stores (needed by `useGetCart`) |
| `seedRegion(region, boundId)` | selects the browsing region without the location flow |
| `seedSelectedAddress(id)` | sets `addressStore.selectedAddressId` |
| `seedBoot({auth,addressId})` | the usual home/cart boot state |
| `seedAuthStorage('in' | 'out')` | token/userId in the storage mock |
Storage: `import { __set, __delete, __snapshot } from '../../mocks/secure-store-mock'`.
Cart lines live under `cart_items` / `flash_cart_items` (`CART_REG`, `CART_FLASH`).
## Procedure mock
```ts
setProcedure('user.order.getOrders', { data: { data: [], pagination: { totalPages: 0 } } })
setProcedure('user.auth.sendOtp', { mode: 'error', error: new Error('boom') })
setProcedure('user.auth.sendOtp', { mode: 'pending' })
setProcedure('user.order.placeOrder', { impl: (input) => ({ data: { orders: [input] } }) })
lastProcedureInput('user.auth.sendOtp')
procedureMutationCalls('user.order.placeOrder')
procedureQueryCalls('user.order.getOrders')
trpc.useUtils() // invalidations are recorded as jest.fn()s
```
Defaults for every procedure live in `mocks/trpc-defaults.ts`.
## CDN JSON mock
```ts
import { setJsonResponse, setJsonError, setJsonPending, jsonCallsFor } from '../../mocks/fetch-json'
import { productsCacheUrl } from '../../fixtures'
setJsonResponse(productsCacheUrl(), { products: [], count: 0, tags: [] })
setJsonError(productsCacheUrl(), new Error('offline'))
```
`setJsonResponse` supports a string, RegExp or predicate matcher; the last
registration wins.
## Native modules
```ts
import { __configure as configureLocation } from '../../mocks/expo-location-mock'
configureLocation({ permission: 'denied', position: null })
import { __configure as configureNotifications, __emitNotification, __emitResponse } from '../../mocks/expo-notifications-mock'
import { router, __setParams, __resetRouterMock } from '../../mocks/expo-router-mock'
expect(router.push).toHaveBeenCalledWith('/home/slot-view?slotId=1849')
```
For deterministic auth states, mock the context at the top of the file:
```tsx
jest.mock('@/src/contexts/AuthContext', () => require('../../mocks/auth-context'))
import { __setAuthState } from '../../mocks/auth-context'
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
```
## Fixtures
`CONSTS`, `CONSTS_FLASH_OFF`, `PRODUCTS`, `MERGED_PRODUCTS`, `TAGS`,
`AVAILABILITY`, `SLOTS` (+ `makeSlots(now)`), `STORES`, `STORE_DETAIL_1`,
`CART_REG`, `CART_FLASH`, `ADDRESSES` (`A1`/`A2`/`A3`), `COUPONS` (`C1…C8`),
`ORDERS` (`O1…O6`), `COMPLAINTS`, `REVIEWS`, `PRODUCT_DETAILS`, `AUTH_USER`,
`TEST_JWT`, `REGION_1`, `REGION_2`, `BOUND_1`, and the URL builders
`productsCacheUrl` / `availabilityCacheUrl` / `slotsCacheUrl` / `storesCacheUrl`
/ `storeDetailCacheUrl`.
## Known harness behaviours
- `useGetCart` reads `cart_items` from storage and enriches from the central
stores, so seed both (`seedCentralStores()` + `__set('cart_items', …)`).
- Auth seeding must be a decodable JWT (`TEST_JWT`), because `getCurrentUserId`
decodes the token to derive the user id.
- `useRegion` keeps module-level startup state. In a single file, tests that
assert the startup adopt/switch path should be ordered first, or the file
should re-require the module with `jest.isolateModules`.
- The `expo-router` mock records navigation but never navigates; layout
primitives render their children.

View file

@ -0,0 +1,283 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* APP-01..APP-24 — app entry + every route `_layout.tsx`.
*
* The `expo-router` mock records navigation and renders layout primitives as
* pass-throughs, so the layouts can be mounted directly. `Stack` / `Tabs` /
* `Slot` are the mock components themselves: their props (and `Stack.Screen`'s)
* are read back with `UNSAFE_getByType` / `UNSAFE_getAllByType` because the
* screen elements render `null`.
*/
import React from 'react'
import { ActivityIndicator } from 'react-native'
import { fireEvent, render, waitFor } from '@testing-library/react-native'
import { MyTouchableOpacity, theme } from 'common-ui'
import Index from '@/app/index'
import AuthLayout from '@/app/(auth)/_layout'
import DrawerLayout from '@/app/(drawer)/_layout'
import FlashIndex from '@/app/(drawer)/(tabs)/flash-delivery/index'
import FlashBaseLayout from '@/app/(drawer)/(tabs)/flash-delivery/_layout'
import HomeLayout from '@/app/(drawer)/(tabs)/home/_layout'
import SearchResultsLayout from '@/app/(drawer)/(tabs)/home/search-results/_layout'
import ProductDetailLayout from '@/app/(drawer)/(tabs)/home/product-detail/_layout'
import SlotViewLayout from '@/app/(drawer)/(tabs)/home/slot-view/_layout'
import StoreDetailLayout from '@/app/(drawer)/(tabs)/stores/store-detail/_layout'
import CouponsLayout from '@/app/(drawer)/(tabs)/me/coupons/_layout'
import MeLayout from '@/app/(drawer)/(tabs)/me/_layout'
import MyOrdersLayout from '@/app/(drawer)/(tabs)/me/my-orders/_layout'
import FloatingCartBar from '@/components/floating-cart-bar'
import { renderWithProviders, seedJsonCache, seedCentralStores, seedRegion } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { Stack, Tabs, Slot, router, __setParams } from '../mocks/expo-router-mock'
import { __setAuthState } from '../mocks/auth-context'
import { useAppStore } from '@/src/store/appStore'
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore'
import { setProcedure } from '../mocks/trpc-client'
import { CONSTS, CONSTS_FLASH_OFF } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
function authState(next: Record<string, any>) {
__setAuthState({ isLoading: false, isAuthenticated: false, user: null, ...next })
}
function renderLayout(ui: React.ReactElement) {
seedRegion()
return renderWithProviders(ui, { auth: false })
}
const allScreens = (view: any) => view.UNSAFE_getAllByType(Stack.Screen)
describe('app entry + route layouts (APP-01..APP-24)', () => {
beforeEach(() => {
resetAllMocks()
})
it('APP-01: auth loading renders the large spinner', () => {
authState({ isLoading: true })
const view = renderWithProviders(<Index />, { auth: false })
expect(view.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
expect(router.replace).not.toHaveBeenCalled()
})
it('APP-02: settled authenticated auth redirects to the home tab', () => {
authState({ isAuthenticated: true })
renderWithProviders(<Index />, { auth: false })
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
})
it('APP-03: settled signed-out auth still redirects home', () => {
authState({ isAuthenticated: false })
renderWithProviders(<Index />, { auth: false })
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
})
it('APP-04: auth layout while loading shows a spinner and no stack', () => {
authState({ isLoading: true })
const view = renderWithProviders(<AuthLayout />, { auth: false })
expect(view.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
expect(view.UNSAFE_queryByType(Stack)).toBeNull()
})
it('APP-05: loaded auth layout renders the stack', () => {
authState({ isLoading: false })
const view = renderWithProviders(<AuthLayout />, { auth: false })
expect(view.UNSAFE_getByType(Stack)).toBeTruthy()
})
it('APP-06: drawer layout while loading shows the pink spinner', () => {
authState({ isLoading: true })
const view = renderWithProviders(<DrawerLayout />, { auth: false })
const spinner = view.UNSAFE_getByType(ActivityIndicator)
expect(spinner.props.color).toBe(theme.colors.pink2)
})
it('APP-07: loaded drawer layout declares the five tabs', () => {
authState({ isLoading: false, isAuthenticated: true })
const view = renderLayout(<DrawerLayout />)
const screens = view.UNSAFE_getAllByType(Tabs.Screen)
expect(screens).toHaveLength(5)
expect(screens.map((screen: any) => screen.props.name)).toEqual([
'(tabs)/home',
'(tabs)/order-again',
'(tabs)/flash-delivery',
'(tabs)/stores',
'(tabs)/me',
])
expect(screens[0].props.options.tabBarLabel).toBe('Home')
expect(screens[1].props.options.tabBarLabel).toBe('Offers')
expect(screens[3].props.options.tabBarLabel).toBe('Stores')
expect(screens[4].props.options.tabBarLabel).toBe('Me')
})
it('APP-08: a single true hideTabsNav key hides the tab bar', () => {
authState({ isAuthenticated: true })
useAppStore.setState({ hideTabsNav: { quick_delivery: true } })
const view = renderLayout(<DrawerLayout />)
const tabs = view.UNSAFE_getByType(Tabs)
expect(tabs.props.screenOptions.tabBarStyle).toEqual({ display: 'none' })
})
it('APP-09: all-false hide keys keep the tab bar visible', () => {
authState({ isAuthenticated: true })
useAppStore.setState({ hideTabsNav: { quick_delivery: false, cart: false } })
const view = renderLayout(<DrawerLayout />)
const tabs = view.UNSAFE_getByType(Tabs)
expect(tabs.props.screenOptions.tabBarStyle.display).toBeUndefined()
expect(tabs.props.screenOptions.tabBarStyle.backgroundColor).toBe('white')
})
it('APP-10: the centre flash tab renders the gradient button with its selected state', () => {
authState({ isAuthenticated: true })
const view = renderLayout(<DrawerLayout />)
const center = view
.UNSAFE_getAllByType(Tabs.Screen)
.find((screen: any) => screen.props.name === '(tabs)/flash-delivery')
const button = render(
center.props.options.tabBarButton({ style: {}, accessibilityState: { selected: true } })
)
expect(button.getByText('1 Hr Delivery')).toBeTruthy()
expect(button.UNSAFE_getByType(MyTouchableOpacity).props.accessibilityState).toEqual({
selected: true,
})
})
it('APP-11: flash-delivery index redirects to the products route', () => {
renderWithProviders(<FlashIndex />, { auth: false })
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/flash-delivery/(products)')
})
it('APP-12: an undefined flash flag defaults to enabled and renders the slot tree', () => {
// `common.essentialConsts` never resolves -> `essentialConsts` is undefined.
setProcedure('common.essentialConsts', { mode: 'pending' })
const view = renderLayout(<FlashBaseLayout />)
expect(view.queryByText('1 Hr Delivery Unavailable')).toBeNull()
expect(view.UNSAFE_getByType(Slot)).toBeTruthy()
})
it('APP-13: isFlashDeliveryEnabled false shows the unavailable gate and replaces home', async () => {
setProcedure('common.essentialConsts', { data: CONSTS_FLASH_OFF })
const view = renderLayout(<FlashBaseLayout />)
await waitFor(() => expect(view.getByText('1 Hr Delivery Unavailable')).toBeTruthy())
fireEvent.press(view.getByText('Go to Scheduled Delivery'))
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
})
it('APP-14: isFlashDeliveryEnabled true renders the Slot children', () => {
setProcedure('common.essentialConsts', { data: CONSTS })
const view = renderLayout(<FlashBaseLayout />)
expect(view.UNSAFE_getByType(Slot)).toBeTruthy()
expect(view.queryByText('1 Hr Delivery Unavailable')).toBeNull()
})
it('APP-15: a set product-detail title flows into the stack screen options', () => {
useStoreHeaderStore.setState({ title: 'Chicken Breast' })
const view = renderLayout(<ProductDetailLayout />)
const screen = allScreens(view).find((candidate: any) => candidate.props.name === '[id]')
expect(screen.props.options.title).toBe('Chicken Breast')
})
it('APP-16: an empty product-detail title falls back to Product Details', () => {
useStoreHeaderStore.setState({ title: '' })
const view = renderLayout(<ProductDetailLayout />)
const screen = allScreens(view).find((candidate: any) => candidate.props.name === '[id]')
expect(screen.props.options.title).toBe('Product Details')
})
it('APP-17: a set store title updates the header and hides the product-detail header', () => {
useStoreHeaderStore.setState({ title: 'The Freshyo Meat House' })
const view = renderLayout(<StoreDetailLayout />)
const screens = allScreens(view)
const store = screens.find((candidate: any) => candidate.props.name === '[id]')
const productDetail = screens.find(
(candidate: any) => candidate.props.name === 'product-detail'
)
expect(store.props.options.title).toBe('The Freshyo Meat House')
expect(productDetail.props.options.headerShown).toBe(false)
})
it('APP-18: coupons opened from the cart hide the header back button', () => {
__setParams({ from: 'cart' })
const view = renderLayout(<CouponsLayout />)
expect(allScreens(view)[0].props.options.headerBackVisible).toBe(false)
})
it('APP-19: coupons opened without a source keep the header back button', () => {
__setParams({})
const view = renderLayout(<CouponsLayout />)
expect(allScreens(view)[0].props.options.headerBackVisible).toBe(true)
})
it('APP-20: me layout while loading shows the loading copy', () => {
authState({ isLoading: true })
const view = renderWithProviders(<MeLayout />, { auth: false })
expect(view.getByText('Loading...')).toBeTruthy()
})
it('APP-21: me layout signed out shows the login wall', () => {
authState({ isLoading: false, isAuthenticated: false })
const view = renderWithProviders(<MeLayout />, { auth: false })
expect(view.getByText('Log in to view your profile, orders and more.')).toBeTruthy()
})
it('APP-22: me layout signed in renders the stack', () => {
authState({ isLoading: false, isAuthenticated: true })
const view = renderWithProviders(<MeLayout />, { auth: false })
expect(view.UNSAFE_getByType(Stack)).toBeTruthy()
})
it('APP-23: the my-orders stack carries both titles', () => {
const view = renderLayout(<MyOrdersLayout />)
const stack = view.UNSAFE_getByType(Stack)
const detail = allScreens(view).find((candidate: any) => candidate.props.name === '[id]')
expect(stack.props.screenOptions.title).toBe('My Orders')
expect(detail.props.options.title).toBe('Order Details')
})
it('APP-24: the floating cart bar is mounted by the layouts that include it', () => {
seedJsonCache()
seedCentralStores()
const search = renderLayout(<SearchResultsLayout />)
expect(search.UNSAFE_getByType(FloatingCartBar)).toBeTruthy()
search.unmount()
const productDetail = renderLayout(<ProductDetailLayout />)
expect(productDetail.UNSAFE_getByType(FloatingCartBar)).toBeTruthy()
productDetail.unmount()
const home = renderLayout(<HomeLayout />)
expect(home.UNSAFE_queryByType(FloatingCartBar)).toBeNull()
home.unmount()
const slotView = renderLayout(<SlotViewLayout />)
expect(slotView.UNSAFE_getByType(FloatingCartBar)).toBeTruthy()
})
})

View file

@ -0,0 +1,566 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* ROOT-01..ROOT-29 — the app shell (`app/_layout.tsx`) and the wrappers it
* composes.
*
* Rows that need the *whole* provider tree (fonts gate, health gate) mount
* `RootLayout`; the remaining rows mount the individual wrapper so their
* behaviour is observable without the surrounding noise.
*/
import React from 'react'
import { Alert, BackHandler, Text, View } from 'react-native'
import { act, fireEvent, render, waitFor } from '@testing-library/react-native'
import { useFonts } from 'expo-font'
import * as Updates from 'expo-updates'
import * as Linking from 'expo-linking'
import Constants from 'expo-constants'
import RootLayout from '@/app/_layout'
import FirstUserWrapper from '@/components/FirstUserWrapper'
import HealthTestWrapper from '@/components/HealthTestWrapper'
import WebViewWrapper from '@/components/WebViewWrapper'
import UpdateChecker from '@/components/UpdateChecker'
import BackHandlerWrapper from '@/components/BackHandler'
import {
NotificationProvider,
useNotification,
} from '@/services/notif-service/notif-context'
import { renderWithProviders, flush, seedRegion } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client'
import { CONSTS } from '../fixtures'
import { router, __setPathname } from '../mocks/expo-router-mock'
import {
__configure as configureNotifications,
__emitNotification,
__emitResponse,
getExpoPushTokenAsync,
removeNotificationSubscription,
} from '../mocks/expo-notifications-mock'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { Stack } from '../mocks/expo-router-mock'
// `RootLayout` builds its own provider tree against the *real* singleton
// QueryClient (default 5-minute gc timers, which keep Jest's event loop alive
// long after the suite ends). Swap it for the harness client (gcTime Infinity).
jest.mock('@/utils/queryClient', () => ({
__esModule: true,
default: require('../helpers/test-utils').createTestQueryClient(),
}))
const fontsMock = useFonts as unknown as jest.Mock
const SOURCE_VERSION = '1.2.0'
const DEV = (global as any).__DEV__
function setDev(value: boolean) {
;(global as any).__DEV__ = value
}
function renderHealth(overrides: Record<string, any> = {}) {
seedRegion()
setProcedure('common.essentialConsts', { data: { ...CONSTS, ...overrides } })
return renderWithProviders(
<HealthTestWrapper>
<View testID="health-child" />
</HealthTestWrapper>,
{ auth: 'out' }
)
}
function renderUpdateChecker() {
seedRegion()
return renderWithProviders(
<UpdateChecker>
<View testID="update-child" />
</UpdateChecker>,
{ auth: 'out' }
)
}
function NotifProbe() {
const { expoPushToken, notifPermission, notification } = useNotification()
return (
<>
<Text testID="notif-token">{expoPushToken ?? 'no-token'}</Text>
<Text testID="notif-permission">{notifPermission}</Text>
<Text testID="notif-has-notification">{notification ? 'yes' : 'no'}</Text>
</>
)
}
describe('app shell (ROOT-01..ROOT-29)', () => {
beforeEach(() => {
resetAllMocks()
fontsMock.mockReturnValue([true, null])
setDev(DEV)
})
afterEach(() => {
setDev(DEV)
})
it('ROOT-01: an unloaded font set renders nothing', () => {
fontsMock.mockReturnValue([false])
const view = render(<RootLayout />)
expect(view.toJSON()).toBeNull()
expect(view.queryByTestId('app-root')).toBeNull()
})
it('ROOT-02: loaded fonts mount the provider tree and the stack', async () => {
seedRegion()
__set('isFirstTimeUser', 'false')
const view = render(<RootLayout />)
expect(view.getByTestId('app-root')).toBeTruthy()
await waitFor(() => expect(view.UNSAFE_getByType(Stack)).toBeTruthy())
})
it('ROOT-03: a pending health check still renders the children', async () => {
seedRegion()
__set('isFirstTimeUser', 'false')
setProcedure('common.healthCheck', { mode: 'pending' })
const view = render(<RootLayout />)
expect(view.getByTestId('app-root')).toBeTruthy()
expect(view.queryByText('Service Unavailable')).toBeNull()
await flush()
})
it('ROOT-04: a failing health check shows Service Unavailable and a Retry action', async () => {
seedRegion()
setProcedure('common.healthCheck', { mode: 'error', error: new Error('offline') })
const view = render(<RootLayout />)
await waitFor(() => expect(view.getByText('Service Unavailable')).toBeTruthy())
// `refetch` on the tRPC query mock is a bare jest.fn that records nothing,
// so the re-request itself cannot be observed here: assert the Retry
// control is wired and pressing it does not throw.
fireEvent.press(view.getByText('Retry'))
expect(view.getByText('Service Unavailable')).toBeTruthy()
})
it('ROOT-05: an older build on iOS shows the update dialog and opens the App Store', async () => {
const view = renderHealth({ versionNum: '1.3.0' })
await waitFor(() => expect(view.getByText('Update Available')).toBeTruthy())
fireEvent.press(view.getByText('Update Now'))
expect(Linking.openURL).toHaveBeenCalledWith(CONSTS.appStoreUrl)
})
it('ROOT-06: an older build on Android opens the Play Store', async () => {
const previous = require('react-native').Platform.OS
require('react-native').Platform.OS = 'android'
try {
const view = renderHealth({ versionNum: '1.3.0' })
await waitFor(() => expect(view.getByText('Update Available')).toBeTruthy())
fireEvent.press(view.getByText('Update Now'))
expect(Linking.openURL).toHaveBeenCalledWith(CONSTS.playStoreUrl)
} finally {
require('react-native').Platform.OS = previous
}
})
it('ROOT-07: equal or newer local versions never show the update dialog', async () => {
const equal = renderHealth({ versionNum: SOURCE_VERSION })
await flush()
expect(equal.queryByText('Update Available')).toBeNull()
equal.unmount()
const newer = renderHealth({ versionNum: '1.0.0' })
await flush()
expect(newer.queryByText('Update Available')).toBeNull()
})
it('ROOT-08: a malformed version on either side is ignored without crashing', async () => {
const malformedBackend = renderHealth({ versionNum: 'abc.def.ghi' })
await flush()
expect(malformedBackend.queryByText('Update Available')).toBeNull()
const original = Constants.expoConfig!.version
;(Constants.expoConfig as any).version = 'bad'
try {
const malformedLocal = renderHealth({ versionNum: '9.9.9' })
await flush()
expect(malformedLocal.queryByText('Update Available')).toBeNull()
} finally {
;(Constants.expoConfig as any).version = original
}
})
it('ROOT-09: a first-time user sees the welcome screen and Next stores the flag', async () => {
const view = render(
<FirstUserWrapper>
<View testID="first-user-child" />
</FirstUserWrapper>
)
await waitFor(() => expect(view.getByText('Hello Happy Shopping')).toBeTruthy())
expect(view.queryByTestId('first-user-child')).toBeNull()
fireEvent.press(view.getByText('Next'))
await waitFor(() => expect(view.getByTestId('first-user-child')).toBeTruthy())
expect(__snapshot().isFirstTimeUser).toBe('false')
})
it("ROOT-10: the stored 'false' value renders the children directly", async () => {
__set('isFirstTimeUser', 'false')
const view = render(
<FirstUserWrapper>
<View testID="first-user-child" />
</FirstUserWrapper>
)
await waitFor(() => expect(view.getByTestId('first-user-child')).toBeTruthy())
expect(view.queryByText('Hello Happy Shopping')).toBeNull()
})
it("ROOT-11: a 'true' or arbitrary stored value keeps the welcome screen", async () => {
for (const stored of ['true', 'anything-else']) {
__set('isFirstTimeUser', stored)
const view = render(
<FirstUserWrapper>
<View testID="first-user-child" />
</FirstUserWrapper>
)
await waitFor(() => expect(view.getByText('Hello Happy Shopping')).toBeTruthy())
expect(view.queryByTestId('first-user-child')).toBeNull()
view.unmount()
}
})
it('ROOT-12: an absent webviewHtml renders the children', async () => {
seedRegion()
const view = renderWithProviders(
<WebViewWrapper>
<View testID="webview-child" />
</WebViewWrapper>,
{ auth: 'out' }
)
await flush()
expect(view.getByTestId('webview-child')).toBeTruthy()
expect(view.queryByTestId('webview')).toBeNull()
})
it('ROOT-13: a non-closable webview hides the children', async () => {
seedRegion()
setProcedure('common.essentialConsts', {
data: { ...CONSTS, webviewHtml: '<h1>hello</h1>', isWebviewClosable: false },
})
const view = renderWithProviders(
<WebViewWrapper>
<View testID="webview-child" />
</WebViewWrapper>,
{ auth: 'out' }
)
await waitFor(() => expect(view.getByTestId('webview')).toBeTruthy())
expect(view.queryByTestId('webview-child')).toBeNull()
expect(view.queryByTestId('webview-close')).toBeNull()
})
it('ROOT-14: the close button hides a closable webview and reveals the children', async () => {
seedRegion()
setProcedure('common.essentialConsts', {
data: { ...CONSTS, webviewHtml: '<h1>hello</h1>', isWebviewClosable: true },
})
const view = renderWithProviders(
<WebViewWrapper>
<View testID="webview-child" />
</WebViewWrapper>,
{ auth: 'out' }
)
await waitFor(() => expect(view.getByTestId('webview-close')).toBeTruthy())
fireEvent.press(view.getByTestId('webview-close'))
await waitFor(() => expect(view.getByTestId('webview-child')).toBeTruthy())
expect(view.queryByTestId('webview')).toBeNull()
})
it('ROOT-15: in development a newer backend internal version does not alert', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
setDev(true)
renderUpdateChecker()
setProcedure('common.essentialConsts', {
data: { ...CONSTS, internalAppVersion: 5 },
})
await flush(3)
expect(alertSpy).not.toHaveBeenCalled()
})
it('ROOT-16: in production a newer backend internal version alerts once and updates', async () => {
setDev(false)
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
renderUpdateChecker()
setProcedure('common.essentialConsts', {
data: { ...CONSTS, internalAppVersion: 5 },
})
await waitFor(() => expect(alertSpy).toHaveBeenCalledTimes(1))
expect(alertSpy.mock.calls[0][0]).toBe('Update available')
const buttons = alertSpy.mock.calls[0][2] as any[]
const update = buttons.find((button) => button.text === 'Update & Restart')
await act(async () => {
await update.onPress()
})
expect(Updates.fetchUpdateAsync).toHaveBeenCalledTimes(1)
expect(Updates.reloadAsync).toHaveBeenCalledTimes(1)
expect((Updates.fetchUpdateAsync as jest.Mock).mock.invocationCallOrder[0]).toBeLessThan(
(Updates.reloadAsync as jest.Mock).mock.invocationCallOrder[0]
)
})
it('ROOT-17: an update fetch failure does not crash or reload', async () => {
setDev(false)
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
;(Updates.fetchUpdateAsync as jest.Mock).mockRejectedValueOnce(new Error('no update'))
renderUpdateChecker()
setProcedure('common.essentialConsts', {
data: { ...CONSTS, internalAppVersion: 5 },
})
await waitFor(() => expect(alertSpy).toHaveBeenCalledTimes(1))
const update = (alertSpy.mock.calls[0][2] as any[]).find(
(button) => button.text === 'Update & Restart'
)
await act(async () => {
await update.onPress()
})
expect(Updates.reloadAsync).not.toHaveBeenCalled()
})
it('ROOT-18: back on home with an empty stack asks to exit and exits', () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
const exitSpy = jest.spyOn(BackHandler, 'exitApp').mockImplementation(() => undefined)
let handler: (() => boolean) | undefined
jest
.spyOn(BackHandler, 'addEventListener')
.mockImplementation((_event: any, listener: any) => {
handler = listener
return { remove: jest.fn() }
})
__setPathname('/home')
router.canGoBack.mockReturnValue(false)
render(<BackHandlerWrapper />)
const result = handler!()
expect(result).toBe(true)
expect(alertSpy).toHaveBeenCalledWith(
'Exit App',
'Are you sure you want to exit?',
expect.any(Array)
)
const exit = (alertSpy.mock.calls[0][2] as any[]).find((button) => button.text === 'Exit')
exit.onPress()
expect(exitSpy).toHaveBeenCalledTimes(1)
})
it('ROOT-19: back on a non-home route is not intercepted', () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
let handler: (() => boolean) | undefined
jest
.spyOn(BackHandler, 'addEventListener')
.mockImplementation((_event: any, listener: any) => {
handler = listener
return { remove: jest.fn() }
})
__setPathname('/stores')
router.canGoBack.mockReturnValue(false)
render(<BackHandlerWrapper />)
expect(handler!()).toBe(false)
expect(alertSpy).not.toHaveBeenCalled()
})
it('ROOT-20: back while the stack can go back is not intercepted', () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
let handler: (() => boolean) | undefined
jest
.spyOn(BackHandler, 'addEventListener')
.mockImplementation((_event: any, listener: any) => {
handler = listener
return { remove: jest.fn() }
})
__setPathname('/home')
router.canGoBack.mockReturnValue(true)
render(<BackHandlerWrapper />)
expect(handler!()).toBe(false)
expect(alertSpy).not.toHaveBeenCalled()
})
it('ROOT-21: the first-user gate renders nothing while the storage read is pending', () => {
const view = render(
<FirstUserWrapper>
<View testID="first-user-child" />
</FirstUserWrapper>
)
expect(view.toJSON()).toBeNull()
})
it('ROOT-22: unmounting the back handler removes its subscription', () => {
const remove = jest.fn()
jest
.spyOn(BackHandler, 'addEventListener')
.mockImplementation(() => ({ remove }))
__setPathname('/home')
router.canGoBack.mockReturnValue(false)
const view = render(<BackHandlerWrapper />)
view.unmount()
expect(remove).toHaveBeenCalledTimes(1)
})
it('ROOT-23: a registered push token and granted permission are exposed to children', async () => {
const view = renderWithProviders(
<NotificationProvider>
<NotifProbe />
</NotificationProvider>,
{ auth: false }
)
await waitFor(() =>
expect(view.getByTestId('notif-token').props.children).toBe(
'ExponentPushToken[test-token]'
)
)
expect(view.getByTestId('notif-permission').props.children).toBe('granted')
})
it('ROOT-24: a permission-denied registration exposes the denied permission', async () => {
configureNotifications({ permission: 'denied', requestResult: 'denied' })
const view = renderWithProviders(
<NotificationProvider>
<NotifProbe />
</NotificationProvider>,
{ auth: false }
)
await waitFor(() => expect(view.getByTestId('notif-permission').props.children).toBe('denied'))
})
it('ROOT-25: any other registration failure leaves the permission pending', async () => {
getExpoPushTokenAsync.mockRejectedValueOnce(new Error('token boom'))
const view = renderWithProviders(
<NotificationProvider>
<NotifProbe />
</NotificationProvider>,
{ auth: false }
)
await flush(3)
expect(view.getByTestId('notif-permission').props.children).toBe('pending')
expect(view.getByTestId('notif-token').props.children).toBe('no-token')
})
it('ROOT-26: a foreground notification shows a toast with its title and body', async () => {
const Toast = require('react-native-toast-message').default
const view = renderWithProviders(
<NotificationProvider>
<NotifProbe />
</NotificationProvider>,
{ auth: false }
)
await waitFor(() =>
expect(view.getByTestId('notif-token').props.children).toBe(
'ExponentPushToken[test-token]'
)
)
act(() => {
__emitNotification({
request: {
content: { title: 'New Order', body: 'Your order is confirmed', data: { orderId: 1 } },
},
})
})
expect(view.getByTestId('notif-has-notification').props.children).toBe('yes')
expect(Toast.show).toHaveBeenCalledWith(
expect.objectContaining({ text1: 'New Order', text2: 'Your order is confirmed' })
)
})
it('ROOT-27: a notification response carrying doctorId routes home', async () => {
const view = renderWithProviders(
<NotificationProvider>
<NotifProbe />
</NotificationProvider>,
{ auth: false }
)
await waitFor(() =>
expect(view.getByTestId('notif-token').props.children).toBe(
'ExponentPushToken[test-token]'
)
)
act(() => {
__emitResponse({
notification: { request: { content: { data: { doctorId: 7 } } } },
})
})
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
})
it('ROOT-28: a notification response carrying tokenId routes home', async () => {
const view = renderWithProviders(
<NotificationProvider>
<NotifProbe />
</NotificationProvider>,
{ auth: false }
)
await waitFor(() =>
expect(view.getByTestId('notif-token').props.children).toBe(
'ExponentPushToken[test-token]'
)
)
act(() => {
__emitResponse({
notification: { request: { content: { data: { tokenId: 9 } } } },
})
})
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
})
it('ROOT-29: unmounting the provider removes both notification subscriptions', async () => {
const view = renderWithProviders(
<NotificationProvider>
<NotifProbe />
</NotificationProvider>,
{ auth: false }
)
await waitFor(() =>
expect(view.getByTestId('notif-token').props.children).toBe(
'ExponentPushToken[test-token]'
)
)
view.unmount()
expect(removeNotificationSubscription).toHaveBeenCalledTimes(2)
})
})

View file

@ -0,0 +1,113 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Section 24 — AddToCartDialog (A2C-01..06).
*
* The dialog is driven by `useCartStore`'s `addedToCartProduct`; the product is
* queued with `setAddedToCartProduct` before render. Slots come from the CDN
* `slots.json` document (via `seedBoot`), the cart lines from `cart_items`.
*/
import * as React from 'react'
import { ScrollView, TouchableOpacity } from 'react-native'
import { fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs'
import AddToCartDialog from '@/src/components/AddToCartDialog'
import { useCartStore } from '@/src/store/cartStore'
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { __set } from '../mocks/secure-store-mock'
import { CART_REG, P_CHICKEN, P_CUCUMBER, SLOTS } from '../fixtures'
const APPENDED_AT = '2024-01-01T00:00:00.000Z'
/** The dialog labels each slot row with its delivery minute. */
const slotTestId = (slot: { deliveryTime: string }) =>
`slot-${dayjs(slot.deliveryTime).format('YYYY-MM-DD-HH-mm')}`
// Chicken (SKU 2) is served by every fixture slot; only the three whose
// freezeTime is still in the future survive the dialog's filter.
const CHICKEN_SLOTS = [SLOTS[0], SLOTS[1], SLOTS[3]].map(slotTestId)
// Cucumber (SKU 5) is served by slots 1849 and 1852.
const CUCUMBER_SLOTS = [SLOTS[0], SLOTS[3]].map(slotTestId)
const cartLine = (id: number, skuId: number, quantity: number, slotId: number) =>
JSON.stringify([{ id, skuId, quantity, slotId, addedAt: APPENDED_AT }])
async function renderDialog(product: any, cart?: string) {
seedBoot()
if (cart) __set('cart_items', cart)
useCartStore.getState().setAddedToCartProduct({ productId: product.id, product })
const utils = renderWithProviders(<AddToCartDialog />, { auth: false })
await flush(2)
return utils
}
describe('AddToCartDialog', () => {
beforeEach(() => resetAllMocks())
it('A2C-01: many slots — the slot list scrolls while the actions stay mounted', async () => {
const { getByTestId, getByText, UNSAFE_getAllByType } = await renderDialog(P_CHICKEN)
await waitFor(() => expect(getByTestId(CHICKEN_SLOTS[2])).toBeTruthy())
CHICKEN_SLOTS.forEach((testID) => expect(getByTestId(testID)).toBeTruthy())
// The only shrinkable region is the slot list; the actions below it are
// rendered outside that scroll view.
const list = UNSAFE_getAllByType(ScrollView).find(
(node) => (node.props.style as any)?.flexShrink === 1
)
expect(list).toBeTruthy()
expect(getByTestId('add-to-cart-confirm')).toBeTruthy()
expect(getByText('Cancel')).toBeTruthy()
})
it('A2C-02: two slots — only that product’s rows render and the sheet is content-sized', async () => {
const { getByTestId, queryByTestId } = await renderDialog(P_CUCUMBER)
await waitFor(() => expect(getByTestId(CUCUMBER_SLOTS[1])).toBeTruthy())
CUCUMBER_SLOTS.forEach((testID) => expect(getByTestId(testID)).toBeTruthy())
// Chicken's second slot (1850) is not a cucumber slot.
expect(queryByTestId(CHICKEN_SLOTS[1])).toBeNull()
expect(getByTestId('add-to-cart-confirm')).toBeTruthy()
})
it('A2C-03: quantity update when an existing line is present — remove button visible', async () => {
const { getByTestId } = await renderDialog(P_CHICKEN, CART_REG)
await waitFor(() => expect(getByTestId('remove-from-cart')).toBeTruthy())
// Cart line quantity (2) is preselected.
expect(getByTestId('quantifier-value')).toHaveTextContent('2')
})
it('A2C-04: no cart line — no remove button', async () => {
const { getByTestId, queryByTestId, getByText } = await renderDialog(P_CHICKEN)
await waitFor(() => expect(getByTestId('add-to-cart-confirm')).toBeTruthy())
expect(queryByTestId('remove-from-cart')).toBeNull()
expect(getByText('Add to Cart')).toBeTruthy()
})
it('A2C-05: a cart line for another SKU is not treated as an update', async () => {
const { getByTestId, queryByTestId, getByText } = await renderDialog(
P_CHICKEN,
cartLine(1, P_CUCUMBER.id, 3, SLOTS[0].id)
)
await waitFor(() => expect(getByTestId('add-to-cart-confirm')).toBeTruthy())
expect(queryByTestId('remove-from-cart')).toBeNull()
expect(getByText('Add to Cart')).toBeTruthy()
})
it('A2C-06: pressing the backdrop closes the dialog and clears the product', async () => {
const { UNSAFE_getAllByType } = await renderDialog(P_CHICKEN, CART_REG)
await waitFor(() => expect(useCartStore.getState().addedToCartProduct).not.toBeNull())
const backdrop = UNSAFE_getAllByType(TouchableOpacity).find(
(node) => node.props.activeOpacity === 1 && typeof node.props.onPress === 'function'
)
expect(backdrop).toBeTruthy()
fireEvent.press(backdrop!)
expect(useCartStore.getState().addedToCartProduct).toBeNull()
})
})

View file

@ -0,0 +1,678 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 17.2 — `AddressForm` (`tests/components/address-form.test.tsx`).
*
* ADDRF-01..37. The region/coordinate resolution goes through
* `utils.common.resolveRegionByLocation.fetch` / `utils.common.resolveBound.fetch`,
* which the procedure mock does NOT record (only `useQuery`/`useMutation` are
* recorded). So the inputs are captured with an `impl` spy instead, and the
* observable UI (heading, city, error text, `onResolvedRegion`) is asserted too.
*
* The map step is a stubbed WebView: its `source.uri` and `onMessage` come back
* through the props of the rendered `webview` host.
*/
import * as React from 'react'
import { fireEvent, waitFor, within, act } from '@testing-library/react-native'
import AddressForm from '@/src/components/AddressForm'
import LocationMapStep from '@/src/components/location/LocationMapStep'
import constants from '@/src/constants'
import { renderWithProviders, seedRegion } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastProcedureInput,
procedureMutationCalls,
} from '../mocks/trpc-client'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import { __snapshot as secureSnapshot } from '../mocks/secure-store-mock'
import { A1, REGION_1, REGION_2, BOUND_1 } from '../fixtures'
// AddressForm imports `../trpc-client`, which the jest `moduleNameMapper`
// (`^(.*/)?src/trpc-client$`) does not catch. Mock the resolved file explicitly
// so the component talks to the harness procedure registry.
jest.mock('../../src/trpc-client.ts', () => require('../mocks/trpc-client'))
const MAP_BASE = `${constants.WEB_UI_BASE_URL}/location-selector`
const PENDING_ADDRESS_KEY = 'freshyo_pending_address'
const REGION_1_CENTER = { ...REGION_1, center: { lat: 11, lng: 22 } }
const REGION_2_CENTER = { ...REGION_2, center: { lat: 33, lng: 44 } }
const BASE_VALUES = {
name: 'Alice',
phone: '9876543210',
addressLine1: '12 Main Road',
addressLine2: '',
city: 'Mahabubnagar',
state: 'Telangana',
isDefault: false,
}
function withCoords(overrides: Record<string, any> = {}) {
return { ...BASE_VALUES, latitude: 17, longitude: 78, ...overrides }
}
/** No device fix: keeps the "no location yet" branches deterministic. */
function denyLocation() {
configureLocation({ permission: 'denied', servicesEnabled: false, position: null })
}
/** Grant a device fix and return the exact rounded coords the store will hold. */
function grantLocation(latitude = 12.34, longitude = 56.78) {
configureLocation({
permission: 'granted',
servicesEnabled: true,
position: { coords: { latitude, longitude, accuracy: 5 }, timestamp: 1 },
})
return { latitude, longitude }
}
/** Spy on the (un-recorded) `resolveRegionByLocation.fetch` input. */
function spyResolveRegion(result: any = { region: REGION_1, bound: BOUND_1 }) {
const impl = jest.fn(() => result)
setProcedure('common.resolveRegionByLocation', { impl })
return impl
}
function failResolveRegion(message = 'boom') {
const impl = jest.fn(() => {
throw new Error(message)
})
setProcedure('common.resolveRegionByLocation', { impl })
return impl
}
/** Spy on the (un-recorded) `resolveBound.fetch` input. */
function spyResolveBound(result: any = { regionId: 2, boundId: 8 }) {
const impl = jest.fn(() => result)
setProcedure('common.resolveBound', { impl })
return impl
}
function renderForm(props: Record<string, any> = {}) {
const onSuccess = jest.fn()
const onResolvedRegion = jest.fn()
const result = renderWithProviders(
<AddressForm onSuccess={onSuccess} onResolvedRegion={onResolvedRegion} {...props} />,
{ auth: false }
)
return { ...result, onSuccess, onResolvedRegion }
}
/** Open the map through the location chooser: attach -> region picker -> region. */
function openMapViaChooser(screen: any, regionId = 1) {
fireEvent.press(screen.getByTestId('address-attach-location'))
fireEvent.press(screen.getByTestId(`address-map-region-${regionId}`))
}
/** Open the map through the City picker's "Select in Map" option. */
function openMapViaCity(screen: any) {
fireEvent.press(screen.getByTestId('address-city'))
fireEvent.press(screen.getByTestId('address-city-option-map'))
}
function sendMapMessage(screen: any, payload: string) {
fireEvent(screen.getByTestId('webview'), 'message', { nativeEvent: { data: payload } })
}
describe('AddressForm', () => {
beforeEach(() => resetAllMocks())
it('ADDRF-01: add mode shows "Add Address" and no service-area notice', () => {
denyLocation()
const { getAllByText, queryByText } = renderForm()
expect(getAllByText('Add Address').length).toBeGreaterThan(0)
expect(queryByText('Edit Address')).toBeNull()
expect(queryByText(/outside our delivery area/)).toBeNull()
})
it('ADDRF-02: edit mode shows "Edit Address" and prefilled values', () => {
denyLocation()
const { getByText, getByTestId } = renderForm({
isEdit: true,
initialValues: { id: 42, ...BASE_VALUES },
})
expect(getByText('Edit Address')).toBeTruthy()
expect(getByTestId('address-name').props.value).toBe('Alice')
expect(getByTestId('address-phone').props.value).toBe('9876543210')
expect(getByTestId('address-line1').props.value).toBe('12 Main Road')
})
it('ADDRF-03: a known browsing region preselects the city', () => {
denyLocation()
seedRegion(REGION_1, 7)
const { getByText } = renderForm()
expect(getByText('Mahabubnagar')).toBeTruthy()
})
it('ADDRF-04: with no browsing region the city shows the "Select town" placeholder', () => {
denyLocation()
const { getByText } = renderForm()
expect(getByText('Select town')).toBeTruthy()
})
it('ADDRF-05: a device fix auto-resolves and shows "Current Location Attached"', async () => {
const coords = grantLocation(12.34, 56.78)
const resolve = spyResolveRegion()
const { getByText, onResolvedRegion } = renderForm()
await waitFor(() => expect(getByText('Current Location Attached')).toBeTruthy())
expect(resolve).toHaveBeenCalledWith({ lat: coords.latitude, lng: coords.longitude })
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalledWith({ regionId: 1, boundId: 7 }))
})
it('ADDRF-06: a device fix outside the area is refused', async () => {
denyLocation()
spyResolveRegion(null)
const { getByText } = renderForm({ initialValues: withCoords() })
await waitFor(() =>
expect(
getByText('This location is outside our delivery area. Try selecting on the map.')
).toBeTruthy()
)
})
it('ADDRF-07: a throwing resolve shows "Could not verify this location."', async () => {
denyLocation()
failResolveRegion()
const { getByText } = renderForm({ initialValues: withCoords() })
await waitFor(() =>
expect(getByText('Could not verify this location. Please try again.')).toBeTruthy()
)
})
it('ADDRF-08: initial coordinates resolve on mount', async () => {
denyLocation()
const resolve = spyResolveRegion()
const { getByText, onResolvedRegion } = renderForm({ initialValues: withCoords() })
await waitFor(() => expect(resolve).toHaveBeenCalledWith({ lat: 17, lng: 78 }))
expect(getByText('Current Location Attached')).toBeTruthy()
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalledWith({ regionId: 1, boundId: 7 }))
})
it('ADDRF-09: without a location the submit is disabled and the hint appears once name is touched', () => {
denyLocation()
const { getByTestId, getByText } = renderForm()
const submit = getByTestId('address-submit')
expect(submit.props.accessibilityState.disabled).toBe(true)
fireEvent(getByTestId('address-name'), 'blur', { target: {}, nativeEvent: {} })
expect(getByText('Attach a location to add address')).toBeTruthy()
})
it('ADDRF-10: opening the city picker lists the regions, "Select in Map" and no empty message', () => {
denyLocation()
const { getByTestId, getByText, queryByText } = renderForm()
fireEvent.press(getByTestId('address-city'))
expect(getByTestId('address-city-option-1')).toBeTruthy()
expect(getByTestId('address-city-option-2')).toBeTruthy()
expect(getByText('Select in Map')).toBeTruthy()
expect(queryByText('No towns available')).toBeNull()
})
it('ADDRF-11: picking a city with no location shows the attach-location error', async () => {
denyLocation()
const { getByTestId, getByText } = renderForm()
fireEvent.press(getByTestId('address-city'))
fireEvent.press(getByTestId('address-city-option-2'))
await waitFor(() =>
expect(getByText('Attach or pick a location inside this town.')).toBeTruthy()
)
})
it('ADDRF-12: picking a city with a location re-resolves the bound', async () => {
denyLocation()
spyResolveRegion()
const resolveBound = spyResolveBound({ regionId: 2, boundId: 8 })
const { getByTestId, getByText, onResolvedRegion } = renderForm({
initialValues: withCoords(),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalledWith({ regionId: 1, boundId: 7 }))
fireEvent.press(getByTestId('address-city'))
fireEvent.press(getByTestId('address-city-option-2'))
await waitFor(() =>
expect(resolveBound).toHaveBeenCalledWith({ regionId: 2, lat: 17, lng: 78 })
)
await waitFor(() =>
expect(onResolvedRegion).toHaveBeenLastCalledWith({ regionId: 2, boundId: 8 })
)
expect(getByText('Hyderabad')).toBeTruthy()
})
it('ADDRF-13: a failing bound resolve shows the outside-town error', async () => {
denyLocation()
spyResolveRegion()
const resolveBound = jest.fn(() => {
throw new Error('nope')
})
setProcedure('common.resolveBound', { impl: resolveBound })
const { getByTestId, getByText, onResolvedRegion } = renderForm({
initialValues: withCoords(),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-city'))
fireEvent.press(getByTestId('address-city-option-2'))
await waitFor(() =>
expect(
getByText('Your location is outside this town. Pick a point on the map inside it.')
).toBeTruthy()
)
})
it('ADDRF-14: "Select in Map" from the city picker opens the map at the first region centre', () => {
denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm()
openMapViaCity({ getByTestId } as any)
const webview = getByTestId('webview')
expect(webview.props.source.uri).toBe(`${MAP_BASE}?lat=11&lng=22`)
})
it('ADDRF-15: the location chooser opens the region picker and marks the current region', () => {
denyLocation()
seedRegion(REGION_1, 7)
const { getByTestId, getByText } = renderForm()
fireEvent.press(getByTestId('address-attach-location'))
expect(getByTestId('address-map-region-1')).toBeTruthy()
expect(within(getByTestId('address-map-region-1')).getByText('Current')).toBeTruthy()
expect(getByText('Select a region')).toBeTruthy()
})
it('ADDRF-16: picking a region in the chooser opens the map at that region centre', () => {
denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm()
fireEvent.press(getByTestId('address-attach-location'))
fireEvent.press(getByTestId('address-map-region-2'))
expect(getByTestId('webview').props.source.uri).toBe(`${MAP_BASE}?lat=33&lng=44`)
})
it('ADDRF-17: "Select in Map" from the chooser opens the map at the first region', () => {
denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm()
fireEvent.press(getByTestId('address-attach-location'))
fireEvent.press(getByTestId('address-map-region-select-in-map'))
expect(getByTestId('webview').props.source.uri).toBe(`${MAP_BASE}?lat=11&lng=22`)
})
it('ADDRF-18: cancelling the region chooser closes it', () => {
denyLocation()
const { getByTestId, queryByTestId } = renderForm()
fireEvent.press(getByTestId('address-attach-location'))
expect(getByTestId('address-map-region-1')).toBeTruthy()
fireEvent.press(getByTestId('address-map-region-cancel'))
expect(queryByTestId('address-map-region-1')).toBeNull()
})
it('ADDRF-19: a map selection closes the map, resolves as "map" and updates the heading', async () => {
denyLocation()
const resolve = spyResolveRegion()
const { getByTestId, getByText, queryByTestId, onResolvedRegion } = renderForm({
initialValues: withCoords(),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
resolve.mockClear()
fireEvent.press(getByTestId('address-choose-location'))
fireEvent.press(getByTestId('address-map-region-1'))
sendMapMessage(
{ getByTestId } as any,
JSON.stringify({ type: 'location-selected', latitude: 12.5, longitude: 77.5 })
)
await waitFor(() => expect(getByText('Location Attached from Map')).toBeTruthy())
expect(resolve).toHaveBeenCalledWith({ lat: 12.5, lng: 77.5 })
expect(queryByTestId('webview')).toBeNull()
})
it('ADDRF-20: cancelling the map closes it without changing the location', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, getByText, queryByTestId, onResolvedRegion } = renderForm({
initialValues: withCoords(),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
expect(getByText('Current Location Attached')).toBeTruthy()
fireEvent.press(getByTestId('address-choose-location'))
fireEvent.press(getByTestId('address-map-region-1'))
expect(getByTestId('webview')).toBeTruthy()
fireEvent.press(getByText('Cancel'))
expect(queryByTestId('webview')).toBeNull()
expect(getByText('Current Location Attached')).toBeTruthy()
})
it('ADDRF-21: an empty name fails validation', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, getByText, onResolvedRegion } = renderForm({
initialValues: withCoords({ name: '' }),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(getByText('Name is required')).toBeTruthy())
})
it('ADDRF-22: an invalid phone fails the 10-digit 6-9 rule', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, getByText, onResolvedRegion } = renderForm({
initialValues: withCoords({ phone: '12345' }),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() =>
expect(
getByText('Phone must be a 10-digit number starting with 6, 7, 8 or 9')
).toBeTruthy()
)
})
it('ADDRF-23: an empty address line 1 fails validation', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, getByText, onResolvedRegion } = renderForm({
initialValues: withCoords({ addressLine1: '' }),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(getByText('Address Line 1 is required')).toBeTruthy())
})
it('ADDRF-24: state is prefilled "Telangana" and disabled', () => {
denyLocation()
const { getByTestId } = renderForm()
const state = getByTestId('address-state')
expect(state.props.value).toBe('Telangana')
expect(state.props.editable === false || state.props.accessibilityState?.disabled === true).toBe(
true
)
})
it('ADDRF-25: an empty address line 2 is accepted on submit', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, onResolvedRegion } = renderForm({
initialValues: withCoords({ addressLine2: '' }),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(lastProcedureInput('user.address.createAddress')).toBeTruthy())
expect(lastProcedureInput('user.address.createAddress').addressLine2).toBe('')
})
it('ADDRF-26: the default checkbox toggles isDefault in the payload', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, onResolvedRegion } = renderForm({
initialValues: withCoords({ isDefault: false }),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-default-checkbox'))
expect(getByTestId('address-default-checkbox').props.accessibilityState.checked).toBe(true)
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(lastProcedureInput('user.address.createAddress')).toBeTruthy())
expect(lastProcedureInput('user.address.createAddress').isDefault).toBe(true)
})
it('ADDRF-27: a create submit sends regionId, city name and coordinates', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, onResolvedRegion } = renderForm({ initialValues: withCoords() })
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1))
expect(lastProcedureInput('user.address.createAddress')).toEqual({
...withCoords(),
city: 'Mahabubnagar',
regionId: 1,
latitude: 17,
longitude: 78,
googleMapsUrl: undefined,
})
})
it('ADDRF-28: an edit submit includes the address id', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, onResolvedRegion } = renderForm({
isEdit: true,
initialValues: { id: 42, ...withCoords() },
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(procedureMutationCalls('user.address.updateAddress')).toHaveLength(1))
const input = lastProcedureInput('user.address.updateAddress')
expect(input.id).toBe(42)
expect(input).toEqual({
id: 42,
...withCoords(),
city: 'Mahabubnagar',
regionId: 1,
latitude: 17,
longitude: 78,
googleMapsUrl: undefined,
})
})
it('ADDRF-29: draft mode saves the pending address, calls onSuccess with no id and skips the API', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, onSuccess, onResolvedRegion } = renderForm({
draftMode: true,
initialValues: withCoords(),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(onSuccess).toHaveBeenCalled())
expect(onSuccess.mock.calls[0][0]).toBeUndefined()
const saved = JSON.parse(secureSnapshot()[PENDING_ADDRESS_KEY])
expect(saved).toMatchObject({
regionId: 1,
name: 'Alice',
phone: '9876543210',
addressLine1: '12 Main Road',
city: 'Mahabubnagar',
state: 'Telangana',
latitude: 17,
longitude: 78,
})
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(0)
})
it('ADDRF-30: a rejected create shows the submit error and clears the loading state', async () => {
denyLocation()
spyResolveRegion()
setProcedure('user.address.createAddress', { mode: 'error', error: new Error('Save failed') })
const { getByTestId, getByText, queryByText, onResolvedRegion } = renderForm({
initialValues: withCoords(),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
fireEvent.press(getByTestId('address-submit'))
await waitFor(() => expect(getByText('Save failed')).toBeTruthy())
expect(queryByText('Adding address...')).toBeNull()
})
it('ADDRF-31: a successful create calls onSuccess after 350ms', async () => {
denyLocation()
spyResolveRegion()
const { getByTestId, onSuccess, onResolvedRegion } = renderForm({
initialValues: withCoords(),
})
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
jest.useFakeTimers()
fireEvent.press(getByTestId('address-submit'))
await act(async () => {
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
expect(onSuccess).not.toHaveBeenCalled()
await act(async () => {
jest.advanceTimersByTime(349)
})
expect(onSuccess).not.toHaveBeenCalled()
await act(async () => {
jest.advanceTimersByTime(1)
})
expect(onSuccess).toHaveBeenCalledWith(A1.id)
})
it('ADDRF-32: a pending submit shows "Adding..."/"Updating..." and disables submit', async () => {
denyLocation()
spyResolveRegion()
setProcedure('user.address.createAddress', { mode: 'pending' })
const add = renderForm({ initialValues: withCoords() })
await waitFor(() => expect(add.onResolvedRegion).toHaveBeenCalled())
fireEvent.press(add.getByTestId('address-submit'))
await waitFor(() => expect(add.getByText('Adding...')).toBeTruthy())
expect(add.getByText('Adding address...')).toBeTruthy()
expect(add.getByTestId('address-submit').props.accessibilityState.disabled).toBe(true)
add.unmount()
setProcedure('user.address.updateAddress', { mode: 'pending' })
const edit = renderForm({ isEdit: true, initialValues: { id: 42, ...withCoords() } })
await waitFor(() => expect(edit.onResolvedRegion).toHaveBeenCalled())
fireEvent.press(edit.getByTestId('address-submit'))
await waitFor(() => expect(edit.getByText('Updating...')).toBeTruthy())
expect(edit.getByText('Updating address...')).toBeTruthy()
})
it('ADDRF-33: the map shows "Loading map..." and the step renders its error banner', async () => {
denyLocation()
const screen = renderForm()
openMapViaChooser(screen as any)
expect(screen.getByText('Loading map...')).toBeTruthy()
// AddressForm never passes an `error` to the step, so assert the banner on
// the step directly with a rejected pick.
const onSelect = jest.fn()
const onCancel = jest.fn()
const step = renderWithProviders(
<LocationMapStep onSelect={onSelect} onCancel={onCancel} error="Pick a point inside the town" />,
{ auth: false }
)
expect(step.getByText('Loading map...')).toBeTruthy()
expect(step.getByText('Pick a point inside the town')).toBeTruthy()
})
it('ADDRF-34: a valid map message fires onSelect with the picked coordinates', async () => {
denyLocation()
const resolve = spyResolveRegion()
const { getByTestId, onResolvedRegion } = renderForm({ initialValues: withCoords() })
await waitFor(() => expect(onResolvedRegion).toHaveBeenCalled())
resolve.mockClear()
fireEvent.press(getByTestId('address-choose-location'))
fireEvent.press(getByTestId('address-map-region-1'))
sendMapMessage(
{ getByTestId } as any,
JSON.stringify({ type: 'location-selected', latitude: 9.9, longitude: 8.8 })
)
await waitFor(() => expect(resolve).toHaveBeenCalledWith({ lat: 9.9, lng: 8.8 }))
})
it('ADDRF-35: invalid map messages are ignored', () => {
denyLocation()
const resolve = spyResolveRegion()
const { getByTestId, queryByText } = renderForm()
openMapViaChooser({ getByTestId } as any)
sendMapMessage({ getByTestId } as any, 'not-json')
sendMapMessage({ getByTestId } as any, JSON.stringify({ type: 'something-else' }))
sendMapMessage({ getByTestId } as any, JSON.stringify({ type: 'location-selected', latitude: 'x' }))
expect(resolve).not.toHaveBeenCalled()
expect(getByTestId('webview')).toBeTruthy()
expect(queryByText('Location Attached from Map')).toBeNull()
})
it('ADDRF-36: the map URL carries lat/lng query params when a centre is known', () => {
denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm()
openMapViaCity({ getByTestId } as any)
const uri = getByTestId('webview').props.source.uri
expect(uri).toContain('?lat=11')
expect(uri).toContain('&lng=22')
})
it('ADDRF-37: the map URL is the bare base URL when no centre is known', () => {
denyLocation()
const { getByTestId } = renderForm()
openMapViaCity({ getByTestId } as any)
expect(getByTestId('webview').props.source.uri).toBe(MAP_BASE)
})
})

View file

@ -0,0 +1,414 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — CheckoutAddressSelector / Display (CAS-01..22).
*
* The selector sorts the saved addresses (selected → default → id) on a
* horizontal carousel, confirms cross-region switches and can attach the device
* location; the display is a read-only card for the checkout page.
*/
import * as React from 'react'
import { Alert, StyleSheet } from 'react-native'
import { act, fireEvent, within } from '@testing-library/react-native'
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'
import AddressForm from '@/src/components/AddressForm'
import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastMutationInput,
procedureMutationCalls,
procedureQueryCalls,
} from '../mocks/trpc-client'
import { __setAuthState } from '../mocks/auth-context'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, REGION_2 } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
// `AddressForm` imports the client relatively (`../trpc-client`) which the
// moduleNameMapper does not rewrite; point that resolved path at the shared mock.
jest.mock('../../src/trpc-client.ts', () => require('../mocks/trpc-client'))
jest.mock('@/src/hooks/useRegion', () => ({
useRegion: () => (globalThis as any).__regionHook,
}))
const ser = (address: any) => ({
...address,
addressLine1: address.line1,
addressLine2: address.line2,
phone: address.mobile,
})
const S1 = ser(A1) // Home, region 1, default
const S2 = ser(A2) // Work, region 2
const S3 = ser(A3) // NoRegion
function setRegionHook(overrides: Record<string, any> = {}) {
const state: any = {
region: null,
regionId: null,
boundId: null,
bound: null,
regionGeneration: 0,
hydrated: true,
coords: null,
locationStatus: 'idle',
isResolvingRegion: false,
setRegion: jest.fn(),
clearRegion: jest.fn(),
refreshLocation: jest.fn(),
...overrides,
}
;(globalThis as any).__regionHook = state
return state
}
function signIn() {
__setAuthState({ isAuthenticated: true, isLoading: false })
}
function setAddresses(addresses: any[]) {
setProcedure('user.address.getUserAddresses', { data: { data: addresses } })
}
const dotColor = (node: any) => StyleSheet.flatten(node.props.style).backgroundColor
describe('CheckoutAddressSelector / Display (CAS)', () => {
beforeEach(() => {
resetAllMocks()
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
})
it('CAS-01: the selected address is sorted first', async () => {
signIn()
setAddresses([S1, S2, S3])
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={12} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
expect(within(getByTestId('address-option-0')).getByText('Work')).toBeTruthy()
})
it('CAS-02: the default address is sorted after the selected one', async () => {
signIn()
setAddresses([S1, S2, S3])
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={13} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
const optionOne = getByTestId('address-option-1')
expect(within(optionOne).getByText('Home')).toBeTruthy()
})
it('CAS-03: the remaining addresses keep a stable ascending id order', async () => {
signIn()
setAddresses([
{ ...S3, isDefault: false },
{ ...S1, isDefault: false },
{ ...S2, isDefault: false },
])
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy()
expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy()
expect(within(getByTestId('address-option-2')).getByText('NoRegion')).toBeTruthy()
})
it('CAS-04: no selection auto-selects a default in the current region', async () => {
signIn()
setAddresses([S1, S2])
const onAddressSelect = jest.fn()
renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
expect(onAddressSelect).toHaveBeenCalledWith(11)
})
it('CAS-05: a default in another region is never auto-selected', async () => {
signIn()
setAddresses([S2, S3])
const onAddressSelect = jest.fn()
renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
expect(onAddressSelect).not.toHaveBeenCalled()
})
it('CAS-06: a default without a region is auto-selected', async () => {
signIn()
setAddresses([{ ...S1, regionId: null }])
const onAddressSelect = jest.fn()
renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
expect(onAddressSelect).toHaveBeenCalledWith(11)
})
it('CAS-07: tapping an address in another region opens the confirm dialog', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn()
setAddresses([S1, S2])
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
fireEvent.press(getByTestId('address-option-1'))
expect(alertSpy).toHaveBeenCalled()
expect(alertSpy.mock.calls[0][0]).toBe('Switch region?')
alertSpy.mockRestore()
})
it('CAS-08: cancelling the region switch changes nothing', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn()
useRegionStore.getState().setRegion(REGION_1, 7)
setAddresses([S1, S2])
const onAddressSelect = jest.fn()
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
fireEvent.press(getByTestId('address-option-1'))
const buttons = alertSpy.mock.calls[0][2] as any[]
const cancel = buttons.find((button) => button.text === 'Cancel')
// The cancel entry is inert: dismissing the dialog simply leaves the state.
expect(cancel.onPress).toBeUndefined()
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(onAddressSelect).not.toHaveBeenCalled()
alertSpy.mockRestore()
})
it('CAS-09: confirming the switch switches the region and replaces with home', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn()
useRegionStore.getState().setRegion(REGION_1, 7)
setAddresses([S1, S2])
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
fireEvent.press(getByTestId('address-option-1'))
const buttons = alertSpy.mock.calls[0][2] as any[]
const confirm = buttons.find((button) => button.text === 'Switch & clear cart')
await act(async () => {
await confirm.onPress()
})
expect(useRegionStore.getState().selectedRegionId).toBe(2)
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore()
})
it('CAS-10: an address in a missing region shows "Unavailable region"', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn()
setAddresses([S1, { ...S2, id: 31, regionId: 99 }])
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
fireEvent.press(getByTestId('address-option-1'))
expect(alertSpy).toHaveBeenCalledWith(
'Unavailable region',
'This address belongs to a region that is not currently available.'
)
alertSpy.mockRestore()
})
it('CAS-11: tapping a same-region address selects it and resets the scroll', async () => {
signIn()
setAddresses([S1, S2])
const onAddressSelect = jest.fn()
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
fireEvent.scroll(getByTestId('address-scroll'), {
nativeEvent: {
contentOffset: { x: 300, y: 0 },
contentSize: { width: 900, height: 100 },
layoutMeasurement: { width: 300, height: 100 },
},
})
const activeColor = dotColor(getByTestId('address-dot-1'))
expect(dotColor(getByTestId('address-dot-0'))).not.toBe(activeColor)
fireEvent.press(getByTestId('address-option-0'))
expect(onAddressSelect).toHaveBeenCalledWith(11)
expect(dotColor(getByTestId('address-dot-0'))).toBe(activeColor)
})
it('CAS-12: one pagination dot per address reflects the scroll index', async () => {
signIn()
setAddresses([S1, S2, S3])
const { getAllByTestId, getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
expect(getAllByTestId(/address-dot-/)).toHaveLength(3)
fireEvent.scroll(getByTestId('address-scroll'), {
nativeEvent: {
contentOffset: { x: 600, y: 0 },
contentSize: { width: 900, height: 100 },
layoutMeasurement: { width: 300, height: 100 },
},
})
expect(dotColor(getByTestId('address-dot-2'))).not.toBe(
dotColor(getByTestId('address-dot-0'))
)
})
it('CAS-13: with no addresses the empty card offers adding one', async () => {
signIn()
setAddresses([])
const { getByText, getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
expect(getByText('No addresses found')).toBeTruthy()
expect(getByTestId('add-address-empty')).toBeTruthy()
})
it('CAS-14: attach location updates the address with the device coordinates', async () => {
signIn()
setAddresses([{ ...S1, latitude: null, longitude: null }])
configureLocation({ permission: 'granted' })
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
expect(getByTestId('attach-location')).toBeTruthy()
fireEvent.press(getByTestId('attach-location'))
await flush(2)
expect(lastMutationInput('user.address.updateAddress')).toMatchObject({
id: 11,
latitude: 17.00012,
longitude: 78.00034,
})
})
it('CAS-15: a denied permission alerts and does not update the address', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn()
setAddresses([{ ...S1, latitude: null, longitude: null }])
configureLocation({ permission: 'denied' })
const { getByTestId } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
fireEvent.press(getByTestId('attach-location'))
await flush(2)
expect(alertSpy).toHaveBeenCalledWith(
'Permission Denied',
'Location permission is required to attach your current location'
)
expect(procedureMutationCalls('user.address.updateAddress')).toHaveLength(0)
alertSpy.mockRestore()
})
it('CAS-16: a location error alerts and clears the loading state', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
signIn()
setAddresses([{ ...S1, latitude: null, longitude: null }])
configureLocation({ permission: 'granted', throwOnPosition: true })
const { getByTestId, getByText } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
{ auth: false }
)
await flush(2)
fireEvent.press(getByTestId('attach-location'))
await flush(2)
expect(alertSpy).toHaveBeenCalledWith(
'Error',
'Unable to fetch location. Please check your GPS settings.'
)
expect(getByText('+ Attach Current Location')).toBeTruthy()
alertSpy.mockRestore()
})
it('CAS-17: a successful add auto-selects the new address and invalidates queries', async () => {
signIn()
setAddresses([S1])
const onAddressSelect = jest.fn()
const { getByTestId, UNSAFE_getByType, queryClient } = renderWithProviders(
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
{ auth: false }
)
await flush(2)
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
fireEvent.press(getByTestId('add-new-address'))
await flush(1)
await act(async () => {
UNSAFE_getByType(AddressForm).props.onSuccess(55)
})
await flush(1)
expect(onAddressSelect).toHaveBeenCalledWith(55)
expect(invalidateSpy).toHaveBeenCalled()
})
it('CAS-18: the display shows the selected address', async () => {
signIn()
setAddresses([S1, S2, S3])
useAddressStore.getState().setSelectedAddressId(12)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('Work')).toBeTruthy()
})
it('CAS-19: the display falls back to the default address', async () => {
signIn()
setAddresses([S1, S2, S3])
useAddressStore.getState().setSelectedAddressId(null)
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('Home')).toBeTruthy()
})
it('CAS-20: the display shows an empty state with no address', async () => {
signIn()
setAddresses([])
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('No address selected')).toBeTruthy()
})
it('CAS-21: the display shows a loading state while addresses load', () => {
signIn()
setProcedure('user.address.getUserAddresses', { mode: 'pending' })
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
expect(getByText('Loading address...')).toBeTruthy()
})
it('CAS-22: the display is query-disabled when signed out and does not crash', async () => {
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2)
expect(getByText('No address selected')).toBeTruthy()
expect(procedureQueryCalls('user.address.getUserAddresses')).toHaveLength(0)
})
})

View file

@ -0,0 +1,239 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — "ComplaintForm" (`tests/components/complaint-form.test.tsx`).
*
* Uploads run through `useUploadToObjectStorage`, so an image path needs:
* - `common.generateUploadUrls` (tRPC mock) to hand back a presigned URL
* - `expo-image-picker` to return an asset so `ImageUploaderNeo` calls `onImageAdd`
* - a `global.fetch` spy (blob read + PUT)
* The raise call itself is asserted through `lastProcedureInput('user.complaint.raise')`.
*/
import * as React from 'react'
import { Alert } from 'react-native'
import * as ImagePicker from 'expo-image-picker'
import { fireEvent, waitFor } from '@testing-library/react-native'
import { resetAllMocks } from '../helpers/reset'
import { renderWithProviders, flush } from '../helpers/test-utils'
import {
expectNoProcedureCall,
lastProcedureInput,
procedureCallCount,
setProcedure,
} from '../mocks/trpc-client'
import ComplaintForm from '@/components/ComplaintForm'
const IMAGE_URL = 'https://cdn.test/photo.jpg'
const PRESIGNED_URL = 'https://upload.test/complaint/abc.jpg'
const UPLOADED_KEY = 'abc.jpg'
function installFetch() {
const fetchSpy = jest.fn(async () => ({
ok: true,
status: 200,
blob: async () => ({}),
}))
;(global as any).fetch = fetchSpy
return fetchSpy
}
function queueImageAsset(uri = IMAGE_URL, mimeType = 'image/jpeg') {
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValueOnce({
canceled: false,
assets: [{ uri, mimeType, fileName: 'photo.jpg' }],
})
}
async function addImage(getByTestId: (id: string) => any) {
queueImageAsset()
fireEvent.press(getByTestId('complaint-images'))
await waitFor(() => expect(getByTestId('complaint-images-remove')).toBeTruthy())
}
function renderForm(overrides: { open?: boolean; onClose?: jest.Mock; orderId?: number } = {}) {
const onClose = overrides.onClose ?? jest.fn()
const result = renderWithProviders(
<ComplaintForm
open={overrides.open ?? true}
onClose={onClose}
orderId={overrides.orderId ?? 42}
/>,
{ auth: false }
)
return { ...result, onClose }
}
describe('ComplaintForm', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
it('CF-01: renders nothing while closed', () => {
const { toJSON, queryByTestId } = renderForm({ open: false })
expect(toJSON()).toBeNull()
expect(queryByTestId('complaint-body')).toBeNull()
expect(queryByTestId('complaint-submit')).toBeNull()
})
it('CF-02: a blank body alerts and raises nothing', async () => {
const { getByTestId } = renderForm()
fireEvent.press(getByTestId('complaint-submit'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'Please enter complaint details')
expectNoProcedureCall('user.complaint.raise')
fireEvent.changeText(getByTestId('complaint-body'), ' ')
fireEvent.press(getByTestId('complaint-submit'))
expect(procedureCallCount('user.complaint.raise')).toBe(0)
expectNoProcedureCall('common.generateUploadUrls')
})
it('CF-03: submits a body-only complaint, then resets and closes', async () => {
const { getByTestId, onClose } = renderForm({ orderId: 42 })
fireEvent.changeText(getByTestId('complaint-body'), 'Cold items were delivered')
fireEvent.press(getByTestId('complaint-submit'))
await waitFor(() =>
expect(lastProcedureInput('user.complaint.raise')).toEqual({
orderId: '42',
complaintBody: 'Cold items were delivered',
imageUrls: [],
})
)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint raised successfully')
expect(getByTestId('complaint-body').props.value).toBe('')
expect(onClose).toHaveBeenCalledTimes(1)
expectNoProcedureCall('common.generateUploadUrls')
})
it('CF-04: uploads attached images and passes the returned keys', async () => {
const fetchSpy = installFetch()
setProcedure('common.generateUploadUrls', { data: { uploadUrls: [PRESIGNED_URL] } })
const { getByTestId, onClose } = renderForm({ orderId: 7 })
await addImage(getByTestId)
fireEvent.changeText(getByTestId('complaint-body'), 'Wrong item delivered')
fireEvent.press(getByTestId('complaint-submit'))
await waitFor(() =>
expect(lastProcedureInput('user.complaint.raise')).toEqual({
orderId: '7',
complaintBody: 'Wrong item delivered',
imageUrls: [UPLOADED_KEY],
})
)
// The upload URL request carries the picked mime type and complaint context.
expect(lastProcedureInput('common.generateUploadUrls')).toEqual({
contextString: 'complaint',
mimeTypes: ['image/jpeg'],
})
// The blob is read from the picked uri and PUT to the presigned url.
expect(fetchSpy).toHaveBeenCalledWith(IMAGE_URL)
expect(fetchSpy).toHaveBeenCalledWith(
PRESIGNED_URL,
expect.objectContaining({ method: 'PUT', headers: { 'Content-Type': 'image/jpeg' } })
)
expect(onClose).toHaveBeenCalledTimes(1)
})
it('CF-05: alerts and does not raise when the upload fails', async () => {
installFetch()
setProcedure('common.generateUploadUrls', {
mode: 'error',
error: new Error('upload url boom'),
})
const { getByTestId, onClose } = renderForm()
await addImage(getByTestId)
fireEvent.changeText(getByTestId('complaint-body'), 'Damaged meat')
fireEvent.press(getByTestId('complaint-submit'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'upload url boom'))
expectNoProcedureCall('user.complaint.raise')
expect(onClose).not.toHaveBeenCalled()
})
it('CF-06: alerts and keeps the form open when raise fails', async () => {
setProcedure('user.complaint.raise', { mode: 'error', error: new Error('raise boom') })
const { getByTestId, onClose } = renderForm()
fireEvent.changeText(getByTestId('complaint-body'), 'Still cold')
fireEvent.press(getByTestId('complaint-submit'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'raise boom'))
expect(getByTestId('complaint-body').props.value).toBe('Still cold')
expect(onClose).not.toHaveBeenCalled()
})
it('CF-07: disables the button and shows a spinner while pending/uploading', async () => {
setProcedure('user.complaint.raise', { mode: 'pending' })
const pendingRaise = renderForm()
fireEvent.changeText(pendingRaise.getByTestId('complaint-body'), 'Pending raise')
fireEvent.press(pendingRaise.getByTestId('complaint-submit'))
await waitFor(() => expect(pendingRaise.getByTestId('complaint-submit-spinner')).toBeTruthy())
expect(pendingRaise.queryByText('Submit Complaint')).toBeNull()
expect(
pendingRaise.getByTestId('complaint-submit').props.accessibilityState?.disabled
).toBe(true)
pendingRaise.unmount()
// Uploading state (presigned URL request never settles).
installFetch()
setProcedure('user.complaint.raise', { data: { success: true } })
setProcedure('common.generateUploadUrls', { mode: 'pending' })
const uploading = renderForm()
await addImage(uploading.getByTestId)
fireEvent.changeText(uploading.getByTestId('complaint-body'), 'Uploading')
fireEvent.press(uploading.getByTestId('complaint-submit'))
await waitFor(() => expect(uploading.getByTestId('complaint-submit-spinner')).toBeTruthy())
expect(uploading.queryByText('Submit Complaint')).toBeNull()
expect(
uploading.getByTestId('complaint-submit').props.accessibilityState?.disabled
).toBe(true)
})
it('CF-08: removes an attached image from the list', async () => {
const { getByTestId, queryByTestId } = renderForm()
await addImage(getByTestId)
expect(queryByTestId('complaint-images-remove')).toBeTruthy()
fireEvent.press(getByTestId('complaint-images-remove'))
await flush()
expect(queryByTestId('complaint-images-remove')).toBeNull()
// A subsequent raise therefore carries no image keys.
fireEvent.changeText(getByTestId('complaint-body'), 'No images now')
fireEvent.press(getByTestId('complaint-submit'))
await waitFor(() =>
expect(lastProcedureInput('user.complaint.raise')).toEqual({
orderId: '42',
complaintBody: 'No images now',
imageUrls: [],
})
)
})
it('CF-09: closes without touching the API', () => {
const { getByTestId, onClose } = renderForm()
fireEvent.press(getByTestId('complaint-close'))
expect(onClose).toHaveBeenCalledTimes(1)
expectNoProcedureCall('user.complaint.raise')
expectNoProcedureCall('common.generateUploadUrls')
})
})

View file

@ -0,0 +1,153 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — `CouponBreakdownDialog` (CBD-01..07).
*
* The dialog renders the per-line split of a product-targeted coupon
* (`computeCouponLineBreakdowns`). Rows come from the central product store for
* names/images and from the `cartLines` prop for the qty x price line.
*/
import * as React from 'react'
import { fireEvent } from '@testing-library/react-native'
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog'
import { renderWithProviders, seedCentralStores } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import type { CartLine, CouponLineBreakdown } from '@packages/shared'
/** The Unicode minus sign the component renders before the rupee amount. */
const MINUS = '\u2212'
const line = (skuId: number, quantity: number, unitPrice: number): CartLine => ({
skuId,
quantity,
unitPrice,
})
const breakdown = (
couponId: number,
discount: number,
lines: { skuId: number; discount: number }[]
): CouponLineBreakdown => ({ couponId, discount, lines })
interface SetupProps {
coupon?: { id: number; code: string } | null
breakdown?: CouponLineBreakdown | null
cartLines?: CartLine[]
onClose?: jest.Mock
}
function setup(props: SetupProps = {}) {
seedCentralStores()
const onClose = props.onClose ?? jest.fn()
const result = renderWithProviders(
<CouponBreakdownDialog
coupon={props.coupon === undefined ? { id: 21, code: 'SAVE10' } : props.coupon}
breakdown={
props.breakdown === undefined
? breakdown(21, 40, [{ skuId: 2, discount: 40 }])
: props.breakdown
}
cartLines={props.cartLines ?? [line(2, 2, 215)]}
onClose={onClose}
/>,
{ auth: false }
)
return { ...result, onClose }
}
describe('CouponBreakdownDialog', () => {
beforeEach(() => resetAllMocks())
it('CBD-01: keeps the dialog closed when the coupon or the breakdown is null', () => {
seedCentralStores()
const first = renderWithProviders(
<CouponBreakdownDialog
coupon={null}
breakdown={breakdown(21, 40, [{ skuId: 2, discount: 40 }])}
cartLines={[line(2, 2, 215)]}
onClose={jest.fn()}
/>,
{ auth: false }
)
expect(first.queryByTestId('coupon-breakdown-dialog')).toBeNull()
first.unmount()
const second = renderWithProviders(
<CouponBreakdownDialog
coupon={{ id: 21, code: 'SAVE10' }}
breakdown={null}
cartLines={[line(2, 2, 215)]}
onClose={jest.fn()}
/>,
{ auth: false }
)
expect(second.queryByTestId('coupon-breakdown-dialog')).toBeNull()
})
it('CBD-02: shows the empty-split message when every row discount is zero', () => {
const { getByTestId, queryByText, queryByTestId } = setup({
breakdown: breakdown(21, 0, [
{ skuId: 2, discount: 0 },
{ skuId: 5, discount: 0 },
]),
})
expect(getByTestId('coupon-breakdown-dialog')).toBeTruthy()
expect(queryByText('No per-product split to show for this order.')).toBeTruthy()
expect(queryByTestId('coupon-breakdown-row-2')).toBeNull()
})
it('CBD-03: lists only discount-bearing rows, largest first', () => {
const { getAllByTestId } = setup({
breakdown: breakdown(21, 70, [
{ skuId: 2, discount: 10 },
{ skuId: 5, discount: 40 },
{ skuId: 8, discount: 20 },
]),
})
const ids = getAllByTestId(/^coupon-breakdown-row-/).map((node) => node.props.testID)
expect(ids).toEqual([
'coupon-breakdown-row-5',
'coupon-breakdown-row-8',
'coupon-breakdown-row-2',
])
})
it('CBD-04: falls back to "Product #id" for an unknown SKU', () => {
const { getByText, getByTestId } = setup({
breakdown: breakdown(21, 40, [{ skuId: 999, discount: 40 }]),
cartLines: [],
})
expect(getByTestId('coupon-breakdown-row-999')).toBeTruthy()
expect(getByText('Product #999')).toBeTruthy()
})
it('CBD-05: renders the row without the qty x price line when the cart line is missing', () => {
const { getByTestId, getByText, queryByText } = setup({
breakdown: breakdown(21, 40, [{ skuId: 2, discount: 40 }]),
cartLines: [],
})
expect(getByTestId('coupon-breakdown-row-2')).toBeTruthy()
expect(getByText('Chicken Breast')).toBeTruthy()
expect(queryByText(new RegExp(`\\u00d7 \\u20b9`))).toBeNull()
})
it('CBD-06: truncates the coupon total to whole rupees', () => {
const { getByText } = setup({
breakdown: breakdown(21, 43.9, [{ skuId: 2, discount: 43.9 }]),
})
expect(getByText(`${MINUS}\u20b943`)).toBeTruthy()
})
it('CBD-07: the close button calls onClose', () => {
const onClose = jest.fn()
const { getByTestId } = setup({ onClose })
fireEvent.press(getByTestId('coupon-breakdown-close'))
expect(onClose).toHaveBeenCalledTimes(1)
})
})

View file

@ -0,0 +1,100 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Section 24 — FloatingCartBar (FCB-01..05).
*
* The bar reads the local cart through `useGetCart`, so lines come from the
* storage mock's `cart_items` / `flash_cart_items` keys and the central stores
* supply the product names/prices (`seedBoot`).
*/
import * as React from 'react'
import { StyleSheet, View } from 'react-native'
import { QueryClient } from '@tanstack/react-query'
import { fireEvent, waitFor } from '@testing-library/react-native'
import FloatingCartBar from '@/components/floating-cart-bar'
import { renderWithProviders, seedBoot, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { CART_REG, CART_FLASH } from '../fixtures'
/**
* Same defaults as the shared harness client, except mutations use `gcTime: 0`:
* React Query otherwise schedules a 5-minute GC timeout on unmount, which keeps
* the jest process alive after the run has finished.
*/
function createCartQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: Infinity,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false, gcTime: 0 },
},
})
}
async function renderBar(props: React.ComponentProps<typeof FloatingCartBar> = {}) {
seedBoot()
const utils = renderWithProviders(<FloatingCartBar {...props} />, {
auth: false,
queryClient: createCartQueryClient(),
})
await flush(2)
return utils
}
describe('FloatingCartBar', () => {
beforeEach(() => resetAllMocks())
it('FCB-01: a controlled isExpanded prop makes the parent own the sheet', async () => {
__set('cart_items', CART_REG)
const { getByText, queryByTestId } = await renderBar({ isExpanded: true })
expect(getByText('Your Cart')).toBeTruthy()
// The collapsed bar is not rendered while expanded.
expect(queryByTestId('go-to-cart')).toBeNull()
})
it('FCB-02: tapping the collapsed bar calls the controlled setIsExpanded with true', async () => {
__set('cart_items', CART_REG)
const setIsExpanded = jest.fn()
const { getByText, queryByText } = await renderBar({ isExpanded: false, setIsExpanded })
expect(queryByText('Your Cart')).toBeNull()
fireEvent.press(getByText(/1 Item/))
expect(setIsExpanded).toHaveBeenCalledWith(true)
})
it('FCB-03: the flash cart renders with the pink theme', async () => {
__set('flash_cart_items', CART_FLASH)
const { UNSAFE_getAllByType } = await renderBar({ isFlashDelivery: true })
const bar = UNSAFE_getAllByType(View).find(
(node) => StyleSheet.flatten(node.props.style as any)?.backgroundColor === '#f81260'
)
expect(bar).toBeTruthy()
expect(StyleSheet.flatten(bar!.props.style as any).borderColor).toBe('#e11d48')
})
it('FCB-04: a quantity mutation refetches the cart and rebuilds the local quantities', async () => {
__set('cart_items', CART_REG)
const { getByTestId } = await renderBar({ isExpanded: true })
fireEvent.press(getByTestId('mini-quantifier-increment'))
await waitFor(() =>
expect(JSON.parse(__snapshot()['cart_items'])[0].quantity).toBe(3)
)
expect(getByTestId('mini-quantifier-value')).toHaveTextContent('3')
})
it('FCB-05: no cart data still renders the empty bar without crashing', async () => {
const { getByText, getByTestId } = await renderBar()
expect(getByText('No Items In Cart')).toBeTruthy()
expect(getByTestId('go-to-cart')).toBeTruthy()
})
})

View file

@ -0,0 +1,893 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — Location components (LOC-01..54).
*
* Covers the region gate (`LocationTestWrapper`), the address chooser
* (`LocationFallbackFlow`), the bar, the map step, the location attacher, the
* cart address gate and the quick-delivery header.
*
* `useRegion` is replaced with a controllable stub so the `LocationTestWrapper`
* contract (region known / loading / resolving / no region / stale region) can be
* exercised deterministically without the hook's module-level startup state.
* Everything below the gate (stores, `confirmRegionSwitch`, cart helpers) runs for
* real.
*/
import * as React from 'react'
import { Linking, Platform, Text } from 'react-native'
import { act, fireEvent, within } from '@testing-library/react-native'
import dayjs from 'dayjs'
import LocationTestWrapper from '@/components/LocationTestWrapper'
import CartAddressGate from '@/components/CartAddressGate'
import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'
import LocationBar from '@/src/components/LocationBar'
import LocationAttacher from '@/src/components/LocationAttacher'
import LocationMapStep from '@/src/components/location/LocationMapStep'
import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow'
import AddressForm from '@/src/components/AddressForm'
import constants from '@/src/constants'
import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useLocationStore } from '@/src/store/locationStore'
import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastMutationInput,
procedureInvalidations,
procedureQueryCalls,
} from '../mocks/trpc-client'
import { __setAuthState } from '../mocks/auth-context'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, BOUND_1, SLOTS, CONSTS } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
// `AddressForm` imports the client relatively (`../trpc-client`) which the
// moduleNameMapper does not rewrite; point that resolved path at the shared mock.
jest.mock('../../src/trpc-client.ts', () => require('../mocks/trpc-client'))
jest.mock('@/src/hooks/useRegion', () => ({
useRegion: () => (globalThis as any).__regionHook,
}))
/** Serialize an address fixture into the API shape the chooser/bar consume. */
const ser = (address: any) => ({
...address,
addressLine1: address.line1,
addressLine2: address.line2,
phone: address.mobile,
})
const S1 = ser(A1) // Home, region 1, default, bound 7
const S2 = ser(A2) // Work, region 2, bound 8
const S3 = ser(A3) // NoRegion, region null
function setRegionHook(overrides: Record<string, any> = {}) {
const state: any = {
region: null,
regionId: null,
boundId: null,
bound: null,
regionGeneration: 0,
hydrated: true,
coords: null,
locationStatus: 'idle',
isResolvingRegion: false,
setRegion: jest.fn(),
clearRegion: jest.fn(),
refreshLocation: jest.fn(),
...overrides,
}
;(globalThis as any).__regionHook = state
return state
}
function signIn() {
__setAuthState({ isAuthenticated: true, isLoading: false })
}
function setAddresses(addresses: any[]) {
setProcedure('user.address.getUserAddresses', { data: { data: addresses } })
}
async function withPlatform(os: 'ios' | 'android', fn: () => Promise<void>) {
const original = Platform.OS
Object.defineProperty(Platform, 'OS', { value: os, configurable: true })
try {
await fn()
} finally {
Object.defineProperty(Platform, 'OS', { value: original, configurable: true })
}
}
/** Mirrors the component's slot label formatter. */
function formatTimeRange(deliveryTime: string | Date) {
const time = dayjs(deliveryTime)
const endTime = time.add(1, 'hour')
const startPeriod = time.format('A')
const endPeriod = endTime.format('A')
const timeRange =
startPeriod === endPeriod
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
return `${time.format('ddd, DD MMM ')}${timeRange}`
}
/** Build a quick-delivery tree with a controlled, unsorted slot document. */
function setupQuickDelivery() {
seedJsonCache()
const slots = [...SLOTS].reverse().map((slot) => ({ ...slot }))
setProcedure('common.essentialConsts', { data: { ...CONSTS } })
setProcedure('user.address.getUserAddresses', { data: { data: [S1, S2] } })
return slots
}
describe('Location components (LOC)', () => {
beforeEach(() => {
resetAllMocks()
setRegionHook()
})
it('LOC-01: LocationTestWrapper renders children when a region is known', () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
const { getByText, queryByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByText('gate children')).toBeTruthy()
expect(queryByTestId('location-loading')).toBeNull()
})
it('LOC-02: LocationTestWrapper shows a spinner while the store is not hydrated', () => {
setRegionHook({ hydrated: false })
const { getByTestId, queryByText } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByTestId('location-loading')).toBeTruthy()
expect(queryByText('Finding your region...')).toBeNull()
})
it('LOC-03: LocationTestWrapper shows "Finding your region..." while resolving', () => {
setRegionHook({ isResolvingRegion: true })
const { getByText, getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByTestId('location-loading')).toBeTruthy()
expect(getByText('Finding your region...')).toBeTruthy()
})
it('LOC-04: LocationTestWrapper falls back to the address flow with no region', () => {
const { getByText, queryByText } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(getByText('Delivery Address')).toBeTruthy()
expect(queryByText('gate children')).toBeNull()
})
it('LOC-05: denied notice is shown with a settings button', () => {
setRegionHook({ locationStatus: 'denied' })
const { getByText, getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(
getByText(
'Location access is not granted. Allow location access for accurate delivery, or add a delivery address below.'
)
).toBeTruthy()
expect(getByTestId('open-location-settings')).toBeTruthy()
})
it('LOC-06: services-off notice is shown with a settings button', () => {
setRegionHook({ locationStatus: 'services-off' })
const { getByText, getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(
getByText('Your device location is turned off. Turn it on, or add a delivery address below.')
).toBeTruthy()
expect(getByTestId('open-location-settings')).toBeTruthy()
})
it('LOC-07: unavailable notice is shown without a settings button', () => {
setRegionHook({ locationStatus: 'unavailable' })
const { getByText, queryByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
expect(
getByText('We could not get your location. Please try again, or add a delivery address below.')
).toBeTruthy()
expect(queryByTestId('open-location-settings')).toBeNull()
})
it('LOC-08: the settings button sends the Android location-source intent', async () => {
setRegionHook({ locationStatus: 'services-off' })
await withPlatform('android', async () => {
const sendIntent = jest.fn(async () => undefined)
;(Linking as any).sendIntent = sendIntent
const { getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
fireEvent.press(getByTestId('open-location-settings'))
await flush(2)
expect(sendIntent).toHaveBeenCalledWith('android.settings.LOCATION_SOURCE_SETTINGS')
})
})
it('LOC-09: the settings button calls Linking.openSettings on iOS', async () => {
setRegionHook({ locationStatus: 'denied' })
await withPlatform('ios', async () => {
const openSettings = jest.fn(async () => undefined)
;(Linking as any).openSettings = openSettings
const { getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
fireEvent.press(getByTestId('open-location-settings'))
await flush(2)
expect(openSettings).toHaveBeenCalled()
})
})
it('LOC-10: a failing settings intent falls back to Linking.openSettings without crashing', async () => {
setRegionHook({ locationStatus: 'services-off' })
await withPlatform('android', async () => {
;(Linking as any).sendIntent = jest.fn(async () => {
throw new Error('no activity')
})
const openSettings = jest.fn(async () => undefined)
;(Linking as any).openSettings = openSettings
const { getByTestId } = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
fireEvent.press(getByTestId('open-location-settings'))
await flush(2)
expect(openSettings).toHaveBeenCalled()
})
})
it('LOC-11: a stale region absent from listRegions is cleared', async () => {
const region = setRegionHook({ region: REGION_1, regionId: 99, boundId: 7 })
renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await flush(2)
expect(region.clearRegion).toHaveBeenCalled()
})
it('LOC-12: the gate polling calls refreshLocation when the location becomes usable', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'denied' })
const region = setRegionHook()
renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await act(async () => {
await Promise.resolve()
})
configureLocation({ permission: 'granted' })
await act(async () => {
jest.advanceTimersByTime(3000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(region.refreshLocation).toHaveBeenCalled()
jest.useRealTimers()
})
it('LOC-13: a failing probe never triggers refreshLocation', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'denied' })
const region = setRegionHook()
renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await act(async () => {
await Promise.resolve()
})
await act(async () => {
jest.advanceTimersByTime(6000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(region.refreshLocation).not.toHaveBeenCalled()
jest.useRealTimers()
})
it('LOC-14: unmounting the gate clears the polling interval', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'denied' })
const region = setRegionHook()
const view = renderWithProviders(
<LocationTestWrapper>
<Text>gate children</Text>
</LocationTestWrapper>,
{ auth: false }
)
await act(async () => {
await Promise.resolve()
})
view.unmount()
configureLocation({ permission: 'granted' })
await act(async () => {
jest.advanceTimersByTime(3000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(region.refreshLocation).not.toHaveBeenCalled()
jest.useRealTimers()
})
it('LOC-15: a saved address activates its region/bound, selects it and closes', async () => {
signIn()
setAddresses([S1, S2])
const onClose = jest.fn()
const { getByTestId } = renderWithProviders(<LocationFallbackFlow onClose={onClose} />, {
auth: false,
})
await flush(2)
fireEvent.press(getByTestId('location-address-11'))
await flush(3)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useRegionStore.getState().selectedBoundId).toBe(7)
expect(useAddressStore.getState().selectedAddressId).toBe(11)
expect(onClose).toHaveBeenCalled()
})
it('LOC-16: a saved address without a region shows a message', async () => {
signIn()
setAddresses([S3])
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
await flush(2)
fireEvent.press(getByTestId('location-address-13'))
await flush(2)
expect(
getByText('This saved address has no region. Please add a new address instead.')
).toBeTruthy()
})
it('LOC-17: a missing bound is resolved from the address coordinates', async () => {
signIn()
setAddresses([{ ...S1, id: 21, boundId: null, latitude: 17.0001, longitude: 78.0001 }])
setProcedure('common.resolveRegionByLocation', { data: { region: REGION_1, bound: BOUND_1 } })
const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByTestId('location-address-21'))
await flush(3)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useRegionStore.getState().selectedBoundId).toBe(7)
})
it('LOC-18: a failing bound resolve still activates the region', async () => {
signIn()
setAddresses([{ ...S1, id: 21, boundId: null, latitude: 17.0001, longitude: 78.0001 }])
setProcedure('common.resolveRegionByLocation', {
impl: () => {
throw new Error('resolve failed')
},
})
const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByTestId('location-address-21'))
await flush(3)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
})
it('LOC-19: an address in a no-longer-serviceable region shows a message and does not switch', async () => {
signIn()
setAddresses([{ ...S1, id: 31, regionId: 99, boundId: 7 }])
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
await flush(2)
fireEvent.press(getByTestId('location-address-31'))
await flush(3)
expect(getByText('This location is no longer serviceable.')).toBeTruthy()
expect(useRegionStore.getState().selectedRegionId).toBeNull()
})
it('LOC-20: the active address prefers the selection over the default (and is off at startup)', async () => {
signIn()
setAddresses([S1, S2])
useAddressStore.getState().setSelectedAddressId(12)
const first = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
expect(within(first.getByTestId('location-address-12')).getByTestId('location-address-active')).toBeTruthy()
expect(
within(first.getByTestId('location-address-11')).queryByTestId('location-address-active')
).toBeNull()
first.unmount()
useAddressStore.getState().setSelectedAddressId(null)
const second = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
expect(within(second.getByTestId('location-address-11')).getByTestId('location-address-active')).toBeTruthy()
second.unmount()
const startup = renderWithProviders(
<LocationFallbackFlow highlightActiveAddress={false} />,
{ auth: false }
)
await flush(2)
expect(startup.queryByTestId('location-address-active')).toBeNull()
})
it('LOC-21: set default posts the update payload and invalidates the address queries', async () => {
signIn()
setAddresses([S1, S2])
const { getByText } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByText('Set as default'))
await flush(3)
const input = lastMutationInput('user.address.updateAddress')
expect(input).toMatchObject({ id: 12, isDefault: true, name: 'Work' })
expect(procedureInvalidations('user.address.getUserAddresses').length).toBeGreaterThan(0)
expect(procedureInvalidations('user.address.getDefaultAddress').length).toBeGreaterThan(0)
})
it('LOC-22: a failed set default shows the error message', async () => {
signIn()
setAddresses([S1, S2])
setProcedure('user.address.updateAddress', {
mode: 'error',
error: new Error('Could not set default'),
})
const { getByText } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByText('Set as default'))
await flush(3)
expect(getByText('Could not set default')).toBeTruthy()
})
it('LOC-23: signed out shows the login footer and never queries addresses', () => {
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
getByTestId('location-login')
expect(getByText('Login to get existing addresses.')).toBeTruthy()
expect(procedureQueryCalls('user.address.getUserAddresses')).toHaveLength(0)
})
it('LOC-24: login mode renders the login screen inline and the back button returns to the chooser', async () => {
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
fireEvent.press(getByTestId('location-login'))
await flush(2)
expect(getByText('Welcome')).toBeTruthy()
fireEvent.press(getByTestId('location-login-back'))
await flush(2)
expect(getByText('Delivery Address')).toBeTruthy()
})
it('LOC-25: add mode renders the address form and the back button returns to the chooser', async () => {
signIn()
const { getByTestId, getByText } = renderWithProviders(<LocationFallbackFlow />, {
auth: false,
})
fireEvent.press(getByTestId('location-add-address'))
await flush(2)
expect(getByTestId('address-submit')).toBeTruthy()
fireEvent.press(getByTestId('location-add-back'))
await flush(2)
expect(getByText('Delivery Address')).toBeTruthy()
})
it('LOC-26: a successful add activates the resolved region, selects the new id and closes', async () => {
signIn()
const onClose = jest.fn()
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<LocationFallbackFlow onClose={onClose} />,
{ auth: false }
)
fireEvent.press(getByTestId('location-add-address'))
await flush(2)
const form = UNSAFE_getByType(AddressForm)
await act(async () => {
form.props.onResolvedRegion({ regionId: 1, boundId: 7 })
await form.props.onSuccess(42)
})
await flush(2)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useAddressStore.getState().selectedAddressId).toBe(42)
expect(onClose).toHaveBeenCalled()
})
it('LOC-27: a successful add while signed out closes without selecting an id', async () => {
const onClose = jest.fn()
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<LocationFallbackFlow onClose={onClose} />,
{ auth: false }
)
fireEvent.press(getByTestId('location-add-address'))
await flush(2)
const form = UNSAFE_getByType(AddressForm)
await act(async () => {
await form.props.onSuccess()
})
await flush(2)
expect(onClose).toHaveBeenCalled()
expect(useAddressStore.getState().selectedAddressId).toBeNull()
})
it('LOC-28: signed in with no addresses shows the empty copy', async () => {
signIn()
setAddresses([])
const { getByText } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
expect(getByText('No saved addresses yet.')).toBeTruthy()
})
it('LOC-29: while busy an overlay is shown and the address cards are disabled', async () => {
signIn()
setAddresses([S1, S2])
setProcedure('common.listRegions', { impl: () => new Promise(() => {}) })
const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2)
fireEvent.press(getByTestId('location-address-11'))
await flush(1)
expect(getByTestId('location-busy-overlay')).toBeTruthy()
expect(getByTestId('location-address-11')).toBeDisabled()
})
it('LOC-30: LocationBar shows the region and active address and opens the switcher', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setAddresses([S1, S2])
useAddressStore.getState().setSelectedAddressId(11)
const { getByTestId, getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2)
expect(getByText('Mahabubnagar')).toBeTruthy()
expect(getByText('12 Main Road, Near Temple, Mahabubnagar')).toBeTruthy()
fireEvent.press(getByTestId('location-bar'))
await flush(2)
expect(getByText('Delivery Address')).toBeTruthy()
})
it('LOC-31: LocationBar without a region shows "Choose your address"', () => {
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
expect(getByText('Choose your address')).toBeTruthy()
})
it('LOC-32: LocationBar prefers the selected address over the default', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setAddresses([S1, S2])
useAddressStore.getState().setSelectedAddressId(12)
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2)
expect(getByText('45 Office Street, Hyderabad')).toBeTruthy()
})
it('LOC-33: LocationBar renders no address line without a selection or default', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setAddresses([])
const { getByText, queryByText } = renderWithProviders(<LocationBar />, { auth: false })
await flush(2)
expect(getByText('Mahabubnagar')).toBeTruthy()
expect(queryByText('12 Main Road, Near Temple, Mahabubnagar')).toBeNull()
})
it('LOC-34: LocationMapStep builds the URL with optional lat/lng params', () => {
const withCoords = renderWithProviders(
<LocationMapStep lat={17} lng={78} onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(withCoords.getByTestId('webview').props.source.uri).toBe(
`${constants.WEB_UI_BASE_URL}/location-selector?lat=17&lng=78`
)
withCoords.unmount()
const withoutCoords = renderWithProviders(
<LocationMapStep onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(withoutCoords.getByTestId('webview').props.source.uri).toBe(
`${constants.WEB_UI_BASE_URL}/location-selector`
)
})
it('LOC-35: LocationMapStep shows "Loading map..." until the webview loads', () => {
const { getByTestId, getByText, queryByText } = renderWithProviders(
<LocationMapStep onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(getByText('Loading map...')).toBeTruthy()
fireEvent(getByTestId('webview'), 'loadEnd')
expect(queryByText('Loading map...')).toBeNull()
})
it('LOC-36: a valid location-selected message calls onSelect', () => {
const onSelect = jest.fn()
const { getByTestId } = renderWithProviders(
<LocationMapStep onSelect={onSelect} onCancel={jest.fn()} />,
{ auth: false }
)
fireEvent(getByTestId('webview'), 'message', {
nativeEvent: {
data: JSON.stringify({ type: 'location-selected', latitude: 1.5, longitude: 2.5 }),
},
})
expect(onSelect).toHaveBeenCalledWith({ latitude: 1.5, longitude: 2.5 })
})
it('LOC-37: an unrelated webview message is ignored', () => {
const onSelect = jest.fn()
const { getByTestId } = renderWithProviders(
<LocationMapStep onSelect={onSelect} onCancel={jest.fn()} />,
{ auth: false }
)
fireEvent(getByTestId('webview'), 'message', {
nativeEvent: { data: JSON.stringify({ type: 'something-else' }) },
})
expect(onSelect).not.toHaveBeenCalled()
})
it('LOC-38: LocationMapStep renders the error banner', () => {
const { getByText } = renderWithProviders(
<LocationMapStep error="Outside our delivery area" onSelect={jest.fn()} onCancel={jest.fn()} />,
{ auth: false }
)
expect(getByText('Outside our delivery area')).toBeTruthy()
})
it('LOC-39: LocationMapStep Cancel calls onCancel', () => {
const onCancel = jest.fn()
const { getByText } = renderWithProviders(
<LocationMapStep onSelect={jest.fn()} onCancel={onCancel} />,
{ auth: false }
)
fireEvent.press(getByText('Cancel'))
expect(onCancel).toHaveBeenCalled()
})
it('LOC-40: LocationAttacher attaches the granted location and shows the success badge', async () => {
configureLocation({ permission: 'granted' })
const onLocationChange = jest.fn()
const { getByTestId, getByText } = renderWithProviders(
<LocationAttacher onLocationChange={onLocationChange} />,
{ auth: false }
)
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(onLocationChange).toHaveBeenCalledWith({
latitude: 17.00012,
longitude: 78.00034,
})
expect(getByText('✓ Location Attached')).toBeTruthy()
// The 3s timer clears the transient success flag; the attached coords persist.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 3100))
})
expect(getByText('✓ Location Attached')).toBeTruthy()
})
it('LOC-41: a denied permission shows the error text and does not emit a location', async () => {
configureLocation({ permission: 'denied' })
const onLocationChange = jest.fn()
const { getByTestId, getByText } = renderWithProviders(
<LocationAttacher onLocationChange={onLocationChange} />,
{ auth: false }
)
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(getByText('Location Permission denied')).toBeTruthy()
expect(onLocationChange).not.toHaveBeenCalled()
})
it('LOC-42: a failed location read shows the error text', async () => {
configureLocation({ permission: 'granted', throwOnPosition: true })
const { getByTestId, getByText } = renderWithProviders(<LocationAttacher />, { auth: false })
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(
getByText('Unable to fetch location. Please check your GPS settings.')
).toBeTruthy()
})
it('LOC-43: a disabled LocationAttacher never requests permission', async () => {
configureLocation({ permission: 'denied' })
const onLocationChange = jest.fn()
const { getByTestId, queryByText } = renderWithProviders(
<LocationAttacher disabled onLocationChange={onLocationChange} />,
{ auth: false }
)
expect(getByTestId('attach-current-location')).toBeDisabled()
fireEvent.press(getByTestId('attach-current-location'))
await flush(2)
expect(onLocationChange).not.toHaveBeenCalled()
expect(queryByText('Location Permission denied')).toBeNull()
})
it('LOC-44: an initial location shows the attached badge straight away', () => {
const { getByText } = renderWithProviders(
<LocationAttacher initialLocation={{ latitude: 1, longitude: 2 }} />,
{ auth: false }
)
expect(getByText('✓ Location Attached')).toBeTruthy()
})
it('LOC-45: the Google Maps option is button-first when uncontrolled and hidden when controlled', () => {
const uncontrolled = renderWithProviders(<LocationAttacher />, { auth: false })
fireEvent.press(uncontrolled.getByTestId('attach-google-maps'))
expect(uncontrolled.getByText(/Open Google Maps and Find location/)).toBeTruthy()
uncontrolled.unmount()
const controlled = renderWithProviders(
<LocationAttacher googleMapsUrl="" onGoogleMapsUrlChange={jest.fn()} />,
{ auth: false }
)
expect(controlled.queryByTestId('attach-google-maps')).toBeNull()
})
it('LOC-46: CartAddressGate enables the current-location option and shows the coordinates', () => {
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
const { getByTestId, getByText } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
expect(getByTestId('cart-address-current')).not.toBeDisabled()
expect(getByText('Use your current location (17.10000, 78.20000)')).toBeTruthy()
})
it('LOC-47: CartAddressGate disables the current-location option without coordinates', () => {
const { getByTestId, getByText } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
expect(getByTestId('cart-address-current')).toBeDisabled()
expect(getByText('Turn on location to use this option')).toBeTruthy()
})
it('LOC-48: CartAddressGate polls and takes a fix once the location turns usable', async () => {
jest.useFakeTimers()
configureLocation({ permission: 'granted' })
renderWithProviders(<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />, {
auth: false,
})
await act(async () => {
jest.advanceTimersByTime(3000)
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
await act(async () => {
await Promise.resolve()
})
expect(useLocationStore.getState().coords).not.toBeNull()
jest.useRealTimers()
})
it('LOC-49: the cart gate current-location mode prefills the device coordinates', async () => {
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-current'))
await flush(1)
const form = UNSAFE_getByType(AddressForm)
expect(form.props.initialValues).toMatchObject({
latitude: 17.1,
longitude: 78.2,
city: 'Mahabubnagar',
isDefault: true,
})
})
it('LOC-50: the cart gate other-location mode starts the form empty', async () => {
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-other'))
await flush(1)
expect(UNSAFE_getByType(AddressForm).props.initialValues).toBeUndefined()
})
it('LOC-51: a saved address in the cart gate closes the modal and calls onDone', async () => {
const onDone = jest.fn()
const { getByTestId, UNSAFE_getByType, UNSAFE_queryByType } = renderWithProviders(
<CartAddressGate onDone={onDone} onBack={jest.fn()} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-other'))
await flush(1)
await act(async () => {
UNSAFE_getByType(AddressForm).props.onSuccess()
})
await flush(1)
expect(onDone).toHaveBeenCalled()
expect(UNSAFE_queryByType(AddressForm)).toBeNull()
})
it('LOC-52: the cart gate back button calls onBack', () => {
const onBack = jest.fn()
const { getByTestId } = renderWithProviders(
<CartAddressGate onDone={jest.fn()} onBack={onBack} />,
{ auth: false }
)
fireEvent.press(getByTestId('cart-address-gate-back'))
expect(onBack).toHaveBeenCalled()
})
it('LOC-53: quick delivery (regular) shows the earliest slot and reports slot changes', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
const slots = setupQuickDelivery()
const onSlotChange = jest.fn()
const { getByTestId, getByText } = renderWithProviders(
<QuickDeliveryAddressSelector onSlotChange={onSlotChange} />,
{ auth: false }
)
await flush(4)
const earliest = [...slots].sort((a, b) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))[0]
expect(getByText(formatTimeRange(earliest.deliveryTime))).toBeTruthy()
fireEvent.press(getByTestId('quick-delivery-slot-button'))
await flush(1)
fireEvent.press(getByTestId('quick-delivery-slot-1849'))
expect(onSlotChange).toHaveBeenCalledWith(1849)
})
it('LOC-54: quick delivery (flash) shows "within 1 hour", the location bar and a back button', async () => {
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
signIn()
setupQuickDelivery()
const { getByTestId, getByText } = renderWithProviders(
<QuickDeliveryAddressSelector isForFlashDelivery />,
{ auth: false }
)
await flush(4)
expect(getByText('Delivery in within 1 hour')).toBeTruthy()
expect(getByTestId('location-bar')).toBeTruthy()
fireEvent.press(getByTestId('quick-delivery-flash-back'))
expect(router.back).toHaveBeenCalled()
})
})

View file

@ -0,0 +1,89 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — "LoginWall" (`tests/components/login-wall.test.tsx`).
*
* The wall only records the redirect state and pushes the login route; the
* `expo-router` mock records navigation instead of performing it, and
* `StorageServiceCasual` runs against the in-memory SecureStore mock.
*/
import * as React from 'react'
import { fireEvent, waitFor } from '@testing-library/react-native'
import { StorageServiceCasual } from 'common-ui'
import { resetAllMocks } from '../helpers/reset'
import { renderWithProviders } from '../helpers/test-utils'
import { __snapshot } from '../mocks/secure-store-mock'
import { router, __setPathname } from '../mocks/expo-router-mock'
import LoginWall from '@/components/LoginWall'
import constants from '@/src/constants'
describe('LoginWall', () => {
beforeEach(() => resetAllMocks())
it('LW-01: renders the default copy', () => {
const { getByText } = renderWithProviders(<LoginWall />, { auth: false })
expect(getByText('Please log in')).toBeTruthy()
expect(getByText('Log in to continue.')).toBeTruthy()
})
it('LW-02: renders a custom title and message', () => {
const { getByText } = renderWithProviders(
<LoginWall title="Sign in required" message="Only members can see this page." />,
{ auth: false }
)
expect(getByText('Sign in required')).toBeTruthy()
expect(getByText('Only members can see this page.')).toBeTruthy()
expect(getByText('Log In')).toBeTruthy()
})
it('LW-03: Log In stores the redirect target/query/timestamp and pushes login', async () => {
__setPathname('/me')
const { getByTestId } = renderWithProviders(<LoginWall />, { auth: false })
fireEvent.press(getByTestId('login-wall-login'))
await waitFor(() => expect(router.push).toHaveBeenCalledWith('/(auth)/login'))
const stored = __snapshot()[constants.AUTH_REDIRECT_KEY]
expect(stored).toBeTruthy()
const parsed = JSON.parse(stored)
expect(parsed.targetUrl).toBe('/me')
expect(parsed.queryParams).toEqual({})
expect(typeof parsed.timestamp).toBe('number')
})
it('LW-04: still pushes login when storing the redirect fails', async () => {
const setItemSpy = jest
.spyOn(StorageServiceCasual, 'setItem')
.mockRejectedValueOnce(new Error('storage unavailable'))
const { getByTestId } = renderWithProviders(<LoginWall />, { auth: false })
fireEvent.press(getByTestId('login-wall-login'))
await waitFor(() => expect(router.push).toHaveBeenCalledWith('/(auth)/login'))
expect(setItemSpy).toHaveBeenCalled()
expect(__snapshot()[constants.AUTH_REDIRECT_KEY]).toBeUndefined()
setItemSpy.mockRestore()
})
it('LW-05: renders Go Back and calls onBack when pressed', () => {
const onBack = jest.fn()
const { getByTestId } = renderWithProviders(<LoginWall onBack={onBack} />, { auth: false })
fireEvent.press(getByTestId('login-wall-back'))
expect(onBack).toHaveBeenCalledTimes(1)
})
it('LW-06: omits Go Back when no onBack handler is given', () => {
const { queryByTestId, queryByText } = renderWithProviders(<LoginWall />, { auth: false })
expect(queryByText('Go Back')).toBeNull()
expect(queryByTestId('login-wall-back')).toBeNull()
})
})

View file

@ -0,0 +1,232 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — `OrderMenu` (OM-01..10).
*
* The menu opens a BottomDialog; the Edit Notes and Cancel Order rows open their
* dialogs behind a 300ms `setTimeout`, so those cases run on fake timers and
* advance them in `act`. Mutations are asserted through the procedure registry
* (`lastProcedureInput`, `procedureMutationCalls`, `procedureInvalidations`).
*/
import * as React from 'react'
import { ActivityIndicator, Alert, TouchableOpacity } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native'
import OrderMenu from '@/components/OrderMenu'
import { renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastProcedureInput,
procedureInvalidations,
procedureMutationCalls,
setProcedure,
} from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock'
import { O1 } from '../fixtures'
const ORDER_ID = O1.id
let alertSpy: jest.SpyInstance
function setup({ fakeTimers = false }: { fakeTimers?: boolean } = {}) {
if (fakeTimers) jest.useFakeTimers()
const postActionHandler = jest.fn()
const utils = renderWithProviders(
<OrderMenu orderId={ORDER_ID} postActionHandler={postActionHandler} />,
{ auth: false }
)
return { ...utils, postActionHandler }
}
function advance(ms = 300) {
act(() => {
jest.advanceTimersByTime(ms)
})
}
type GetByTestId = (testId: string) => any
function openNotesDialog(getByTestId: GetByTestId) {
fireEvent.press(getByTestId('order-menu-trigger'))
fireEvent.press(getByTestId('order-menu-edit-notes'))
advance()
}
function openCancelDialog(getByTestId: GetByTestId) {
fireEvent.press(getByTestId('order-menu-trigger'))
fireEvent.press(getByTestId('order-menu-cancel-order'))
advance()
}
describe('OrderMenu', () => {
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => {
alertSpy.mockRestore()
})
it('OM-01: the trigger opens the Order Options menu', () => {
const { getByTestId, getByText } = setup()
fireEvent.press(getByTestId('order-menu-trigger'))
expect(getByText('Order Options')).toBeTruthy()
expect(getByText(`Select an action for Order #${ORDER_ID}`)).toBeTruthy()
})
it('OM-02: View Details pushes the order detail route', () => {
const { getByTestId } = setup()
fireEvent.press(getByTestId('order-menu-trigger'))
fireEvent.press(getByTestId('order-menu-view-details'))
expect(router.push).toHaveBeenCalledWith(
`/(drawer)/(tabs)/me/my-orders/${ORDER_ID}`
)
})
it('OM-03: Edit Notes opens only after 300ms, with an empty input', () => {
const { getByTestId, queryByText } = setup({ fakeTimers: true })
fireEvent.press(getByTestId('order-menu-trigger'))
fireEvent.press(getByTestId('order-menu-edit-notes'))
// The menu closes immediately; the notes dialog is still pending.
expect(queryByText('Order Options')).toBeNull()
expect(queryByText('Edit Instructions')).toBeNull()
advance(299)
expect(queryByText('Edit Instructions')).toBeNull()
advance(1)
expect(queryByText('Edit Instructions')).toBeTruthy()
expect(getByTestId('order-menu-notes-input').props.value).toBe('')
jest.useRealTimers()
})
it('OM-04: saving notes sends the trimmed payload, alerts and runs the post action', async () => {
const { getByTestId, postActionHandler } = setup({ fakeTimers: true })
openNotesDialog(getByTestId)
jest.useRealTimers()
fireEvent.changeText(getByTestId('order-menu-notes-input'), ' Leave at the door ')
fireEvent.press(getByTestId('order-menu-save-notes'))
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Notes updated successfully')
)
expect(lastProcedureInput('user.order.updateUserNotes')).toEqual({
id: ORDER_ID,
userNotes: 'Leave at the door',
})
expect(postActionHandler).toHaveBeenCalledTimes(1)
})
it('OM-05: a failed notes save alerts and leaves the dialog open', async () => {
setProcedure('user.order.updateUserNotes', { mode: 'error', error: new Error('nope') })
const { getByTestId, getByText } = setup({ fakeTimers: true })
openNotesDialog(getByTestId)
jest.useRealTimers()
fireEvent.changeText(getByTestId('order-menu-notes-input'), 'note')
fireEvent.press(getByTestId('order-menu-save-notes'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
expect(getByText('Edit Instructions')).toBeTruthy()
})
it('OM-06: a blank cancel reason alerts without calling the API', () => {
const { getByTestId, queryByText } = setup({ fakeTimers: true })
openCancelDialog(getByTestId)
expect(queryByText('Confirm Cancellation')).toBeTruthy()
fireEvent.press(getByTestId('order-menu-confirm-cancel'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'Please enter a reason for cancellation')
expect(procedureMutationCalls('user.order.cancelOrder')).toHaveLength(0)
jest.useRealTimers()
})
it('OM-07: cancelling invalidates orders, alerts and runs the post action', async () => {
const { getByTestId, postActionHandler } = setup({ fakeTimers: true })
openCancelDialog(getByTestId)
jest.useRealTimers()
fireEvent.changeText(getByTestId('order-menu-cancel-reason-input'), 'Ordered by mistake')
fireEvent.press(getByTestId('order-menu-confirm-cancel'))
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Order cancelled successfully')
)
expect(lastProcedureInput('user.order.cancelOrder')).toEqual({
id: ORDER_ID,
reason: 'Ordered by mistake',
})
expect(procedureInvalidations('user.order.getOrders')).toHaveLength(1)
expect(postActionHandler).toHaveBeenCalledTimes(1)
})
it('OM-08: a failed cancel alerts with the server message', async () => {
setProcedure('user.order.cancelOrder', {
mode: 'error',
error: new Error('cancel boom'),
})
const { getByTestId } = setup({ fakeTimers: true })
openCancelDialog(getByTestId)
jest.useRealTimers()
fireEvent.changeText(getByTestId('order-menu-cancel-reason-input'), 'reason')
fireEvent.press(getByTestId('order-menu-confirm-cancel'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'cancel boom'))
})
it('OM-09: closing the complaint form runs the post action', () => {
const { getByTestId, postActionHandler, UNSAFE_getAllByType } = setup()
fireEvent.press(getByTestId('order-menu-trigger'))
fireEvent.press(getByTestId('order-menu-raise-complaint'))
// The complaint BottomDialog renders last; its backdrop closes the form.
const backdrops = UNSAFE_getAllByType(TouchableOpacity).filter(
(node) => node.props.activeOpacity === 1
)
expect(backdrops.length).toBeGreaterThan(0)
fireEvent.press(backdrops[backdrops.length - 1])
expect(postActionHandler).toHaveBeenCalledTimes(1)
})
it('OM-10: pending mutations disable their buttons and show a spinner', () => {
setProcedure('user.order.updateUserNotes', { mode: 'pending' })
setProcedure('user.order.cancelOrder', { mode: 'pending' })
const { getByTestId, queryByText, UNSAFE_getAllByType } = setup({ fakeTimers: true })
// Edit notes pending.
openNotesDialog(getByTestId)
fireEvent.changeText(getByTestId('order-menu-notes-input'), 'note')
fireEvent.press(getByTestId('order-menu-save-notes'))
expect(queryByText('Save Instructions')).toBeNull()
expect(getByTestId('order-menu-save-notes').props.accessibilityState.disabled).toBe(true)
expect(UNSAFE_getAllByType(ActivityIndicator).length).toBeGreaterThan(0)
// Cancel order pending.
openCancelDialog(getByTestId)
fireEvent.changeText(getByTestId('order-menu-cancel-reason-input'), 'reason')
fireEvent.press(getByTestId('order-menu-confirm-cancel'))
expect(queryByText('Confirm Cancellation')).toBeNull()
expect(getByTestId('order-menu-confirm-cancel').props.accessibilityState.disabled).toBe(true)
jest.useRealTimers()
})
})

View file

@ -0,0 +1,123 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — `OrderStatusTracker` (OST-01..07).
*
* `deliveryStageIndex` maps the backend deliveryStatus onto the furthest stage
* (Placed -> Packed -> Delivered); `cancelled` supersedes it and marks every
* stage inactive. Colours are asserted through the flattened style, and the dots
* carry per-stage testIDs.
*/
import * as React from 'react'
import { StyleSheet } from 'react-native'
import OrderStatusTracker from '@/components/OrderStatusTracker'
import { renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
const ACTIVE = '#10B981'
const INACTIVE = '#E2E8F0'
const LABEL_GRAY = '#94A3B8'
const STAGES = ['placed', 'packed', 'delivered'] as const
function renderTracker(props: {
deliveryStatus?: string | null
activeColor?: string
inactiveColor?: string
}) {
return renderWithProviders(<OrderStatusTracker {...props} />, { auth: false })
}
function backgroundColor(node: any): string | undefined {
return StyleSheet.flatten(node.props.style)?.backgroundColor
}
function textColor(node: any): string | undefined {
return StyleSheet.flatten(node.props.style)?.color
}
describe('OrderStatusTracker', () => {
beforeEach(() => resetAllMocks())
it('OST-01: pending / processing keeps only Placed active', () => {
const pending = renderTracker({ deliveryStatus: 'pending' })
expect(backgroundColor(pending.getByTestId('order-status-dot-placed'))).toBe(ACTIVE)
expect(backgroundColor(pending.getByTestId('order-status-dot-packed'))).toBe(INACTIVE)
expect(backgroundColor(pending.getByTestId('order-status-dot-delivered'))).toBe(INACTIVE)
pending.unmount()
const processing = renderTracker({ deliveryStatus: 'processing' })
expect(backgroundColor(processing.getByTestId('order-status-dot-placed'))).toBe(ACTIVE)
expect(backgroundColor(processing.getByTestId('order-status-dot-packed'))).toBe(INACTIVE)
})
it('OST-02: packaged marks Placed and Packed active', () => {
const { getByTestId } = renderTracker({ deliveryStatus: 'packaged' })
expect(backgroundColor(getByTestId('order-status-dot-placed'))).toBe(ACTIVE)
expect(backgroundColor(getByTestId('order-status-dot-packed'))).toBe(ACTIVE)
expect(backgroundColor(getByTestId('order-status-dot-delivered'))).toBe(INACTIVE)
})
it('OST-03: success / delivered marks every stage active', () => {
const success = renderTracker({ deliveryStatus: 'success' })
STAGES.forEach((stage) =>
expect(backgroundColor(success.getByTestId(`order-status-dot-${stage}`))).toBe(ACTIVE)
)
success.unmount()
const delivered = renderTracker({ deliveryStatus: 'delivered' })
STAGES.forEach((stage) =>
expect(backgroundColor(delivered.getByTestId(`order-status-dot-${stage}`))).toBe(ACTIVE)
)
})
it('OST-04: cancelled leaves no stage active and grays the labels', () => {
const { getByTestId, getByText } = renderTracker({ deliveryStatus: 'cancelled' })
STAGES.forEach((stage) =>
expect(backgroundColor(getByTestId(`order-status-dot-${stage}`))).toBe(INACTIVE)
)
expect(textColor(getByText('Placed'))).toBe(LABEL_GRAY)
expect(textColor(getByText('Packed'))).toBe(LABEL_GRAY)
expect(textColor(getByText('Delivered'))).toBe(LABEL_GRAY)
})
it('OST-05: null / empty status falls back to Placed only', () => {
const empty = renderTracker({ deliveryStatus: null })
expect(backgroundColor(empty.getByTestId('order-status-dot-placed'))).toBe(ACTIVE)
expect(backgroundColor(empty.getByTestId('order-status-dot-packed'))).toBe(INACTIVE)
empty.unmount()
const blank = renderTracker({ deliveryStatus: '' })
expect(backgroundColor(blank.getByTestId('order-status-dot-placed'))).toBe(ACTIVE)
expect(backgroundColor(blank.getByTestId('order-status-dot-packed'))).toBe(INACTIVE)
})
it('OST-06: custom colors drive both dot and connector colors', () => {
const active = '#FF0000'
const inactive = '#0000FF'
const { getByTestId } = renderTracker({
deliveryStatus: 'packaged',
activeColor: active,
inactiveColor: inactive,
})
expect(backgroundColor(getByTestId('order-status-dot-placed'))).toBe(active)
expect(backgroundColor(getByTestId('order-status-dot-packed'))).toBe(active)
expect(backgroundColor(getByTestId('order-status-dot-delivered'))).toBe(inactive)
// Placed->Packed connector is reached, Packed->Delivered is not.
expect(backgroundColor(getByTestId('order-status-line-right-placed'))).toBe(active)
expect(backgroundColor(getByTestId('order-status-line-left-packed'))).toBe(active)
expect(backgroundColor(getByTestId('order-status-line-right-packed'))).toBe(inactive)
expect(backgroundColor(getByTestId('order-status-line-left-delivered'))).toBe(inactive)
})
it('OST-07: exposes one dot per stage plus the tracker container', () => {
const { getByTestId, getAllByTestId } = renderTracker({ deliveryStatus: 'pending' })
expect(getByTestId('order-status-tracker')).toBeTruthy()
expect(getAllByTestId(/^order-status-dot-/)).toHaveLength(3)
STAGES.forEach((stage) => expect(getByTestId(`order-status-dot-${stage}`)).toBeTruthy())
})
})

View file

@ -0,0 +1,188 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — QuickDeliveryAddressSelector (SLOTQ-01..06).
*
* The header is a delivery-time picker (the address dropdown is currently
* commented out in the component) plus a warning when the selected/default
* address belongs to another region.
*/
import * as React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import dayjs from 'dayjs'
import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'
import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client'
import { __setAuthState } from '../mocks/auth-context'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { setJsonResponse } from '../mocks/fetch-json'
import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, REGION_2, SLOTS, CART_REG, slotsCacheUrl } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
jest.mock('@/src/hooks/useRegion', () => ({
useRegion: () => (globalThis as any).__regionHook,
}))
const ser = (address: any) => ({
...address,
addressLine1: address.line1,
addressLine2: address.line2,
phone: address.mobile,
})
const S1 = ser(A1) // Home, region 1
const S2 = ser(A2) // Work, region 2
const S3 = ser(A3) // NoRegion
function setRegionHook(overrides: Record<string, any> = {}) {
const state: any = {
region: null,
regionId: null,
boundId: null,
bound: null,
regionGeneration: 0,
hydrated: true,
coords: null,
locationStatus: 'idle',
isResolvingRegion: false,
setRegion: jest.fn(),
clearRegion: jest.fn(),
refreshLocation: jest.fn(),
...overrides,
}
;(globalThis as any).__regionHook = state
return state
}
function setup(options: { addresses?: any[]; slots?: any[] } = {}) {
seedJsonCache()
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
__setAuthState({ isAuthenticated: true, isLoading: false })
setProcedure('user.address.getUserAddresses', { data: { data: options.addresses ?? [S1, S2] } })
const slots = (options.slots ?? SLOTS).map((slot) => ({ ...slot }))
setJsonResponse(slotsCacheUrl(1) + '?v=123', {
slots,
productAvailability: [],
count: slots.length,
})
return slots
}
/** Mirrors the component's slot label formatter. */
function formatTimeRange(deliveryTime: string | Date) {
const time = dayjs(deliveryTime)
const endTime = time.add(1, 'hour')
const startPeriod = time.format('A')
const endPeriod = endTime.format('A')
const timeRange =
startPeriod === endPeriod
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
return `${time.format('ddd, DD MMM ')}${timeRange}`
}
describe('QuickDeliveryAddressSelector (SLOTQ)', () => {
beforeEach(() => {
resetAllMocks()
setRegionHook()
})
it('SLOTQ-01: a foreign address warns, confirms the switch and clears the cart/home', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
useRegionStore.getState().setRegion(REGION_1, 7)
useAddressStore.getState().setSelectedAddressId(12)
__set('cart_items', CART_REG)
setup()
const { getByTestId, getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false,
})
await flush(4)
expect(
getByText('Selected address is in another region. Tap to switch region (clears cart).')
).toBeTruthy()
fireEvent.press(getByTestId('quick-delivery-foreign-warning'))
expect(alertSpy).toHaveBeenCalled()
expect(alertSpy.mock.calls[0][0]).toBe('Switch region?')
const buttons = alertSpy.mock.calls[0][2] as any[]
const switchButton = buttons.find((button) => button.text === 'Switch & clear cart')
await act(async () => {
await switchButton.onPress()
})
expect(useRegionStore.getState().selectedRegionId).toBe(2)
expect(__snapshot().cart_items).toBe('[]')
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore()
})
it('SLOTQ-02: an address in an unavailable region alerts instead of switching', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
useRegionStore.getState().setRegion(REGION_1, 7)
useAddressStore.getState().setSelectedAddressId(31)
setup({ addresses: [S1, { ...S1, id: 31, regionId: 99 }] })
const { getByTestId } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false,
})
await flush(4)
fireEvent.press(getByTestId('quick-delivery-foreign-warning'))
expect(alertSpy).toHaveBeenCalledWith(
'Unavailable region',
'This address belongs to a region that is not currently available.'
)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
alertSpy.mockRestore()
})
it('SLOTQ-03: no selected/default address leaves the address summary hidden', async () => {
setup({ addresses: [] })
const { getByTestId, queryByText } = renderWithProviders(
<QuickDeliveryAddressSelector />,
{ auth: false }
)
await flush(4)
// The address dropdown is commented out in the component, so `Select address`
// never renders; the delivery-time button remains the only header control.
expect(queryByText('Select address')).toBeNull()
expect(getByTestId('quick-delivery-slot-button')).toBeTruthy()
})
it('SLOTQ-04: the earliest slot is selected and the slot list is sorted in place', async () => {
const slots = setup({ slots: [SLOTS[3], SLOTS[0], SLOTS[1]] })
const earliest = [...slots].sort((a, b) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))[0]
const { getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, { auth: false })
await flush(4)
expect(getByText(formatTimeRange(earliest.deliveryTime))).toBeTruthy()
// `slotsData.slots.sort(...)` mutates the fetched array in place.
expect(slots[0].id).toBe(earliest.id)
})
it('SLOTQ-05: with no slots the header shows "Select time"', async () => {
setup({ slots: [] })
const { getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, {
auth: false,
})
await flush(4)
expect(getByText('Select time')).toBeTruthy()
})
it('SLOTQ-06: a selected slot id renders its formatted delivery range', async () => {
const slots = setup()
const chosen = slots.find((slot) => slot.id === 1849) ?? slots[0]
const { getByText } = renderWithProviders(
<QuickDeliveryAddressSelector slotId={1849} />,
{ auth: false }
)
await flush(4)
expect(getByText(formatTimeRange(chosen.deliveryTime))).toBeTruthy()
})
})

View file

@ -0,0 +1,596 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* REG-06 .. REG-37 — shared registration / edit-profile form.
*
* The form is rendered directly (no page wrapper) so the `onSubmit` spy and the
* `user.auth.updatePassword` mutation are the only things that observe the
* payload. Network is limited to the object-store upload path: procedure mocks
* for `common.generateUploadUrls` and a `global.fetch` PUT spy.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker'
import RegistrationForm from '@/components/registration-form'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastProcedureInput,
procedureCallCount,
} from '../mocks/trpc-client'
const UPLOAD_URL = 'https://bucket.test/profile/upload-1.jpg'
// extractKeyFromPresignedUrl drops the bucket segment: bucket/profile/<key>.
const UPLOAD_KEY = 'upload-1.jpg'
const picker = ImagePicker.launchImageLibraryAsync as unknown as jest.Mock
let alertSpy: jest.SpyInstance
/** Replace `global.fetch`: the blob read resolves, the presigned PUT succeeds. */
function mockFetch() {
const fn = jest.fn(async (_url: string, init?: any) => {
if (init?.method === 'PUT') {
return { ok: true, status: 200 } as any
}
return { ok: true, status: 200, blob: async () => ({ size: 4 }) } as any
})
;(global as any).fetch = fn
return fn
}
function mockPickerOnce(asset: any) {
picker.mockResolvedValueOnce({ canceled: false, assets: [asset] })
}
function renderForm(onSubmit: jest.Mock, extra: Record<string, any> = {}) {
return renderWithProviders(<RegistrationForm onSubmit={onSubmit} {...extra} />, {
auth: false,
})
}
type Get = (id: string) => any
/** Fill every field the register-mode form validates, with per-field overrides. */
function fillAllValid(get: Get, overrides: Record<string, any> = {}) {
const values = {
name: 'Alice',
email: 'alice@example.com',
mobile: '9876543210',
password: 'secret1',
confirmPassword: 'secret1',
terms: true,
...overrides,
}
fireEvent.changeText(get('registration-name-input'), values.name)
fireEvent.changeText(get('registration-email-input'), values.email)
fireEvent.changeText(get('registration-mobile-input'), values.mobile)
fireEvent.changeText(get('registration-password-input'), values.password)
fireEvent.changeText(get('registration-confirm-password-input'), values.confirmPassword)
if (values.terms) fireEvent.press(get('registration-terms-toggle'))
}
async function submitForm(get: Get) {
fireEvent.press(get('registration-submit-button'))
await flush()
}
async function pickImage(get: Get, asset: any) {
mockPickerOnce(asset)
fireEvent.press(get('profile-image-picker'))
await flush()
}
async function openPasswordDialog(get: Get) {
fireEvent.press(get('registration-update-password-button'))
await flush()
}
const EDIT_VALUES = {
name: 'Bob',
email: 'bob@example.com',
mobile: '9876543210',
profileImageUri: 'https://cdn.test/avatar.png',
}
describe('RegistrationForm (REG-06..REG-37)', () => {
beforeEach(() => {
resetAllMocks()
picker.mockReset()
picker.mockResolvedValue({ canceled: true, assets: null })
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
/* ---------------- name ---------------- */
it('REG-06: empty name shows "Name is required" and does not submit', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
await submitForm(getByTestId)
expect(getByText('Name is required')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-07: one-character name shows the minimum-length error', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { name: 'A' })
await submitForm(getByTestId)
expect(getByText('Name must be at least 2 characters')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-08: name surrounded by spaces is trimmed before validation and payload', async () => {
const onSubmit = jest.fn()
const { getByTestId } = renderForm(onSubmit)
fillAllValid(getByTestId, { name: ' Alice ' })
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0].name).toBe('Alice')
})
/* ---------------- email ---------------- */
it('REG-09: empty email in registration shows "Email is required"', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { email: '' })
await submitForm(getByTestId)
expect(getByText('Email is required')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-10: invalid email a@b shows the format error', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { email: 'a@b' })
await submitForm(getByTestId)
expect(getByText('Please enter a valid email address')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-11: uppercase email is lowercased in the payload', async () => {
const onSubmit = jest.fn()
const { getByTestId } = renderForm(onSubmit)
fillAllValid(getByTestId, { email: 'ALICE@EXAMPLE.COM' })
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit.mock.calls[0][0].email).toBe('alice@example.com')
})
it('REG-12: empty email in edit mode (catalogue: accepted — see report)', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit, {
isEdit: true,
initialValues: { name: 'Bob', email: '', mobile: '9876543210' },
})
await submitForm(getByTestId)
// Current implementation: the Controller's unconditional `required` rule
// still blocks submission, even though the manual guard skips email in
// edit mode. Asserted as-is (documented as a catalogue/implementation gap).
expect(getByText('Email is required')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
/* ---------------- mobile ---------------- */
it('REG-13: empty mobile shows "Mobile number is required"', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { mobile: '' })
await submitForm(getByTestId)
expect(getByText('Mobile number is required')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-14: ten digits not starting 6-9 shows the format error', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { mobile: '1234567890' })
await submitForm(getByTestId)
expect(getByText('Please enter a valid 10-digit mobile number')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-15: mobile input keeps digits only and never exceeds 10 digits', () => {
const { getByTestId } = renderForm(jest.fn())
const input = getByTestId('registration-mobile-input')
fireEvent.changeText(input, '98 76-54 32 10')
expect(getByTestId('registration-mobile-input').props.value).toBe('9876543210')
// 11 digits: the change is rejected, so the value stays at 10 digits.
fireEvent.changeText(input, '98765432109')
expect(getByTestId('registration-mobile-input').props.value).toBe('9876543210')
})
/* ---------------- password + terms (register mode) ---------------- */
it('REG-16: empty password shows "Password is required"', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { password: '', confirmPassword: '' })
await submitForm(getByTestId)
expect(getByText('Password is required')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-17: password shorter than 6 shows the minimum-length error', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { password: '123', confirmPassword: '123' })
await submitForm(getByTestId)
expect(getByText('Password must be at least 6 characters')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-18: mismatched confirm password shows "Passwords do not match"', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { password: 'secret1', confirmPassword: 'nope123' })
await submitForm(getByTestId)
expect(getByText('Passwords do not match')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-19: unaccepted terms show the terms error and do not submit', async () => {
const onSubmit = jest.fn()
const { getByTestId, getByText } = renderForm(onSubmit)
fillAllValid(getByTestId, { terms: false })
await submitForm(getByTestId)
expect(getByText('You must accept the terms and conditions')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
/* ---------------- happy registration ---------------- */
it('REG-20: valid registration submits the normalized payload', async () => {
const onSubmit = jest.fn()
const { getByTestId } = renderForm(onSubmit)
fillAllValid(getByTestId, {
name: ' Alice ',
email: 'Alice@Example.COM',
mobile: '98765 43210',
})
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(onSubmit).toHaveBeenCalledWith({
name: 'Alice',
email: 'alice@example.com',
mobile: '9876543210',
password: 'secret1',
})
})
/* ---------------- profile image upload ---------------- */
it('REG-21: selected image is uploaded and the payload carries profileImageUrl', async () => {
const onSubmit = jest.fn()
const fetchMock = mockFetch()
setProcedure('common.generateUploadUrls', { data: { uploadUrls: [UPLOAD_URL] } })
const { getByTestId } = renderForm(onSubmit)
await pickImage(getByTestId, {
uri: 'file:///avatar.png',
mimeType: 'image/png',
fileName: 'avatar.png',
})
fillAllValid(getByTestId)
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(lastProcedureInput('common.generateUploadUrls')).toEqual({
contextString: 'profile',
mimeTypes: ['image/png'],
})
const putCall = fetchMock.mock.calls.find(([, init]: any) => init?.method === 'PUT')
expect(putCall?.[0]).toBe(UPLOAD_URL)
expect(putCall?.[1]).toEqual({
method: 'PUT',
body: expect.anything(),
headers: { 'Content-Type': 'image/png' },
})
expect(onSubmit.mock.calls[0][0]).toEqual({
name: 'Alice',
email: 'alice@example.com',
mobile: '9876543210',
password: 'secret1',
profileImageUrl: UPLOAD_KEY,
})
})
it('REG-22: cancelled picker means no upload and no profileImageUrl key', async () => {
const onSubmit = jest.fn()
mockFetch()
const { getByTestId } = renderForm(onSubmit)
fireEvent.press(getByTestId('profile-image-picker'))
await flush()
fillAllValid(getByTestId)
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(procedureCallCount('common.generateUploadUrls')).toBe(0)
expect('profileImageUrl' in onSubmit.mock.calls[0][0]).toBe(false)
})
it('REG-23: missing mime type falls back to image/jpeg', async () => {
const onSubmit = jest.fn()
const fetchMock = mockFetch()
setProcedure('common.generateUploadUrls', { data: { uploadUrls: [UPLOAD_URL] } })
const { getByTestId } = renderForm(onSubmit)
await pickImage(getByTestId, { uri: 'file:///avatar.png', fileName: 'avatar.png' })
fillAllValid(getByTestId)
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect(lastProcedureInput('common.generateUploadUrls')).toEqual({
contextString: 'profile',
mimeTypes: ['image/jpeg'],
})
const putCall = fetchMock.mock.calls.find(([, init]: any) => init?.method === 'PUT')
expect(putCall?.[1].headers).toEqual({ 'Content-Type': 'image/jpeg' })
})
it('REG-24: a rejected upload rejects the submit and never calls onSubmit', async () => {
const onSubmit = jest.fn()
mockFetch()
setProcedure('common.generateUploadUrls', {
mode: 'error',
error: new Error('upload boom'),
})
const { getByTestId } = renderForm(onSubmit)
await pickImage(getByTestId, {
uri: 'file:///avatar.png',
mimeType: 'image/png',
fileName: 'avatar.png',
})
fillAllValid(getByTestId)
const submission = fireEvent.press(getByTestId('registration-submit-button'))
await act(async () => {
await expect(Promise.resolve(submission)).rejects.toThrow('upload boom')
})
await flush()
// No Alert is raised for upload failures in the current implementation.
expect(alertSpy).not.toHaveBeenCalled()
expect(onSubmit).not.toHaveBeenCalled()
})
it('REG-25: pending upload shows "Uploading..." on a disabled button', async () => {
const onSubmit = jest.fn()
mockFetch()
setProcedure('common.generateUploadUrls', { mode: 'pending' })
const { getByTestId, getByText } = renderForm(onSubmit)
await pickImage(getByTestId, {
uri: 'file:///avatar.png',
mimeType: 'image/png',
fileName: 'avatar.png',
})
fillAllValid(getByTestId)
fireEvent.press(getByTestId('registration-submit-button'))
await flush()
expect(getByText('Uploading...')).toBeTruthy()
expect(getByTestId('registration-submit-button')).toBeDisabled()
expect(onSubmit).not.toHaveBeenCalled()
})
/* ---------------- edit mode ---------------- */
it('REG-26: edit mode hides register fields and swaps the actions', () => {
const { getByTestId, getByText, queryByTestId } = renderForm(jest.fn(), {
isEdit: true,
initialValues: EDIT_VALUES,
})
expect(queryByTestId('registration-password-input')).toBeNull()
expect(queryByTestId('registration-confirm-password-input')).toBeNull()
expect(queryByTestId('registration-terms-toggle')).toBeNull()
expect(getByText('Update Profile')).toBeTruthy()
expect(getByTestId('registration-update-password-button')).toBeTruthy()
expect(getByText('Update Password')).toBeTruthy()
})
it('REG-27: edit mode prefills name, email, mobile and profile image', async () => {
const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES })
expect(getByTestId('registration-name-input').props.value).toBe('Bob')
expect(getByTestId('registration-email-input').props.value).toBe('bob@example.com')
expect(getByTestId('registration-mobile-input').props.value).toBe('9876543210')
await waitFor(() =>
expect(getByTestId('expo-image').props.accessibilityLabel).toBe(
EDIT_VALUES.profileImageUri
)
)
})
it('REG-28: edit submit sends name/email/mobile and omits password', async () => {
const onSubmit = jest.fn()
const { getByTestId } = renderForm(onSubmit, { isEdit: true, initialValues: EDIT_VALUES })
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
const payload = onSubmit.mock.calls[0][0]
expect(payload.name).toBe('Bob')
expect(payload.email).toBe('bob@example.com')
expect(payload.mobile).toBe('9876543210')
expect(payload.password).toBeUndefined()
})
it('REG-29: edit mode never renders password fields and the payload omits password', async () => {
const onSubmit = jest.fn()
const { getByTestId, queryByTestId } = renderForm(onSubmit, {
isEdit: true,
initialValues: EDIT_VALUES,
})
expect(queryByTestId('registration-password-input')).toBeNull()
expect(queryByTestId('registration-confirm-password-input')).toBeNull()
await submitForm(getByTestId)
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
expect('password' in onSubmit.mock.calls[0][0]).toBe(false)
})
it('REG-36: edit loading shows "Updating..." on a disabled button', () => {
const { getByTestId, getByText } = renderForm(jest.fn(), {
isEdit: true,
isLoading: true,
initialValues: EDIT_VALUES,
})
expect(getByText('Updating...')).toBeTruthy()
expect(getByTestId('registration-submit-button')).toBeDisabled()
})
it('REG-37: ProfileImage receives the initial profile image URI', async () => {
const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES })
await waitFor(() =>
expect(getByTestId('expo-image').props.accessibilityLabel).toBe(
EDIT_VALUES.profileImageUri
)
)
})
/* ---------------- password dialog ---------------- */
it('REG-30: mismatched dialog passwords alert and skip the mutation', async () => {
const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES })
await openPasswordDialog(getByTestId)
fireEvent.changeText(getByTestId('password-dialog-password-input'), 'secret1')
fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), 'other12')
fireEvent.press(getByTestId('password-dialog-update-button'))
await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Passwords do not match')
expect(procedureCallCount('user.auth.updatePassword')).toBe(0)
})
it('REG-31: a short dialog password alerts and skips the mutation', async () => {
const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES })
await openPasswordDialog(getByTestId)
fireEvent.changeText(getByTestId('password-dialog-password-input'), '123')
fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), '123')
fireEvent.press(getByTestId('password-dialog-update-button'))
await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Password must be at least 6 characters')
expect(procedureCallCount('user.auth.updatePassword')).toBe(0)
})
it('REG-32: a valid dialog password mutates, alerts, closes and resets', async () => {
const { getByTestId, queryByTestId } = renderForm(jest.fn(), {
isEdit: true,
initialValues: EDIT_VALUES,
})
await openPasswordDialog(getByTestId)
fireEvent.changeText(getByTestId('password-dialog-password-input'), 'secret1')
fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), 'secret1')
fireEvent.press(getByTestId('password-dialog-update-button'))
await flush()
await waitFor(() =>
expect(lastProcedureInput('user.auth.updatePassword')).toEqual({ password: 'secret1' })
)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Password updated successfully')
expect(queryByTestId('password-dialog-password-input')).toBeNull()
await openPasswordDialog(getByTestId)
expect(getByTestId('password-dialog-password-input').props.value).toBe('')
expect(getByTestId('password-dialog-confirm-password-input').props.value).toBe('')
})
it('REG-33: a rejected password mutation alerts and keeps the dialog open', async () => {
setProcedure('user.auth.updatePassword', { mode: 'error', error: new Error('nope') })
const { getByTestId, queryByTestId } = renderForm(jest.fn(), {
isEdit: true,
initialValues: EDIT_VALUES,
})
await openPasswordDialog(getByTestId)
fireEvent.changeText(getByTestId('password-dialog-password-input'), 'secret1')
fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), 'secret1')
fireEvent.press(getByTestId('password-dialog-update-button'))
await flush()
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
expect(queryByTestId('password-dialog-password-input')).not.toBeNull()
})
it('REG-34: a pending password mutation disables the Update button', async () => {
setProcedure('user.auth.updatePassword', { mode: 'pending' })
const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES })
await openPasswordDialog(getByTestId)
fireEvent.changeText(getByTestId('password-dialog-password-input'), 'secret1')
fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), 'secret1')
fireEvent.press(getByTestId('password-dialog-update-button'))
await flush()
expect(getByTestId('password-dialog-update-button')).toBeDisabled()
})
it('REG-35: cancelling the dialog closes it, calls no API and keeps the values', async () => {
const { getByTestId, queryByTestId } = renderForm(jest.fn(), {
isEdit: true,
initialValues: EDIT_VALUES,
})
await openPasswordDialog(getByTestId)
fireEvent.changeText(getByTestId('password-dialog-password-input'), 'secret1')
fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), 'secret1')
fireEvent.press(getByTestId('password-dialog-cancel-button'))
await flush()
expect(queryByTestId('password-dialog-password-input')).toBeNull()
expect(procedureCallCount('user.auth.updatePassword')).toBe(0)
// Current behaviour: closing does not reset the local dialog state.
await openPasswordDialog(getByTestId)
expect(getByTestId('password-dialog-password-input').props.value).toBe('secret1')
expect(getByTestId('password-dialog-confirm-password-input').props.value).toBe('secret1')
})
})

View file

@ -0,0 +1,171 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 24 — "Static / chrome" (`tests/components/static-chrome.test.tsx`).
*
* - STATIC-01..05 TabLayoutWrapper, TestingPhaseNote, TermsAndConditionsContent,
* the tab icon set (focused/unfocused) and icon prop pass-through
* - TERMS-04..05 the shared `TermsAndConditionsContent` props (showTitle / compact)
*
* The icons intentionally exercise the `react-native-svg` shim so a broken icon
* (missing render) fails here instead of surfacing on a page test.
*/
import * as React from 'react'
import { Text } from 'react-native'
import { render, within } from '@testing-library/react-native'
import Svg, { Path } from 'react-native-svg'
import { resetAllMocks } from '../helpers/reset'
import { renderWithProviders } from '../helpers/test-utils'
import TabLayoutWrapper from '@/components/TabLayoutWrapper'
import TestingPhaseNote from '@/components/TestingPhaseNote'
import { TermsAndConditionsContent } from '@/components/TermsAndConditions'
import HomeIcon from '@/components/icons/HomeIcon'
import StoresIcon from '@/components/icons/StoresIcon'
import CartIcon from '@/components/icons/CartIcon'
import OffersIcon from '@/components/icons/OffersIcon'
import MeIcon from '@/components/icons/MeIcon'
describe('Static / chrome', () => {
beforeEach(() => resetAllMocks())
/** Deep-merge a (possibly nested, possibly falsy) RN style prop. */
const flatStyle = (style: any): Record<string, any> => {
if (!style) return {}
if (Array.isArray(style)) return Object.assign({}, ...style.map(flatStyle))
if (typeof style === 'object') return style
return {}
}
it('STATIC-01: TabLayoutWrapper renders children inside the top safe area', () => {
const { getByTestId, getByText } = renderWithProviders(
<TabLayoutWrapper style={{ backgroundColor: '#FFFFFF' }}>
<Text>tab-child</Text>
</TabLayoutWrapper>,
{ auth: false }
)
const wrapper = getByTestId('tab-layout-wrapper')
expect(getByText('tab-child')).toBeTruthy()
// Base `flex-1 bg-white` merged with the caller style.
const merged = flatStyle(wrapper.props.style)
expect(merged.backgroundColor).toBe('#FFFFFF')
expect(merged.flexGrow).toBe(1)
})
it('STATIC-02: TestingPhaseNote shows the title and four bullets', () => {
const { getByTestId } = renderWithProviders(<TestingPhaseNote />, { auth: false })
const note = within(getByTestId('testing-phase-note'))
expect(note.getByText('Testing Phase')).toBeTruthy()
expect(note.getByText('• This app is in testing phase until Jan 23, 2026')).toBeTruthy()
expect(note.getByText('• Actual delivery service has not started yet')).toBeTruthy()
expect(note.getByText('• Prices shown are not real')).toBeTruthy()
expect(
note.getByText('• Any feedback or issues found? WhatsApp on +91 9676651496')
).toBeTruthy()
})
it('STATIC-03: TermsAndConditionsContent renders the full policy', () => {
const { getByTestId } = renderWithProviders(<TermsAndConditionsContent />, { auth: false })
const terms = within(getByTestId('terms-content'))
expect(terms.getByText('FRESHYO – Legal Policies')).toBeTruthy()
// Sections A–E.
expect(terms.getByText('A. TERMS & CONDITIONS')).toBeTruthy()
expect(terms.getByText('B. PRIVACY POLICY')).toBeTruthy()
expect(terms.getByText('C. REFUND & CANCELLATION POLICY')).toBeTruthy()
expect(terms.getByText('D. CONTACT INFORMATION')).toBeTruthy()
expect(terms.getByText('E. ACCEPTANCE')).toBeTruthy()
// COD-only + privacy + refunds + contact.
expect(
terms.getByText(
'Prices are displayed in INR and include applicable taxes unless stated otherwise. Only Cash on Delivery (COD) is accepted. Full payment must be made at the time of delivery. Failure to pay may result in order cancellation and account restrictions.'
)
).toBeTruthy()
expect(
terms.getByText('FRESHYO respects your privacy and is committed to protecting your data.')
).toBeTruthy()
expect(
terms.getByText(
"Since payments are Cash on Delivery, refunds (if applicable) will be handled via: cash adjustment, replacement, or store credit (at FRESHYO's discretion)."
)
).toBeTruthy()
expect(terms.getByText('📧 Email: support@freshyo.in')).toBeTruthy()
expect(terms.getByText('📞 Customer Support: 8688182552')).toBeTruthy()
})
it('STATIC-04: every tab icon renders one SVG per focused/unfocused state', () => {
const { UNSAFE_getAllByType } = render(
<>
<HomeIcon focused size={24} color="#111111" />
<HomeIcon focused={false} size={24} color="#111111" />
<StoresIcon focused size={24} color="#111111" />
<StoresIcon focused={false} size={24} color="#111111" />
<CartIcon focused size={24} color="#111111" />
<CartIcon focused={false} size={24} color="#111111" />
<OffersIcon focused size={24} color="#111111" />
<OffersIcon focused={false} size={24} color="#111111" />
<MeIcon focused size={24} color="#111111" />
<MeIcon focused={false} size={24} color="#111111" />
</>
)
expect(UNSAFE_getAllByType(Svg)).toHaveLength(10)
})
it('STATIC-05: icon size and color are passed through to the SVG props', () => {
const { UNSAFE_getAllByType, UNSAFE_getByType } = render(
<HomeIcon focused size={40} color="#123456" />
)
const svg = UNSAFE_getByType(Svg)
expect(svg.props.width).toBe(40)
expect(svg.props.height).toBe(40)
const paths = UNSAFE_getAllByType(Path)
expect(paths.length).toBeGreaterThan(0)
paths.forEach((path: any) => expect(path.props.fill).toBe('#123456'))
})
it('TERMS-04: showTitle=false hides the title but keeps the sections', () => {
const { getByTestId, queryByText } = renderWithProviders(
<TermsAndConditionsContent showTitle={false} />,
{ auth: false }
)
expect(queryByText('FRESHYO – Legal Policies')).toBeNull()
expect(queryByText('Last Updated: [Add Date]')).toBeNull()
const terms = within(getByTestId('terms-content'))
expect(terms.getByText('A. TERMS & CONDITIONS')).toBeTruthy()
expect(terms.getByText('E. ACCEPTANCE')).toBeTruthy()
})
it('TERMS-05: compact applies the smaller text styles', () => {
const regular = renderWithProviders(<TermsAndConditionsContent showTitle={false} />, {
auth: false,
})
const compact = renderWithProviders(
<TermsAndConditionsContent showTitle={false} compact />,
{ auth: false }
)
const styleOf = (result: any, text: string) => flatStyle(result.getByText(text).props.style)
const regularHeading = styleOf(regular, 'A. TERMS & CONDITIONS')
const compactHeading = styleOf(compact, 'A. TERMS & CONDITIONS')
expect(compactHeading.fontSize).toBeLessThan(regularHeading.fontSize)
const regularBody = styleOf(
regular,
'FRESHYO is a grocery and fresh meat delivery application serving customers only within Mahabubnagar Town, Telangana, India.'
)
const compactBody = styleOf(
compact,
'FRESHYO is a grocery and fresh meat delivery application serving customers only within Mahabubnagar Town, Telangana, India.'
)
expect(compactBody.fontSize).toBeLessThan(regularBody.fontSize)
})
})

601
apps/user-ui/tests/fixtures/index.ts vendored Normal file
View file

@ -0,0 +1,601 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Backend-shaped fixtures used across the user-ui suite.
*
* Field names mirror the real cache/scaffold payloads:
* - products.json -> scaffoldProducts ({ products, count, tags })
* - availability -> scaffoldAvailability ({ availability, count })
* - slots.json -> scaffoldSlotsWithProducts ({ slots, productAvailability, count })
* - stores.json -> scaffoldStores ({ stores })
* - stores/<id>.json -> scaffoldStoreWithProducts ({ store, products, tags })
*/
export const REGION_1 = {
id: 1,
name: 'Mahabubnagar',
description: 'Region one',
effectiveBoundId: 7,
}
export const REGION_2 = {
id: 2,
name: 'Hyderabad',
description: 'Region two',
effectiveBoundId: 8,
}
export const REGIONS = [REGION_1, REGION_2]
export const BOUND_1 = { id: 7, regionId: 1, priority: 1, name: 'Bound 1' }
export const BOUND_2 = { id: 8, regionId: 1, priority: 10, name: 'Bound 2' }
export const CACHE_BASE = 'https://assets.test/freshyo-cache/'
export const API_CACHE_KEY = 'cache-key'
export const PRODUCTS_VERSION_NUM = 12
export const AVAILABILITY_VERSION_NUM = 34
export const SLOTS_VERSION_NUM = 56
/** Flat essential-consts payload returned by `common.essentialConsts`. */
export const CONSTS = {
boundId: 7,
regionId: 1,
assetsDomain: CACHE_BASE,
apiCacheKey: API_CACHE_KEY,
products_version_num: PRODUCTS_VERSION_NUM,
availability_version_num: AVAILABILITY_VERSION_NUM,
slots_version_num: SLOTS_VERSION_NUM,
freeDeliveryThreshold: 249,
deliveryCharge: 15,
flashFreeDeliveryThreshold: 199,
flashDeliveryCharge: 25,
isFlashDeliveryEnabled: true,
platformFeePercent: 0,
supportMobile: '8688182552',
supportEmail: 'support@freshyo.in',
welcomeMessage: 'Welcome to Freshyo',
versionNum: '1.2.0',
internalAppVersion: 2,
appStoreUrl: 'https://apps.apple.com/app/freshyo/id123456',
playStoreUrl: 'https://play.google.com/store/apps/details?id=com.freshyotrial.app',
webviewHtml: null,
isWebviewClosable: true,
tagsOrder: [1, 2, 3],
}
export const CONSTS_FLASH_OFF = { ...CONSTS, isFlashDeliveryEnabled: false }
export function productsCacheUrl(regionId = 1, version = PRODUCTS_VERSION_NUM) {
return `${CACHE_BASE}${API_CACHE_KEY}/regions/${regionId}/v-${version}/products.json`
}
export function availabilityCacheUrl(regionId = 1, version = AVAILABILITY_VERSION_NUM) {
return `${CACHE_BASE}regions/${regionId}/av-${version}/availability.json`
}
export function slotsCacheUrl(regionId = 1, version = SLOTS_VERSION_NUM) {
return `${CACHE_BASE}regions/${regionId}/slots/v-${version}/slots.json`
}
export function storesCacheUrl(regionId = 1, version = PRODUCTS_VERSION_NUM) {
return `${CACHE_BASE}${API_CACHE_KEY}/regions/${regionId}/v-${version}/stores.json`
}
export function storeDetailCacheUrl(storeId: number, regionId = 1, version = PRODUCTS_VERSION_NUM) {
return `${CACHE_BASE}${API_CACHE_KEY}/regions/${regionId}/v-${version}/stores/${storeId}.json`
}
/* -------------------------------------------------------------------------- */
/* Products */
/* -------------------------------------------------------------------------- */
export const P_CHICKEN = {
id: 2,
name: 'Chicken Breast',
shortDescription: 'Tender boneless breast',
unit: '500g',
unitNotation: '500g',
incrementStep: 1,
productQuantity: 500,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: ['chicken.jpg'],
productType: 'item',
isComboOnly: false,
price: 215,
marketPrice: 220,
flashPrice: null,
isFlashAvailable: false,
}
export const P_CUCUMBER = {
id: 5,
name: 'Cucumber',
shortDescription: 'Farm fresh cucumbers',
unit: '500g',
unitNotation: '500g',
incrementStep: 1,
productQuantity: 500,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: ['cucumber.jpg'],
productType: 'item',
isComboOnly: false,
price: 15,
marketPrice: 20,
flashPrice: null,
isFlashAvailable: false,
}
export const P_OUT = {
id: 6,
name: 'Mutton',
shortDescription: 'Fresh mutton',
unit: '500g',
unitNotation: '500g',
incrementStep: 1,
productQuantity: 500,
storeId: 1,
isOutOfStock: true,
nextDeliveryDate: null,
images: ['mutton.jpg'],
productType: 'item',
isComboOnly: false,
price: 400,
marketPrice: 450,
flashPrice: null,
isFlashAvailable: false,
}
export const P_OFFER = {
id: 7,
name: 'Offer Chicken',
shortDescription: 'Special offer pack',
unit: '1kg',
unitNotation: '1kg',
incrementStep: 1,
productQuantity: 1000,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: ['offer.jpg'],
productType: 'item',
isComboOnly: false,
price: 199,
marketPrice: 260,
flashPrice: null,
isFlashAvailable: false,
}
export const P_FLASH = {
id: 8,
name: 'Paneer',
shortDescription: 'Soft paneer cubes',
unit: '200g',
unitNotation: '200g',
incrementStep: 1,
productQuantity: 200,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: ['paneer.jpg'],
productType: 'item',
isComboOnly: false,
price: 90,
marketPrice: 100,
flashPrice: 75,
isFlashAvailable: true,
}
export const P_NO_IMAGE = {
id: 9,
name: 'No Image Item',
shortDescription: '',
unit: '1pc',
unitNotation: '1pc',
incrementStep: 1,
productQuantity: 1,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: [],
productType: 'item',
isComboOnly: false,
price: 10,
marketPrice: null,
flashPrice: null,
isFlashAvailable: false,
}
export const P_NO_SLOT = {
id: 10,
name: 'No Slot Item',
shortDescription: '',
unit: '1pc',
unitNotation: '1pc',
incrementStep: 1,
productQuantity: 1,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: ['noslot.jpg'],
productType: 'item',
isComboOnly: false,
price: 50,
marketPrice: 60,
flashPrice: null,
isFlashAvailable: false,
}
export const P_COMBO_ONLY = {
id: 149,
name: 'Combo Only SKU',
shortDescription: '',
unit: '1pc',
unitNotation: '1pc',
incrementStep: 1,
productQuantity: 1,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: [],
productType: 'item',
isComboOnly: true,
price: 99,
marketPrice: 120,
flashPrice: null,
isFlashAvailable: false,
}
export const P_COMBO = {
id: 150,
name: 'Family Combo',
shortDescription: 'Chicken + cucumber combo',
longDescription: 'A family pack with chicken and cucumber.',
unit: '1 combo',
unitNotation: '1 combo',
incrementStep: 1,
productQuantity: 1,
storeId: 1,
isOutOfStock: false,
nextDeliveryDate: null,
images: ['combo.jpg'],
productType: 'combo',
isComboOnly: false,
price: 599,
marketPrice: 700,
flashPrice: null,
isFlashAvailable: false,
comboItems: [P_CHICKEN, P_CUCUMBER],
}
export const PRODUCTS = [
P_CHICKEN,
P_CUCUMBER,
P_OUT,
P_OFFER,
P_FLASH,
P_NO_IMAGE,
P_NO_SLOT,
P_COMBO,
P_COMBO_ONLY,
]
export const TAGS = [
{ id: 1, tagName: 'Chicken', tagDescription: null, imageUrl: null, isDashboardTag: true, relatedStores: [1], productIds: [2, 6, 9] },
{ id: 2, tagName: 'Vegetables', tagDescription: null, imageUrl: null, isDashboardTag: false, relatedStores: [1], productIds: [5] },
{ id: 3, tagName: 'Empty', tagDescription: null, imageUrl: null, isDashboardTag: false, relatedStores: [], productIds: [] },
]
export const PRODUCTS_RESPONSE = { products: PRODUCTS, count: PRODUCTS.length, tags: TAGS }
export const AVAILABILITY = [
{ id: 2, price: 215, marketPrice: 220, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: false },
{ id: 5, price: 15, marketPrice: 20, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: false },
{ id: 6, price: 400, marketPrice: 450, flashPrice: null, isFlashAvailable: false, isOutOfStock: true, isSuspended: false, isOffer: false },
{ id: 7, price: 199, marketPrice: 260, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: true },
{ id: 8, price: 90, marketPrice: 100, flashPrice: 75, isFlashAvailable: true, isOutOfStock: false, isSuspended: false, isOffer: false },
{ id: 9, price: 10, marketPrice: null, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: false },
{ id: 10, price: 50, marketPrice: 60, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: false },
{ id: 150, price: 599, marketPrice: 700, flashPrice: null, isFlashAvailable: false, isOutOfStock: false, isSuspended: false, isOffer: false },
]
export const AVAILABILITY_RESPONSE = { availability: AVAILABILITY, count: AVAILABILITY.length }
/** `useAllProducts` merges availability into products; the cart store expects this shape. */
export const MERGED_PRODUCTS = PRODUCTS.map((product) => {
const availability = AVAILABILITY.find((entry) => entry.id === product.id)
return {
...product,
price: availability ? Number(availability.price) : 0,
marketPrice: availability?.marketPrice ?? null,
flashPrice: availability?.flashPrice ?? null,
isFlashAvailable: availability?.isFlashAvailable ?? false,
isOutOfStock: availability?.isOutOfStock ?? false,
isSuspended: availability?.isSuspended ?? false,
isOffer: availability?.isOffer ?? false,
}
}).filter((product) => !product.isComboOnly)
/* -------------------------------------------------------------------------- */
/* Slots */
/* -------------------------------------------------------------------------- */
const HOUR = 60 * 60 * 1000
export function makeSlots(now: number = Date.now()) {
const iso = (offsetMs: number) => new Date(now + offsetMs).toISOString()
return [
{ id: 1849, deliveryTime: iso(2 * HOUR), freezeTime: iso(1 * HOUR), products: [{ id: 2, images: ['chicken.jpg'] }, { id: 5, images: ['cucumber.jpg'] }] },
{ id: 1850, deliveryTime: iso(4 * HOUR), freezeTime: iso(3 * HOUR), products: [{ id: 2, images: ['chicken.jpg'] }, { id: 8, images: ['paneer.jpg'] }] },
{ id: 1851, deliveryTime: iso(-2 * HOUR), freezeTime: iso(-3 * HOUR), products: [{ id: 2, images: ['chicken.jpg'] }] },
{ id: 1852, deliveryTime: iso(6 * HOUR), freezeTime: iso(5 * HOUR), products: [{ id: 2, images: ['chicken.jpg'] }, { id: 5, images: ['cucumber.jpg'] }, { id: 8, images: ['paneer.jpg'] }] },
]
}
export const SLOTS = makeSlots()
export const PRODUCT_AVAILABILITY = PRODUCTS.map((product) => ({ id: product.id }))
export function slotsResponse(slots = SLOTS) {
return { slots, productAvailability: PRODUCT_AVAILABILITY, count: slots.length }
}
export const SLOTS_RESPONSE = slotsResponse()
/* -------------------------------------------------------------------------- */
/* Stores */
/* -------------------------------------------------------------------------- */
export const STORES = [
{
id: 1,
name: 'The Freshyo Meat House',
description: 'Fresh meat and produce',
signedImageUrl: 'https://assets.test/store1.jpg',
productCount: 12,
sampleProducts: [
{ id: 2, name: 'Chicken Breast', signedImageUrl: 'https://assets.test/chicken.jpg' },
{ id: 5, name: 'Cucumber', signedImageUrl: 'https://assets.test/cucumber.jpg' },
],
},
{
id: 2,
name: 'Freshyo Greens',
description: 'Vegetables only',
signedImageUrl: null,
productCount: 2,
sampleProducts: [{ id: 5, name: 'Cucumber', signedImageUrl: 'https://assets.test/cucumber.jpg' }],
},
]
export const STORES_RESPONSE = { stores: STORES }
export const STORE_DETAIL_1 = {
store: { id: 1, name: 'The Freshyo Meat House', description: 'Fresh meat and produce', signedImageUrl: 'https://assets.test/store1.jpg' },
products: [P_CHICKEN, P_CUCUMBER],
tags: [
{ id: 1, tagName: 'Chicken', tagDescription: null, productIds: [2] },
{ id: 2, tagName: 'Veg', tagDescription: null, productIds: [5] },
],
}
/* -------------------------------------------------------------------------- */
/* Cart */
/* -------------------------------------------------------------------------- */
export const CART_REG = JSON.stringify([
{ id: 1, skuId: 2, quantity: 2, slotId: 1849, addedAt: new Date().toISOString() },
])
export const CART_FLASH = JSON.stringify([
{ id: 1, skuId: 8, quantity: 1, slotId: 0, addedAt: new Date().toISOString() },
])
/* -------------------------------------------------------------------------- */
/* Addresses */
/* -------------------------------------------------------------------------- */
export const A1 = {
id: 11,
name: 'Home',
mobile: '9876543210',
line1: '12 Main Road',
line2: 'Near Temple',
city: 'Mahabubnagar',
state: 'Telangana',
pincode: '509001',
regionId: 1,
boundId: 7,
isDefault: true,
latitude: 17.0,
longitude: 78.0,
googleMapsUrl: null,
}
export const A2 = {
id: 12,
name: 'Work',
mobile: '9876543211',
line1: '45 Office Street',
line2: null,
city: 'Hyderabad',
state: 'Telangana',
pincode: '500001',
regionId: 2,
boundId: 8,
isDefault: false,
latitude: 18.0,
longitude: 79.0,
googleMapsUrl: null,
}
export const A3 = {
id: 13,
name: 'NoRegion',
mobile: '9876543212',
line1: 'Somewhere',
line2: null,
city: 'Nowhere',
state: 'Telangana',
pincode: '500002',
regionId: null,
boundId: null,
isDefault: false,
latitude: null,
longitude: null,
googleMapsUrl: null,
}
export const ADDRESSES = [A1, A2, A3]
export const ADDRESSES_RESPONSE = { data: ADDRESSES }
/* -------------------------------------------------------------------------- */
/* Coupons */
/* -------------------------------------------------------------------------- */
export const C1 = { id: 21, couponCode: 'SAVE10', discountPercent: '10', maxValue: 50, minOrder: null, flatDiscount: null, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 1 }
export const C2 = { id: 22, couponCode: 'FLAT100', discountPercent: null, maxValue: null, minOrder: null, flatDiscount: 100, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 1 }
export const C3 = { id: 23, couponCode: 'MIN1000', discountPercent: null, maxValue: null, minOrder: 1000, flatDiscount: 50, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 1 }
export const C4 = { id: 24, couponCode: 'TARGET10', discountPercent: '10', maxValue: 40, minOrder: null, flatDiscount: null, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [2], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 1 }
export const C5 = { id: 25, couponCode: 'EXCLUSIVE', discountPercent: null, maxValue: null, minOrder: null, flatDiscount: 20, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: true, firstOrderOnly: false, regionId: 1 }
export const C6 = { id: 26, couponCode: 'USED', discountPercent: '10', maxValue: 30, minOrder: null, flatDiscount: null, validTill: null, isApplyForAll: true, isInvalidated: false, maxLimitForUser: 1, usedCount: 1, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 1 }
export const C7 = { id: 27, couponCode: 'OTHERREGION', discountPercent: '10', maxValue: 30, minOrder: null, flatDiscount: null, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: false, regionId: 2 }
export const C8 = { id: 28, couponCode: 'FIRST', discountPercent: null, maxValue: null, minOrder: null, flatDiscount: 40, validTill: null, isApplyForAll: true, isInvalidated: false, skuIds: [], applicableUsers: [], isExclusive: false, firstOrderOnly: true, regionId: 1 }
export const COUPONS = [C1, C2, C3, C4, C5, C6, C7, C8]
export const ELIGIBLE_COUPONS_RESPONSE = { data: COUPONS, isFirstOrder: true }
export const MY_COUPONS_RESPONSE = {
data: {
personal: [{ ...C4, status: 'available', maxLimitForUser: 3, usedCount: 1 }],
general: [C1, { ...C6, status: 'used' }],
},
}
/* -------------------------------------------------------------------------- */
/* Orders */
/* -------------------------------------------------------------------------- */
const ORDER_ITEMS = [
{ id: 1, skuId: 2, name: 'Chicken Breast', quantity: 2, unit: '500g', price: 215, image: 'chicken.jpg', isPackaged: false, isVerified: false },
{ id: 2, skuId: 5, name: 'Cucumber', quantity: 1, unit: '500g', price: 15, image: 'cucumber.jpg', isPackaged: true, isVerified: false },
]
export const O1 = {
orderId: 'ORD-1001',
id: 1001,
readableId: 101,
orderStatus: 'pending',
deliveryStatus: 'pending',
deliveryType: 'regular',
orderAmount: 445,
totalAmount: 445,
subtotal: 445,
discountAmount: 0,
deliveryCharge: 15,
couponCode: null,
orderDate: new Date().toISOString(),
createdAt: new Date().toISOString(),
deliveryDate: new Date(Date.now() + 7200000).toISOString(),
regionId: 1,
regionName: 'Mahabubnagar',
userNotes: null,
adminNotes: null,
items: ORDER_ITEMS,
user: { id: 5, name: 'Test User', mobile: '9876543210' },
address: { line1: '12 Main Road', city: 'Mahabubnagar', state: 'Telangana', pincode: '509001' },
}
export const O2 = {
...O1,
orderId: 'ORD-1002',
id: 1002,
readableId: 102,
deliveryType: 'flash',
orderStatus: 'pending',
orderAmount: 90,
totalAmount: 90,
deliveryCharge: 0,
}
export const O3 = {
...O1,
orderId: 'ORD-1003',
id: 1003,
readableId: 103,
orderStatus: 'cancelled',
deliveryStatus: 'cancelled',
cancellationReason: 'Customer requested',
}
export const O4 = {
...O1,
orderId: 'ORD-1004',
id: 1004,
readableId: 104,
orderStatus: 'success',
deliveryStatus: 'success',
}
export const O5 = {
...O1,
orderId: 'ORD-1005',
id: 1005,
readableId: 105,
items: [...ORDER_ITEMS, { id: 3, skuId: 8, name: 'Paneer', quantity: 1, unit: '200g', price: 90, image: 'paneer.jpg', isPackaged: false, isVerified: false }],
}
export const O6 = {
...O1,
orderId: 'ORD-1006',
id: 1006,
readableId: 106,
userNotes: 'Leave at the door',
couponCode: 'SAVE10',
discountAmount: 43,
deliveryCharge: 15,
}
export const ORDERS = [O1, O2, O3, O4, O5, O6]
export const ORDERS_RESPONSE = { data: ORDERS, pagination: { totalPages: 1, total: ORDERS.length, page: 1, pageSize: 10 } }
/* -------------------------------------------------------------------------- */
/* Complaints / reviews / user */
/* -------------------------------------------------------------------------- */
export const AUTH_USER = { id: 5, name: 'Test User', email: 'test@example.com', mobile: '9876543210' }
/** A decodable (unverified) JWT whose payload carries `id: 5`. */
export const TEST_JWT = `header.${Buffer.from(JSON.stringify({ id: 5, userId: 5 })).toString('base64url')}.signature`
export const AUTH_USER_FULL = {
...AUTH_USER,
profileImage: 'https://assets.test/profile.jpg',
createdAt: new Date().toISOString(),
bio: null,
dateOfBirth: null,
gender: null,
occupation: null,
}
export const SELF_DATA_RESPONSE = { data: { user: AUTH_USER_FULL } }
export const COMPLAINTS = [
{ id: 1, orderId: 'ORD-1001', complaintBody: 'Late delivery', complaintImages: [], complaintStatus: 'pending', complaintResponse: null, createdAt: new Date().toISOString(), user: AUTH_USER },
{ id: 2, orderId: null, complaintBody: 'App issue', complaintImages: ['issue.jpg'], complaintStatus: 'resolved', complaintResponse: 'We fixed it', createdAt: new Date().toISOString(), user: AUTH_USER },
]
export const COMPLAINTS_RESPONSE = { complaints: COMPLAINTS }
export const REVIEWS = [
{ id: 1, rating: 5, review: 'Great', reviewImages: [], adminResponse: null, user: { name: 'A' }, createdAt: new Date().toISOString() },
{ id: 2, rating: 3, review: 'Okay', reviewImages: [], adminResponse: 'Thanks', user: { name: 'B' }, createdAt: new Date().toISOString() },
]
export const REVIEWS_RESPONSE = { reviews: REVIEWS, hasMore: false, count: REVIEWS.length }
export const PRODUCT_DETAILS = {
...P_CHICKEN,
productId: 2,
longDescription: 'Tender boneless chicken breast.',
store: { id: 1, name: 'The Freshyo Meat House' },
reviews: REVIEWS,
averageRating: 4,
totalReviews: REVIEWS.length,
}
export const CART_SLOTS_RESPONSE: Record<number, any[]> = {
2: [SLOTS[0], SLOTS[1], SLOTS[3]],
5: [SLOTS[0], SLOTS[3]],
8: [SLOTS[1], SLOTS[3]],
}

View file

@ -0,0 +1,70 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Reset helpers. Call `resetAllMocks()` in `beforeEach` so no Zustand store,
* storage key, procedure fixture or navigation spy leaks between cases.
*/
import { resetTrpcMocks, seedDefaultProcedures } from '../mocks/trpc-client'
import { resetJsonMocks } from '../mocks/fetch-json'
import { __reset as resetSecureStore } from '../mocks/secure-store-mock'
import { __reset as resetLocation } from '../mocks/expo-location-mock'
import { __reset as resetNotifications } from '../mocks/expo-notifications-mock'
import { __resetRouterMock } from '../mocks/expo-router-mock'
import { __resetAuthState } from '../mocks/auth-context'
import { useAppStore } from '@/src/store/appStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useCartStore } from '@/src/store/cartStore'
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 { useCheckoutStore } from '@/src/store/checkoutStore'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useRegionStore } from '@/src/store/regionStore'
import { useLocationStore } from '@/src/store/locationStore'
import { useSlotStore } from '@/components/stores/slotStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
export function resetStores() {
useAppStore.setState({ hideTabsNav: {} })
useAddressStore.setState({ selectedAddressId: null })
useCartStore.setState({ addedToCartProduct: null })
useFlashCartStore.setState({ addedFlashProduct: null })
useNavigationStore.setState({ isNavigatedFromHome: false, selectedStoreId: null })
useQuickDeliveryStore.setState({ isDrawerHidden: false, selectedSlotId: null })
useStoreHeaderStore.setState({ title: '' })
useCheckoutStore.setState({ userNotes: '' })
useCentralProductStore.setState({ products: [], productsById: {}, refetchProducts: null })
useCentralSlotStore.setState({
slots: [],
productSlotsMap: {},
isSlotsLoaded: false,
refetchSlots: null,
})
useRegionStore.setState({
selectedRegionId: null,
selectedRegion: null,
selectedBoundId: null,
regionGeneration: 0,
})
useSlotStore.setState({ slotId: undefined, storeId: undefined })
useFlashNavigationStore.setState({ shouldNavigateToCart: false })
useLocationStore.getState().stop()
useLocationStore.setState({ coords: null, status: 'idle', error: null })
}
export function resetAllMocks() {
jest.clearAllMocks()
jest.useRealTimers()
resetStores()
resetTrpcMocks()
resetJsonMocks()
resetSecureStore()
resetLocation()
resetNotifications()
__resetRouterMock()
__resetAuthState()
}
export { seedDefaultProcedures }

View file

@ -0,0 +1,171 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import { render as rtlRender, RenderResult } from '@testing-library/react-native'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RefreshProvider } from 'common-ui'
import { AuthProvider } from '@/src/contexts/AuthContext'
import { setJsonResponse } from '../mocks/fetch-json'
import { __set as setSecureItem, __delete as deleteSecureItem } from '../mocks/secure-store-mock'
import {
AVAILABILITY_RESPONSE,
PRODUCT_AVAILABILITY,
PRODUCTS_RESPONSE,
SLOTS,
SLOTS_RESPONSE,
STORES_RESPONSE,
STORE_DETAIL_1,
MERGED_PRODUCTS,
AVAILABILITY,
TEST_JWT,
availabilityCacheUrl,
productsCacheUrl,
slotsCacheUrl,
storeDetailCacheUrl,
storesCacheUrl,
A1,
REGION_1,
} from '../fixtures'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
export function createTestQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: Infinity,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false },
},
})
}
type AuthMode = 'in' | 'out' | false
export interface RenderOptions {
queryClient?: QueryClient
auth?: AuthMode
withRefresh?: boolean
userId?: string
token?: string
}
export function seedAuthStorage(mode: AuthMode, userId = '5', token = TEST_JWT) {
if (mode === 'in') {
setSecureItem('authToken', token)
setSecureItem('userId', userId)
} else {
deleteSecureItem('authToken')
deleteSecureItem('userId')
}
}
export interface RenderWithProvidersResult extends RenderResult {
queryClient: QueryClient
}
export function renderWithProviders(
ui: React.ReactElement,
options: RenderOptions = {}
): RenderWithProvidersResult {
const queryClient = options.queryClient ?? createTestQueryClient()
const auth = options.auth ?? 'out'
const withRefresh = options.withRefresh ?? true
if (auth !== false) {
// Synchronous seeding so AuthProvider's bootstrap effect reads the token.
seedAuthStorage(auth, options.userId, options.token)
}
const Wrapper = ({ children }: { children: React.ReactNode }) => {
let tree: React.ReactElement = React.createElement(React.Fragment, null, children)
if (auth !== false) {
tree = React.createElement(AuthProvider, null, tree)
}
if (withRefresh) {
tree = React.createElement(RefreshProvider, { queryClient, children: tree } as any)
}
tree = React.createElement(QueryClientProvider, { client: queryClient }, tree)
return tree
}
const result = rtlRender(ui, { wrapper: Wrapper })
return { ...result, queryClient }
}
/** Render and let queued effects / microtasks settle. */
export async function renderAndFlush(
ui: React.ReactElement,
options: RenderOptions = {}
): Promise<RenderWithProvidersResult> {
const result = renderWithProviders(ui, options)
await flush()
return result
}
/** Await a macrotask so promise chains and effects settle. */
export async function flush(times = 1) {
const { act } = require('@testing-library/react-native')
for (let index = 0; index < times; index += 1) {
// eslint-disable-next-line no-await-in-loop
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
}
}
/**
* Register the standard regional CDN documents. Override any of them by calling
* `setJsonResponse` again *after* this helper (later registrations win).
*/
export function seedJsonCache(overrides: {
products?: any
availability?: any
slots?: any
stores?: any
storeDetail?: any
regionId?: number
} = {}) {
const regionId = overrides.regionId ?? 1
setJsonResponse(productsCacheUrl(regionId), overrides.products ?? PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(regionId), overrides.availability ?? AVAILABILITY_RESPONSE)
setJsonResponse(slotsCacheUrl(regionId), overrides.slots ?? SLOTS_RESPONSE)
setJsonResponse(`${slotsCacheUrl(regionId)}?v=123`, overrides.slots ?? SLOTS_RESPONSE)
setJsonResponse(storesCacheUrl(regionId), overrides.stores ?? STORES_RESPONSE)
setJsonResponse(storeDetailCacheUrl(1, regionId), overrides.storeDetail ?? STORE_DETAIL_1)
setJsonResponse(storeDetailCacheUrl(2, regionId), overrides.storeDetail ?? STORE_DETAIL_1)
}
/** Populate the central product/slot stores so `useGetCart` can enrich lines. */
export function seedCentralStores(options: { products?: any[]; slots?: any[] } = {}) {
const products = options.products ?? MERGED_PRODUCTS
useCentralProductStore.getState().setProducts(products)
useCentralSlotStore
.getState()
.setSlotsData((options.slots ?? SLOTS) as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any)
}
/** Select a browsing region (+ bound) without going through the location flow. */
export function seedRegion(region = REGION_1, boundId: number | null = 7) {
useRegionStore.getState().setRegion(region as any, boundId)
}
export function seedSelectedAddress(addressId: number | null = A1.id) {
useAddressStore.getState().setSelectedAddressId(addressId)
}
/** Convenience: the usual home/cart boot state (region + catalogue + cache). */
export function seedBoot(options: { auth?: AuthMode; addressId?: number | null } = {}) {
seedJsonCache()
seedCentralStores()
seedRegion()
seedSelectedAddress(options.addressId ?? null)
}
export function setConsoleErrorMock() {
return jest.spyOn(console, 'error').mockImplementation(() => undefined)
}

View file

@ -0,0 +1,109 @@
/* eslint-disable */
const path = require('path')
const appRoot = path.resolve(__dirname, '..')
const repoRoot = path.resolve(__dirname, '../../..')
// Packages that ship untranspiled ESM/JSX and must run through babel.
const transformAllowList = [
'(jest-)?react-native',
'@react-native(-community)?',
'expo(nent)?',
'@expo(nent)?/.*',
'@expo-google-fonts/.*',
'react-navigation',
'@react-navigation/.*',
'@unimodules/.*',
'unimodules',
'sentry-expo',
'native-base',
'react-native-svg',
'react-native-reanimated',
'react-native-gesture-handler',
'react-native-toast-message',
'react-native-webview',
'react-native-element-dropdown',
'react-native-keyboard-aware-scroll-view',
'react-native-pager-view',
'react-native-paper',
'react-native-razorpay',
'react-native-phonepe-pg',
'@react-native-google-signin/.*',
'twrnc',
'@trpc/.*',
'@tanstack/.*',
'zustand',
'formik',
'jwt-decode',
'@packages/.*',
'common-ui',
]
module.exports = {
preset: 'jest-expo',
rootDir: __dirname,
testMatch: ['<rootDir>/**/*.test.ts', '<rootDir>/**/*.test.tsx'],
setupFiles: [require.resolve('react-native-gesture-handler/jestSetup')],
setupFilesAfterEnv: [path.join(__dirname, 'setup.ts')],
transformIgnorePatterns: [
'/node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@sentry/react-native|native-base|react-native-svg|react-native-reanimated|react-native-gesture-handler|react-native-toast-message|react-native-webview|react-native-element-dropdown|react-native-keyboard-aware-scroll-view|react-native-pager-view|react-native-paper|react-native-razorpay|react-native-phonepe-pg|@react-native-google-signin/.*|@trpc/.*|@tanstack/.*|zustand|formik|jwt-decode|fuse.js|twrnc)',
'/node_modules/react-native-reanimated/plugin/',
],
moduleNameMapper: {
// Manual mocks first (order matters: moduleNameMapper is first-match-wins).
'^(.*/)?src/trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^\\./trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^\\.\\./trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^(.*/)?src/lib/fetch-json$': '<rootDir>/mocks/fetch-json.ts',
// Native / platform modules -> shared shims (every copy of a package, root
// or packages/ui/node_modules, resolves to the same mock).
'^react-native-reanimated$': path.join(repoRoot, 'node_modules/react-native-reanimated/mock.js'),
'^expo-secure-store$': '<rootDir>/mocks/native/secure-store.ts',
'^expo-location$': '<rootDir>/mocks/native/location.ts',
'^expo-notifications$': '<rootDir>/mocks/native/notifications.ts',
'^expo-constants$': '<rootDir>/mocks/native/constants.ts',
'^expo-auth-session/providers/google$': '<rootDir>/mocks/native/common.tsx',
'^expo-auth-session$': '<rootDir>/mocks/native/common.tsx',
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
'^expo-image$': '<rootDir>/mocks/native/common.tsx',
'^expo-linear-gradient$': '<rootDir>/mocks/native/common.tsx',
'^expo-blur$': '<rootDir>/mocks/native/common.tsx',
'^expo-status-bar$': '<rootDir>/mocks/native/common.tsx',
'^expo-font$': '<rootDir>/mocks/native/common.tsx',
'^expo-updates$': '<rootDir>/mocks/native/common.tsx',
'^expo-splash-screen$': '<rootDir>/mocks/native/common.tsx',
'^expo-web-browser$': '<rootDir>/mocks/native/common.tsx',
'^expo-linking$': '<rootDir>/mocks/native/common.tsx',
'^expo-haptics$': '<rootDir>/mocks/native/common.tsx',
'^expo-image-picker$': '<rootDir>/mocks/native/common.tsx',
'^expo-document-picker$': '<rootDir>/mocks/native/common.tsx',
'^expo-device$': '<rootDir>/mocks/native/common.tsx',
'^react-native-webview$': '<rootDir>/mocks/native/common.tsx',
'^react-native-safe-area-context$': '<rootDir>/mocks/native/common.tsx',
'^react-native-svg$': '<rootDir>/mocks/native/svg.tsx',
'^@react-native-community/datetimepicker$': '<rootDir>/mocks/native/datetimepicker.tsx',
'^@react-native-picker/picker$': '<rootDir>/mocks/native/picker.tsx',
'^react-native-toast-message$': '<rootDir>/mocks/native/toast-message.tsx',
'^react-native-razorpay$': '<rootDir>/mocks/native/razorpay.ts',
'^react-native-phonepe-pg$': '<rootDir>/mocks/native/phonepe.ts',
'^@react-native-google-signin/google-signin$': '<rootDir>/mocks/native/google-signin.ts',
'^@react-navigation/native$': '<rootDir>/mocks/native/react-navigation.tsx',
// Workspace packages.
'^@packages/shared$': path.join(repoRoot, 'packages/shared'),
'^@packages/shared/(.*)$': path.join(repoRoot, 'packages/shared') + '/$1',
'^common-ui$': path.join(repoRoot, 'packages/ui/index.ts'),
'^common-ui/(.*)$': path.join(repoRoot, 'packages/ui') + '/$1',
'^@backend/(.*)$': path.join(repoRoot, 'apps/backend/src') + '/$1',
// App-root alias.
'^@/(.*)$': appRoot + '/$1',
},
clearMocks: false,
restoreMocks: false,
fakeTimers: {
doNotFake: ['nextTick', 'queueMicrotask', 'setImmediate'],
},
testTimeout: 20000,
verbose: false,
maxWorkers: '50%',
}

View file

@ -0,0 +1,341 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 25 — "App helpers" (`tests/lib/app-helpers.test.tsx`).
*
* - REGSW-01..09 the region-switch side effects (`confirmRegionSwitch`)
* - PENDING-05..10 the signed-out address draft sync (`PendingAddressSync`)
* - CENTRAL-01..02 the central store wiring (`CentralStoreInitializer`)
*
* AuthContext is replaced with the deterministic mock so `PendingAddressSync`
* can be driven through exact auth states.
*/
import * as React from 'react'
import { Text } from 'react-native'
import { waitFor } from '@testing-library/react-native'
import { resetAllMocks } from '../helpers/reset'
import {
createTestQueryClient,
flush,
renderWithProviders,
seedCentralStores,
seedJsonCache,
seedRegion,
} from '../helpers/test-utils'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { lastProcedureInput, procedureInvalidations, procedureMutationCalls, setProcedure } from '../mocks/trpc-client'
import { jsonCallsFor } from '../mocks/fetch-json'
import { __setAuthState } from '../mocks/auth-context'
import { confirmRegionSwitch } from '@/src/lib/region-switch'
import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'
import { useCartStore } from '@/src/store/cartStore'
import { useFlashCartStore } from '@/src/store/flashCartStore'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useSlotStore } from '@/components/stores/slotStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
import CentralStoreInitializer from '@/src/components/CentralStoreInitializer'
import PendingAddressSync from '@/src/components/PendingAddressSync'
import { A1, AUTH_USER, CART_REG, MERGED_PRODUCTS, P_CHICKEN, productsCacheUrl, REGION_1, REGION_2 } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
const addedProduct = P_CHICKEN as any
const PENDING_INPUT = {
regionId: 1,
name: 'Home',
phone: '9876543210',
addressLine1: '12 Main Road',
addressLine2: 'Near Temple',
city: 'Mahabubnagar',
state: 'Telangana',
isDefault: true,
latitude: 17,
longitude: 78,
}
const pendingSnapshot = () => __snapshot().freshyo_pending_address
describe('app helpers', () => {
beforeEach(() => {
resetAllMocks()
})
it('REGSW-01: same region keeps both carts and the chosen address but clears selections/caches', async () => {
seedRegion(REGION_1 as any, 7)
__set('cart_items', CART_REG)
useAddressStore.getState().setSelectedAddressId(A1.id)
useQuickDeliveryStore.getState().setSelectedSlotId(1849)
useSlotStore.getState().setSlotId(1849)
useSlotStore.getState().setStoreId(2)
useCartStore.getState().setAddedToCartProduct(addedProduct)
useFlashCartStore.getState().setAddedFlashProduct(addedProduct)
useFlashNavigationStore.getState().setShouldNavigateToCart(true)
const queryClient = createTestQueryClient()
const removeSpy = jest.spyOn(queryClient, 'removeQueries')
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
const generationBefore = useRegionStore.getState().regionGeneration
await confirmRegionSwitch(REGION_1 as any, queryClient)
// Same-region switch must not touch the persisted carts or stash anything.
expect(__snapshot().cart_items).toBe(CART_REG)
expect(Object.keys(__snapshot()).some((key) => key.startsWith('region_carts_'))).toBe(false)
expect(useAddressStore.getState().selectedAddressId).toBe(A1.id)
expect(useRegionStore.getState().selectedRegionId).toBe(1)
expect(useRegionStore.getState().regionGeneration).toBe(generationBefore)
// ...but the in-memory selections/caches are still reset and queries refreshed.
expect(useQuickDeliveryStore.getState().selectedSlotId).toBeNull()
expect(useSlotStore.getState().slotId).toBeUndefined()
expect(useSlotStore.getState().storeId).toBeUndefined()
expect(useCartStore.getState().addedToCartProduct).toBeNull()
expect(useFlashCartStore.getState().addedFlashProduct).toBeNull()
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false)
expect(useCentralProductStore.getState().products).toEqual([])
expect(removeSpy).toHaveBeenCalledTimes(5)
expect(invalidateSpy).toHaveBeenCalledTimes(1)
})
it('REGSW-02: different region stashes the old carts, clears both and drops the address', async () => {
seedRegion(REGION_1 as any, 7)
__set('cart_items', CART_REG)
__set('flash_cart_items', '[]')
useAddressStore.getState().setSelectedAddressId(A1.id)
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
const snapshot = __snapshot()
expect(JSON.parse(snapshot.region_carts_1)).toEqual({
regular: [{ skuId: 2, slotId: 1849, quantity: 2 }],
flash: [],
})
expect(snapshot.cart_items).toBe('[]')
expect(snapshot.flash_cart_items).toBe('[]')
expect(useAddressStore.getState().selectedAddressId).toBeNull()
expect(useRegionStore.getState().selectedRegionId).toBe(REGION_2.id)
expect(useRegionStore.getState().selectedBoundId).toBe(8)
})
it('REGSW-03: no previous region does not stash anything', async () => {
__set('cart_items', CART_REG)
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
expect(Object.keys(__snapshot()).filter((key) => key.startsWith('region_carts_'))).toHaveLength(0)
expect(__snapshot().cart_items).toBe('[]')
})
it('REGSW-04: a known region restores its stashed carts', async () => {
seedRegion(REGION_1 as any, 7)
__set('region_carts_2', JSON.stringify({ regular: [{ skuId: 8, slotId: 0, quantity: 3 }], flash: [] }))
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
const items = JSON.parse(__snapshot().cart_items)
expect(items).toHaveLength(1)
expect(items[0]).toMatchObject({ skuId: 8, slotId: 0, quantity: 3 })
expect(items[0].id).toBe(1)
})
it('REGSW-05: resets the quick-delivery, slot, cart and flash stores', async () => {
seedRegion(REGION_1 as any, 7)
useQuickDeliveryStore.getState().setSelectedSlotId(1849)
useSlotStore.getState().setSlotId(1849)
useSlotStore.getState().setStoreId(2)
useCartStore.getState().setAddedToCartProduct(addedProduct)
useFlashCartStore.getState().setAddedFlashProduct(addedProduct)
useFlashNavigationStore.getState().setShouldNavigateToCart(true)
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
expect(useQuickDeliveryStore.getState().selectedSlotId).toBeNull()
expect(useSlotStore.getState().slotId).toBeUndefined()
expect(useSlotStore.getState().storeId).toBeUndefined()
expect(useCartStore.getState().addedToCartProduct).toBeNull()
expect(useFlashCartStore.getState().addedFlashProduct).toBeNull()
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false)
})
it('REGSW-06: clears the central product and slot stores', async () => {
seedRegion(REGION_1 as any, 7)
seedCentralStores()
expect(useCentralProductStore.getState().products.length).toBeGreaterThan(0)
expect(Object.keys(useCentralSlotStore.getState().productSlotsMap).length).toBeGreaterThan(0)
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient(), 8)
expect(useCentralProductStore.getState().products).toEqual([])
expect(useCentralProductStore.getState().productsById).toEqual({})
expect(useCentralSlotStore.getState().slots).toEqual([])
expect(useCentralSlotStore.getState().productSlotsMap).toEqual({})
})
it('REGSW-07: removes the region-scoped catalog queries', async () => {
seedRegion(REGION_1 as any, 7)
const queryClient = createTestQueryClient()
const removeSpy = jest.spyOn(queryClient, 'removeQueries')
await confirmRegionSwitch(REGION_2 as any, queryClient, 8)
for (const key of ['all-products', 'stores', 'slots', 'availability', 'store-with-products']) {
expect(removeSpy).toHaveBeenCalledWith({ queryKey: [key] })
}
})
it('REGSW-08: sets the new region, falling back to its effective bound', async () => {
seedRegion(REGION_1 as any, 7)
await confirmRegionSwitch(REGION_2 as any, createTestQueryClient())
expect(useRegionStore.getState().selectedRegionId).toBe(REGION_2.id)
expect(useRegionStore.getState().selectedBoundId).toBe(REGION_2.effectiveBoundId)
expect(REGION_2.effectiveBoundId).toBe(8)
})
it('REGSW-09: invalidates all queries after the switch', async () => {
seedRegion(REGION_1 as any, 7)
const queryClient = createTestQueryClient()
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
await confirmRegionSwitch(REGION_2 as any, queryClient, 8)
expect(invalidateSpy).toHaveBeenCalledTimes(1)
})
it('PENDING-05: signed out does not sync the pending address', async () => {
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
renderWithProviders(<PendingAddressSync />, { auth: false })
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(0)
expect(pendingSnapshot()).toBe(JSON.stringify(PENDING_INPUT))
})
it('PENDING-06: signed in posts the pending address, clears it and invalidates addresses', async () => {
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
renderWithProviders(<PendingAddressSync />, { auth: false })
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
expect(lastProcedureInput('user.address.createAddress')).toEqual(PENDING_INPUT)
expect(pendingSnapshot()).toBeUndefined()
expect(procedureInvalidations('user.address.getUserAddresses')).toHaveLength(1)
expect(procedureInvalidations('user.address.getDefaultAddress')).toHaveLength(1)
})
it('PENDING-07: signed in with no pending address creates nothing', async () => {
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
renderWithProviders(<PendingAddressSync />, { auth: false })
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(0)
})
it('PENDING-08: a failed create keeps the draft and a later mount retries', async () => {
setProcedure('user.address.createAddress', { mode: 'error', error: new Error('boom') })
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
const first = renderWithProviders(<PendingAddressSync />, { auth: false })
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
expect(pendingSnapshot()).toBe(JSON.stringify(PENDING_INPUT))
// Remount: a later authenticated mount retries the kept draft.
first.unmount()
renderWithProviders(<PendingAddressSync />, { auth: false })
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(2)
})
it('PENDING-09: concurrent auth events run one sync at a time', async () => {
setProcedure('user.address.createAddress', { mode: 'pending' })
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
const { rerender } = renderWithProviders(<PendingAddressSync />, { auth: false })
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
// Flip auth off and on again while the first create is still in flight.
__setAuthState({ isAuthenticated: false })
rerender(<PendingAddressSync />)
__setAuthState({ isAuthenticated: true })
rerender(<PendingAddressSync />)
await flush(3)
// The in-flight guard holds, so no second create is fired.
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
})
it('PENDING-10: unmounting before the read resolves cancels the sync', async () => {
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
const { unmount } = renderWithProviders(<PendingAddressSync />, { auth: false })
unmount()
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(0)
expect(pendingSnapshot()).toBe(JSON.stringify(PENDING_INPUT))
})
it('CENTRAL-01: the initializer populates the central stores and reconciles slots', async () => {
seedJsonCache()
seedRegion(REGION_1 as any, 7)
__set(
'cart_items',
JSON.stringify([{ id: 1, skuId: 2, quantity: 1, slotId: 9999, addedAt: new Date().toISOString() }])
)
const { getByText } = renderWithProviders(
<CentralStoreInitializer>
<Text>child</Text>
</CentralStoreInitializer>,
{ auth: false }
)
expect(getByText('child')).toBeTruthy()
await waitFor(() => expect(useCentralProductStore.getState().products).toHaveLength(MERGED_PRODUCTS.length))
await waitFor(() => expect(useCentralSlotStore.getState().isSlotsLoaded).toBe(true))
expect(useCentralSlotStore.getState().productSlotsMap[2].slots.length).toBeGreaterThan(0)
// Reconcile rewrites the stale slot to the product's earliest valid slot.
await waitFor(() => {
const items = JSON.parse(__snapshot().cart_items ?? '[]')
expect(items[0]?.slotId).toBe(1851)
})
})
it('CENTRAL-02: unmounting stops the initializer without further fetching', async () => {
seedJsonCache()
seedRegion(REGION_1 as any, 7)
const { unmount } = renderWithProviders(
<CentralStoreInitializer>
<Text>child</Text>
</CentralStoreInitializer>,
{ auth: false }
)
await waitFor(() => expect(useCentralProductStore.getState().products.length).toBeGreaterThan(0))
const callsBefore = jsonCallsFor(productsCacheUrl()).length
expect(callsBefore).toBeGreaterThan(0)
unmount()
await flush(2)
expect(jsonCallsFor(productsCacheUrl())).toHaveLength(callsBefore)
})
})

View file

@ -0,0 +1,284 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* AUTH-01..AUTH-17 from JEST-TEST-CASES.md section 25.
*
* These exercise the *real* `AuthProvider` from `src/contexts/AuthContext.tsx`
* (no `auth-context` mock here): the shared trpc procedure registry stands in
* for the network, `expo-secure-store` is the in-memory mock, and `expo-router`
* is recorded rather than navigated.
*/
import * as React from 'react'
import { Text } from 'react-native'
import { act, waitFor } from '@testing-library/react-native'
import { StorageService } from 'common-ui'
import { useAuth } from '@/src/contexts/AuthContext'
import { getAuthToken, getUserId } from '@/hooks/useJWT'
import constants from '@/src/constants'
import {
renderWithProviders,
flush,
createTestQueryClient,
} from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { router } from '../mocks/expo-router-mock'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { setProcedure, lastProcedureInput } from '../mocks/trpc-client'
import { AUTH_USER, AUTH_USER_FULL, TEST_JWT } from '../fixtures'
let ctx: any
function AuthProbe() {
ctx = useAuth()
return (
<Text testID="auth-state">
{`${ctx.isAuthenticated ? 'in' : 'out'}:${ctx.isLoading ? 'loading' : 'ready'}`}
</Text>
)
}
/** Run a context async action inside act, capturing a thrown error. */
async function invoke(action: (current: any) => Promise<void> | void) {
let error: unknown = null
await act(async () => {
try {
await action(ctx)
} catch (err) {
error = err
}
})
await flush(2)
return error
}
describe('AuthContext', () => {
beforeEach(() => resetAllMocks())
it('AUTH-01: starts signed out and not loading when there is no token/userId', async () => {
renderWithProviders(<AuthProbe />, { auth: 'out' })
await waitFor(() => expect(ctx.isLoading).toBe(false))
expect(ctx.isAuthenticated).toBe(false)
expect(ctx.token).toBeNull()
expect(ctx.user).toBeNull()
})
it('AUTH-02: is authenticated but still loading while getSelfData is pending', async () => {
setProcedure('user.user.getSelfData', { mode: 'pending' })
renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isAuthenticated).toBe(true))
expect(ctx.isLoading).toBe(true)
expect(ctx.token).toBe(TEST_JWT)
})
it('AUTH-03: populates user and userDetails from getSelfData', async () => {
renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isLoading).toBe(false))
expect(ctx.user.name).toBe('Test User')
expect(ctx.user.email).toBe('test@example.com')
expect(ctx.userDetails).toEqual(AUTH_USER_FULL)
})
it('AUTH-04: signs out when getSelfData fails but keeps the stored token', async () => {
setProcedure('user.user.getSelfData', {
mode: 'error',
error: new Error('unauthorized'),
})
renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isAuthenticated).toBe(false))
expect(ctx.isLoading).toBe(false)
// Current behaviour: deleteAuthToken() is commented out.
expect(__snapshot().authToken).toBe(TEST_JWT)
})
it('AUTH-05: loginWithToken stores token/userId and runs the redirect handler', async () => {
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
const error = await invoke((auth) =>
auth.loginWithToken('custom-token', { ...AUTH_USER, id: 9 })
)
expect(error).toBeNull()
expect(await getAuthToken()).toBe('custom-token')
expect(await getUserId()).toBe('9')
expect(ctx.isAuthenticated).toBe(true)
// No stored redirect state -> fall back to the previous screen.
expect(router.back).toHaveBeenCalled()
})
it('AUTH-06: surfaces a storage failure from loginWithToken and stops loading', async () => {
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
const spy = jest
.spyOn(StorageService, 'setItem')
.mockRejectedValueOnce(new Error('disk full'))
const error = await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any))
spy.mockRestore()
expect(error).toBeInstanceOf(Error)
expect(ctx.isLoading).toBe(false)
})
it('AUTH-07: login calls the login mutation, stores the token and marks the user in', async () => {
const credentials = { mobile: '9876543210' }
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
const error = await invoke((auth) => auth.login(credentials as any))
expect(error).toBeNull()
expect(lastProcedureInput('user.auth.login')).toEqual(credentials)
expect(await getAuthToken()).toBe('test-token')
expect(await getUserId()).toBe('5')
expect(ctx.isAuthenticated).toBe(true)
})
it('AUTH-08: login failure stops loading and rethrows', async () => {
setProcedure('user.auth.login', { mode: 'error', error: new Error('bad creds') })
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
const error = await invoke((auth) => auth.login({ mobile: '1' } as any))
expect(error).toBeInstanceOf(Error)
expect(ctx.isLoading).toBe(false)
})
it('AUTH-09: register calls the register mutation and stores the token', async () => {
const data = { mobile: '9876543210', otp: '1234', name: 'Test User' }
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
const error = await invoke((auth) => auth.register(data as any))
expect(error).toBeNull()
expect(lastProcedureInput('user.auth.register')).toEqual(data)
expect(await getAuthToken()).toBe('test-token')
expect(await getUserId()).toBe('5')
expect(ctx.isAuthenticated).toBe(true)
})
it('AUTH-10: register failure stops loading and rethrows', async () => {
setProcedure('user.auth.register', { mode: 'error', error: new Error('taken') })
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
const error = await invoke((auth) => auth.register({ mobile: '1' } as any))
expect(error).toBeInstanceOf(Error)
expect(ctx.isLoading).toBe(false)
})
it('AUTH-11: logout clears the token, the query client and the auth state', async () => {
const queryClient = createTestQueryClient()
renderWithProviders(<AuthProbe />, { auth: 'in', queryClient })
await flush()
const clearSpy = jest.spyOn(queryClient, 'clear')
await invoke((auth) => auth.logout())
expect(clearSpy).toHaveBeenCalled()
expect(__snapshot().authToken).toBeUndefined()
expect(ctx.isAuthenticated).toBe(false)
expect(ctx.user).toBeNull()
})
it('AUTH-12: logout still clears state and cache when deleting the token fails', async () => {
const queryClient = createTestQueryClient()
renderWithProviders(<AuthProbe />, { auth: 'in', queryClient })
await flush()
const clearSpy = jest.spyOn(queryClient, 'clear')
const spy = jest
.spyOn(StorageService, 'removeItem')
.mockRejectedValueOnce(new Error('offline'))
await invoke((auth) => auth.logout())
spy.mockRestore()
expect(clearSpy).toHaveBeenCalled()
expect(ctx.isAuthenticated).toBe(false)
expect(ctx.user).toBeNull()
})
it('AUTH-13: updateUser/updateUserDetails merge and are null safe', async () => {
const first = renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.userDetails).not.toBeNull())
act(() => ctx.updateUser({ name: 'Renamed' }))
expect(ctx.user.name).toBe('Renamed')
expect(ctx.user.email).toBe('test@example.com')
act(() => ctx.updateUserDetails({ bio: 'hello' } as any))
expect(ctx.userDetails.bio).toBe('hello')
first.unmount()
renderWithProviders(<AuthProbe />, { auth: 'out' })
await flush()
expect(ctx.user).toBeNull()
act(() => {
ctx.updateUser({ name: 'x' })
ctx.updateUserDetails({ bio: 'y' } as any)
})
expect(ctx.user).toBeNull()
expect(ctx.userDetails).toBeNull()
})
it('AUTH-14: valid redirect state removes the key and replaces with target + params', async () => {
__set(
constants.AUTH_REDIRECT_KEY,
JSON.stringify({
targetUrl: '/orders',
queryParams: { id: 1, drop: null },
timestamp: Date.now(),
})
)
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any))
await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/orders?id=1'))
expect(__snapshot()[constants.AUTH_REDIRECT_KEY]).toBeUndefined()
})
it('AUTH-15: redirect state older than 24h replaces with home', async () => {
__set(
constants.AUTH_REDIRECT_KEY,
JSON.stringify({
targetUrl: '/orders',
queryParams: {},
timestamp: Date.now() - 25 * 60 * 60 * 1000,
})
)
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any))
await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/'))
})
it('AUTH-16: no redirect state falls back to router.back()', async () => {
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any))
await waitFor(() => expect(router.back).toHaveBeenCalled())
expect(router.replace).not.toHaveBeenCalled()
})
it('AUTH-17: corrupt redirect JSON replaces with home', async () => {
__set(constants.AUTH_REDIRECT_KEY, 'not-json{')
renderWithProviders(<AuthProbe />, { auth: 'in' })
await flush()
await invoke((auth) => auth.loginWithToken('t', AUTH_USER as any))
await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/'))
})
})

View file

@ -0,0 +1,509 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Section 25 — Cart hook contract.
*
* Covers `apps/user-ui/hooks/cart-query-hooks.tsx`: the local-cart CRUD helpers
* behind `useAddToCart` / `useUpdateCartItem` / `useRemoveFromCart`, the
* `useGetCart` enrichment + totals, `useReconcileCartSlots`, and the exported
* per-region snapshot helpers (`clearLocalCart`, `stashRegionCarts`,
* `restoreRegionCarts`).
*
* The helpers talk to `StorageServiceCasual` directly, so every write lands in
* the in-memory secure-store mock and can be read back with `__snapshot()`.
*/
import * as React from 'react'
import { act, waitFor } from '@testing-library/react-native'
import { QueryClient } from '@tanstack/react-query'
import { StorageServiceCasual } from 'common-ui'
import {
useGetCart,
useAddToCart,
useUpdateCartItem,
useRemoveFromCart,
useReconcileCartSlots,
clearLocalCart,
stashRegionCarts,
restoreRegionCarts,
type CartType,
} from '@/hooks/cart-query-hooks'
import { renderWithProviders, seedCentralStores, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { MERGED_PRODUCTS } from '../fixtures'
const ADDED_AT = '2024-01-01T00:00:00.000Z'
const REGULAR_KEY = 'cart_items'
const FLASH_KEY = 'flash_cart_items'
const makeLine = (id: number, skuId: number, quantity: number, slotId: number) => ({
id,
skuId,
quantity,
slotId,
addedAt: ADDED_AT,
})
function seedCart(key: string, lines: any[]) {
__set(key, JSON.stringify(lines))
}
/** Read a cart (or region snapshot) straight out of the storage mock. */
function stored(key = REGULAR_KEY): any[] {
const raw = __snapshot()[key]
return raw ? JSON.parse(raw) : []
}
/* -------------------------------------------------------------------------- */
/* Probes: expose the hook's return value to the test body. */
/* -------------------------------------------------------------------------- */
interface ProbeApi {
current: any
}
function GetCartProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useGetCart({ refetchOnWindowFocus: false }, cartType)
return null
}
function AddProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useAddToCart({ showSuccessAlert: false, showErrorAlert: false }, cartType)
return null
}
function UpdateProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false }, cartType)
return null
}
function RemoveProbe({ api, cartType = 'regular' as CartType }: { api: ProbeApi; cartType?: CartType }) {
api.current = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false }, cartType)
return null
}
function ReconcileProbe() {
useReconcileCartSlots()
return null
}
/** Let an async mutation settle inside `act`. */
async function run<T>(fn: () => Promise<T>): Promise<T | undefined> {
let result: T | undefined
await act(async () => {
result = await fn()
// Let react-query's notify manager `setTimeout(0)` flush inside `act`.
await new Promise((resolve) => setTimeout(resolve, 0))
})
return result
}
/**
* Same defaults as the shared harness client, except mutations use `gcTime: 0`.
* React Query's `Mutation` otherwise schedules a 5-minute GC timeout on
* unmount, which keeps the jest process alive after the run has finished.
*/
function createCartQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: Infinity,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false, gcTime: 0 },
},
})
}
function mount(ui: React.ReactElement, queryClient: QueryClient = createCartQueryClient()) {
return renderWithProviders(ui, { auth: false, queryClient })
}
describe('Cart query hooks', () => {
beforeEach(() => resetAllMocks())
it('CARTQ-01: add new item writes a storage line with id 1, quantity and slot', async () => {
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
await run(() => api.current.addToCartAsync(2, 2, 1849))
const lines = stored()
expect(lines).toHaveLength(1)
expect(lines[0]).toMatchObject({ id: 1, skuId: 2, quantity: 2, slotId: 1849 })
expect(lines[0].addedAt).toEqual(expect.any(String))
})
it('CARTQ-02: add existing SKU increments the quantity and moves the slot when provided', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
await run(() => api.current.addToCartAsync(2, 3, 1850))
expect(stored()).toHaveLength(1)
expect(stored()[0]).toMatchObject({ id: 1, skuId: 2, quantity: 5, slotId: 1850 })
})
it('CARTQ-03: adding an existing SKU without a slot leaves the slot unchanged', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
// The public `addToCart`/`addToCartAsync` guard slotId, but the raw mutation
// passes `undefined` through to `addToLocalCart`, which then keeps the slot.
await run(() => api.current.mutateAsync({ skuId: 2, quantity: 1, slotId: undefined } as any))
expect(stored()).toHaveLength(1)
expect(stored()[0]).toMatchObject({ id: 1, skuId: 2, quantity: 3, slotId: 1849 })
})
it('CARTQ-04: adding without a slot throws "slotId is required for adding to cart"', async () => {
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
expect(() => api.current.addToCart(2, 1)).toThrow('slotId is required for adding to cart')
expect(() => api.current.addToCartAsync(2, 1)).toThrow('slotId is required for adding to cart')
// Nothing reached storage.
expect(stored()).toEqual([])
})
it('CARTQ-05: new ids are allocated from the current maximum, not the length', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 1, 1849), makeLine(5, 5, 1, 1850)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} />)
await run(() => api.current.addToCartAsync(8, 1, 1852))
expect(stored().map((item) => item.id)).toEqual([1, 5, 6])
})
it('CARTQ-06: update item persists the new quantity', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<UpdateProbe api={api} />)
await run(() => api.current.updateCartItemAsync(1, 5))
expect(stored()).toHaveLength(1)
expect(stored()[0].quantity).toBe(5)
})
it('CARTQ-07: updating a missing item leaves the cart unchanged', async () => {
const seeded = [makeLine(1, 2, 2, 1849)]
seedCart(REGULAR_KEY, seeded)
const api: ProbeApi = { current: null }
mount(<UpdateProbe api={api} />)
await run(() => api.current.updateCartItemAsync(999, 5))
expect(stored()).toEqual(seeded)
})
it('CARTQ-08: remove filters the line out of the cart', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 1, 1850)])
const api: ProbeApi = { current: null }
mount(<RemoveProbe api={api} />)
await run(() => api.current.removeFromCartAsync(1))
expect(stored()).toEqual([makeLine(2, 5, 1, 1850)])
})
it('CARTQ-09: removing a missing item leaves the cart unchanged', async () => {
const seeded = [makeLine(1, 2, 2, 1849)]
seedCart(REGULAR_KEY, seeded)
const api: ProbeApi = { current: null }
mount(<RemoveProbe api={api} />)
await run(() => api.current.removeFromCartAsync(999))
expect(stored()).toEqual(seeded)
})
it('CARTQ-10: clearLocalCart stores an empty array', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
await clearLocalCart('regular')
expect(stored()).toEqual([])
expect(JSON.parse(__snapshot()[REGULAR_KEY])).toEqual([])
})
it('CARTQ-11: the flash cart is stored separately and leaves the regular cart alone', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<AddProbe api={api} cartType="flash" />)
await run(() => api.current.addToCartAsync(8, 3, 0))
expect(stored(FLASH_KEY)).toEqual([expect.objectContaining({ id: 1, skuId: 8, quantity: 3, slotId: 0 })])
expect(stored(REGULAR_KEY)).toEqual([makeLine(1, 2, 2, 1849)])
})
it('CARTQ-12: corrupt cart JSON surfaces as an error and is left in place (no fallback)', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [] as any)
__set(REGULAR_KEY, '{not json')
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.error).toBeTruthy())
expect(api.current.error).toBeInstanceOf(Error)
expect(api.current.data).toBeUndefined()
// Current behaviour: no fallback — the corrupt blob is not repaired.
expect(__snapshot()[REGULAR_KEY]).toBe('{not json')
})
it('CARTQ-13: useGetCart enriches lines from the central product store', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
// P_CHICKEN (id 2) price 215 -> subtotal 215 * 2.
// Current behaviour: the enriched line surfaces only the six cart fields;
// the product's name / unitNotation / marketPrice feed the lookup but are
// not part of the returned line shape.
expect(api.current.cartItems).toEqual([
{
id: 1,
skuId: 2,
quantity: 2,
addedAt: ADDED_AT,
subtotal: 430,
slotId: 1849,
},
])
expect(api.current.data.items).toEqual(api.current.cartItems)
})
it('CARTQ-14: a line whose product is missing from the store is hidden', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 999, 1, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toEqual([])
expect(api.current.isEmpty).toBe(true)
expect(api.current.hasItems).toBe(false)
})
it('CARTQ-15: a line whose SKU has no slot entry is hidden', async () => {
// Product 777 exists in the product store but not in PRODUCT_AVAILABILITY,
// so it never appears in `productSlotsMap`.
const ghost = { ...MERGED_PRODUCTS[0], id: 777, name: 'Ghost Product' }
seedCentralStores({ products: [...MERGED_PRODUCTS, ghost] })
seedCart(REGULAR_KEY, [makeLine(1, 777, 1, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toEqual([])
expect(api.current.isEmpty).toBe(true)
})
it('CARTQ-16: a zero-quantity line is preserved', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 0, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toHaveLength(1)
expect(api.current.cartItems[0]).toMatchObject({ quantity: 0, subtotal: 0 })
expect(api.current.isEmpty).toBe(false)
})
it('CARTQ-17: the query stays disabled (loading false, no data) until products load', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await flush()
// No products in the central store -> `enabled` is false, so the query never
// fetches: React Query reports `isLoading === false` and no data.
expect(api.current.isLoading).toBe(false)
expect(api.current.data).toBeUndefined()
act(() => {
seedCentralStores()
})
await waitFor(() => expect(api.current.data).toBeDefined())
expect(api.current.cartItems).toHaveLength(1)
})
it('CARTQ-18: totals sum the enriched subtotals', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 4, 1850)])
const api: ProbeApi = { current: null }
mount(<GetCartProbe api={api} />)
await waitFor(() => expect(api.current.data).toBeDefined())
// 215 * 2 + 15 * 4 = 490
expect(api.current.cartItems.map((item: any) => item.subtotal)).toEqual([430, 60])
expect(api.current.totalItems).toBe(2)
expect(api.current.totalPrice).toBe(490)
expect(api.current.data.totalItems).toBe(2)
expect(api.current.data.totalAmount).toBe(490)
})
it('CARTQ-19: reconcile keeps a line whose slot is still valid', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(stored()).toEqual([makeLine(1, 2, 2, 1849)])
expect(invalidate).not.toHaveBeenCalled()
})
it('CARTQ-20: reconcile moves an invalid slot to the nearest by delivery time', async () => {
seedCentralStores()
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 9999)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
mount(<ReconcileProbe />, queryClient)
// SKU 2 is served by slots 1849/1850/1851/1852; 1851 has the earliest
// deliveryTime (now - 2h), so it is the "nearest".
await waitFor(() => expect(stored()[0].slotId).toBe(1851))
expect(invalidate).toHaveBeenCalledWith({ queryKey: ['local-cart-regular'] })
expect(stored()[0]).toMatchObject({ id: 1, skuId: 2, quantity: 2 })
})
it('CARTQ-21: reconcile keeps a line whose product has no slots at all', async () => {
seedCentralStores()
// P_NO_SLOT (id 10) exists in productAvailability but is in no delivery slot.
seedCart(REGULAR_KEY, [makeLine(1, 10, 2, 7)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(stored()).toEqual([makeLine(1, 10, 2, 7)])
expect(invalidate).not.toHaveBeenCalled()
})
it('CARTQ-22: reconcile does nothing while the slot store is not loaded', async () => {
// No `seedCentralStores()` -> isSlotsLoaded false and an empty productSlotsMap.
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 9999)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
const setItem = jest.spyOn(StorageServiceCasual, 'setItem')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(setItem).not.toHaveBeenCalled()
expect(invalidate).not.toHaveBeenCalled()
expect(stored()).toEqual([makeLine(1, 2, 2, 9999)])
})
it('CARTQ-23: reconcile writes nothing when every line is already valid', async () => {
seedCentralStores()
// SKU 2 is served by slots 1849/1850/1851/1852 and SKU 5 by 1849/1852, so
// both of these lines are already valid.
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 1, 1852)])
const queryClient = createCartQueryClient()
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
const setItem = jest.spyOn(StorageServiceCasual, 'setItem')
mount(<ReconcileProbe />, queryClient)
await flush(3)
expect(setItem).not.toHaveBeenCalled()
expect(invalidate).not.toHaveBeenCalled()
})
it('CARTQ-24: stashRegionCarts snapshots sku, slot and quantity for both carts', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849), makeLine(2, 5, 4, 1850)])
seedCart(FLASH_KEY, [makeLine(1, 8, 3, 0)])
await stashRegionCarts(1)
expect(stored('region_carts_1')).toEqual({
regular: [
{ skuId: 2, slotId: 1849, quantity: 2 },
{ skuId: 5, slotId: 1850, quantity: 4 },
],
flash: [{ skuId: 8, slotId: 0, quantity: 3 }],
})
})
it('CARTQ-25: restoreRegionCarts reissues ids and defaults missing/invalid quantities to 1', async () => {
__set(
'region_carts_2',
JSON.stringify({
regular: [
{ skuId: 2, slotId: 1849, quantity: 3 },
{ skuId: 5, slotId: 1850, quantity: 0 },
],
flash: [{ skuId: 8, slotId: 0 }],
})
)
await restoreRegionCarts(2)
const regular = stored(REGULAR_KEY)
expect(regular.map((item) => item.id)).toEqual([1, 2])
expect(regular.map((item) => [item.skuId, item.slotId, item.quantity])).toEqual([
[2, 1849, 3],
[5, 1850, 1],
])
expect(regular.every((item) => typeof item.addedAt === 'string')).toBe(true)
const flash = stored(FLASH_KEY)
expect(flash).toHaveLength(1)
expect(flash[0]).toMatchObject({ id: 1, skuId: 8, slotId: 0, quantity: 1 })
})
it('CARTQ-26: a corrupt region snapshot restores both carts to empty', async () => {
seedCart(REGULAR_KEY, [makeLine(1, 2, 2, 1849)])
seedCart(FLASH_KEY, [makeLine(1, 8, 3, 0)])
__set('region_carts_3', '{not json')
await restoreRegionCarts(3)
expect(stored(REGULAR_KEY)).toEqual([])
expect(stored(FLASH_KEY)).toEqual([])
})
it('CARTQ-27: stash -> clear -> restore round-trips a region switch', async () => {
const regular = [makeLine(1, 2, 2, 1849), makeLine(2, 5, 1, 1850)]
const flash = [makeLine(1, 8, 3, 0)]
seedCart(REGULAR_KEY, regular)
seedCart(FLASH_KEY, flash)
await stashRegionCarts(1)
await clearLocalCart('regular')
await clearLocalCart('flash')
expect(stored(REGULAR_KEY)).toEqual([])
expect(stored(FLASH_KEY)).toEqual([])
await restoreRegionCarts(1)
expect(stored(REGULAR_KEY).map((item) => [item.id, item.skuId, item.slotId, item.quantity])).toEqual([
[1, 2, 1849, 2],
[2, 5, 1850, 1],
])
expect(stored(FLASH_KEY).map((item) => [item.id, item.skuId, item.slotId, item.quantity])).toEqual([
[1, 8, 0, 3],
])
})
})

View file

@ -0,0 +1,136 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Harness self-test.
*
* Verifies the shared infrastructure the rest of the suite depends on:
* - the procedure registry (setProcedure / lastProcedureInput)
* - the regional CDN JSON mock behind `useAllProducts`
* - provider rendering + central-store seeding
* - the storage mock round-trip
*/
import * as React from 'react'
import { Text, View } from 'react-native'
import { waitFor } from '@testing-library/react-native'
import { trpc, setProcedure, lastProcedureInput, procedureMutationCalls } from '../mocks/trpc-client'
import { fetchJson } from '../mocks/fetch-json'
import { StorageService, StorageServiceCasual } from 'common-ui'
import { useAllProducts } from '@/src/hooks/prominent-api-hooks'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import {
renderWithProviders,
seedBoot,
seedJsonCache,
seedRegion,
createTestQueryClient,
} from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { productsCacheUrl, MERGED_PRODUCTS } from '../fixtures'
describe('test harness', () => {
beforeEach(() => {
resetAllMocks()
})
it('returns procedure defaults through the mock hooks', async () => {
function Probe() {
const { data, isLoading } = trpc.user.order.getOrders.useQuery({ page: 1, pageSize: 10 })
if (isLoading) return <Text>loading</Text>
return <Text>{`orders:${data?.data?.length ?? 0}`}</Text>
}
const { getByText } = renderWithProviders(<Probe />)
await waitFor(() => expect(getByText('orders:6')).toBeTruthy())
})
it('records mutation input for assertions', async () => {
function Probe() {
const mutation = trpc.user.auth.sendOtp.useMutation()
React.useEffect(() => {
mutation.mutate({ mobile: '9876543210' })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return <Text>probe</Text>
}
renderWithProviders(<Probe />)
await waitFor(() => expect(lastProcedureInput('user.auth.sendOtp')).toEqual({ mobile: '9876543210' }))
expect(procedureMutationCalls('user.auth.sendOtp')).toHaveLength(1)
})
it('overrides a procedure outcome per test', async () => {
setProcedure('user.auth.sendOtp', { mode: 'error', error: new Error('boom') })
function Probe() {
const mutation = trpc.user.auth.sendOtp.useMutation()
const [message, setMessage] = React.useState('idle')
React.useEffect(() => {
mutation.mutateAsync({ mobile: '1' }).catch((error: Error) => setMessage(error.message))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return <Text>{message}</Text>
}
const { getByText } = renderWithProviders(<Probe />)
await waitFor(() => expect(getByText('boom')).toBeTruthy())
})
it('loads regional products from the versioned CDN URL', async () => {
seedBoot()
function Probe() {
const { data, isLoading } = useAllProducts()
if (isLoading) return <Text>loading</Text>
return <Text>{`products:${data?.products?.length ?? 0}`}</Text>
}
const { getByText } = renderWithProviders(<Probe />, { auth: false })
await waitFor(() => expect(getByText(`products:${MERGED_PRODUCTS.length}`)).toBeTruthy())
const documents = await fetchJson(productsCacheUrl())
expect((documents as any).products).toHaveLength(9)
})
it('seeds the central product store for cart enrichment', () => {
seedBoot()
expect(useCentralProductStore.getState().products.length).toBe(MERGED_PRODUCTS.length)
expect(useCentralProductStore.getState().productsById[2]?.name).toBe('Chicken Breast')
})
it('round-trips secure storage', async () => {
await StorageService.setItem('authToken', 'token-1')
await StorageServiceCasual.setItem('cart_items', '[]')
expect(await StorageService.getItem('authToken')).toBe('token-1')
expect(await StorageServiceCasual.getItem('cart_items')).toBe('[]')
})
it('re-seeds defaults after a reset', async () => {
setProcedure('common.healthCheck', { mode: 'error' })
function Probe() {
const { data, isError } = trpc.common.healthCheck.useQuery()
return <Text>{isError ? 'error' : JSON.stringify(data)}</Text>
}
resetAllMocks()
const { getByText } = renderWithProviders(<Probe />, { auth: false })
await waitFor(() => expect(getByText(JSON.stringify({ ok: true, status: 'healthy' }))).toBeTruthy())
})
it('exposes the query client for invalidation assertions', async () => {
const queryClient = createTestQueryClient()
const { queryClient: returned } = renderWithProviders(<View />, { queryClient, auth: false })
expect(returned).toBe(queryClient)
expect(queryClient.getQueryCache().getAll()).toEqual([])
})
it('hydrates a region without a location round-trip', () => {
seedRegion()
expect(useCentralProductStore.getState().products).toEqual([])
})
it('registers the standard CDN documents', async () => {
seedJsonCache()
const doc: any = await fetchJson(productsCacheUrl())
expect(doc.count).toBe(9)
})
})

View file

@ -0,0 +1,170 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 25 — "Region and location" (`tests/lib/location-store.test.ts`).
*
* LOCSTORE-01..09: direct unit tests over the real `useLocationStore`.
* `resetAllMocks()` calls `stop()` (which bumps the module-level `activeToken`
* and clears `started`) so every case starts from a clean one-shot launch.
*/
import { resetAllMocks } from '../helpers/reset'
import { useLocationStore } from '@/src/store/locationStore'
import * as Location from '../mocks/expo-location-mock'
import { __configure } from '../mocks/expo-location-mock'
const store = () => useLocationStore.getState()
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
async function settle(times = 4) {
for (let index = 0; index < times; index += 1) {
// eslint-disable-next-line no-await-in-loop
await tick()
}
}
afterEach(() => {
jest.restoreAllMocks()
})
describe('locationStore', () => {
beforeEach(() => {
resetAllMocks()
})
it('LOCSTORE-01: start() takes a single permission + fix per launch', async () => {
const permission = jest.spyOn(Location, 'requestForegroundPermissionsAsync')
const fix = jest.spyOn(Location, 'getCurrentPositionAsync')
store().start()
await settle()
store().start() // second start must be a no-op
await settle()
expect(permission).toHaveBeenCalledTimes(1)
expect(fix).toHaveBeenCalledTimes(1)
expect(store().status).toBe('granted')
})
it('LOCSTORE-02: denied permission yields status denied with no coords', async () => {
__configure({ permission: 'denied' })
store().start()
await settle()
expect(store().status).toBe('denied')
expect(store().coords).toBeNull()
expect(store().error).toBeNull()
})
it('LOCSTORE-03: disabled services yield status services-off', async () => {
__configure({ permission: 'granted', servicesEnabled: false })
store().start()
await settle()
expect(store().status).toBe('services-off')
expect(store().coords).toBeNull()
})
it('LOCSTORE-04: success rounds coordinates to 5 decimal places', async () => {
__configure({
permission: 'granted',
servicesEnabled: true,
position: { coords: { latitude: 17.123456789, longitude: 78.987654321 }, timestamp: 1 },
})
store().start()
await settle()
expect(store().status).toBe('granted')
expect(store().coords).toEqual({ latitude: 17.12346, longitude: 78.98765 })
})
it('LOCSTORE-05: a hanging fix times out to unavailable with an error', async () => {
jest.useFakeTimers()
__configure({ permission: 'granted', servicesEnabled: true })
jest
.spyOn(Location, 'getCurrentPositionAsync')
.mockImplementation(() => new Promise<never>(() => {}))
store().start()
await jest.advanceTimersByTimeAsync(0)
expect(store().status).toBe('locating')
await jest.advanceTimersByTimeAsync(8000)
expect(store().status).toBe('unavailable')
expect(store().coords).toBeNull()
expect(store().error).toMatch(/timed out/i)
})
it('LOCSTORE-06: a stale in-flight fix is ignored after stop()', async () => {
__configure({ permission: 'granted', servicesEnabled: true })
let resolveFix: (position: any) => void = () => {}
const pending = new Promise((resolve) => {
resolveFix = resolve
})
jest.spyOn(Location, 'getCurrentPositionAsync').mockReturnValue(pending as any)
store().start()
await settle(2)
expect(store().status).toBe('locating')
store().stop()
expect(store().status).toBe('idle')
resolveFix({ coords: { latitude: 1, longitude: 2 }, timestamp: 1 })
await settle(2)
// The fix landed after the token was bumped, so it must be discarded.
expect(store().status).toBe('idle')
expect(store().coords).toBeNull()
})
it('LOCSTORE-07: stop() resets state and allows start() to run again', async () => {
__configure({ permission: 'granted', servicesEnabled: true })
const permission = jest.spyOn(Location, 'requestForegroundPermissionsAsync')
store().start()
await settle()
expect(store().status).toBe('granted')
store().stop()
expect(store().status).toBe('idle')
expect(store().coords).toBeNull()
expect(store().error).toBeNull()
store().start()
await settle()
expect(store().status).toBe('granted')
expect(permission).toHaveBeenCalledTimes(2)
})
it('LOCSTORE-08: probe() is true when permission is granted and services are on', async () => {
__configure({ permission: 'granted', servicesEnabled: true })
const permission = jest.spyOn(Location, 'getForegroundPermissionsAsync')
const fix = jest.spyOn(Location, 'getCurrentPositionAsync')
await expect(store().probe()).resolves.toBe(true)
expect(permission).toHaveBeenCalledTimes(1)
// probe() never takes a fix and never touches the read state.
expect(fix).not.toHaveBeenCalled()
expect(store().status).toBe('idle')
expect(store().coords).toBeNull()
})
it('LOCSTORE-09: probe() is false when denied / services off / throws, leaving state untouched', async () => {
__configure({ permission: 'denied' })
await expect(store().probe()).resolves.toBe(false)
__configure({ permission: 'granted', servicesEnabled: false })
await expect(store().probe()).resolves.toBe(false)
__configure({ permission: 'granted', servicesEnabled: true, throwOnPermission: true })
await expect(store().probe()).resolves.toBe(false)
expect(store().status).toBe('idle')
expect(store().coords).toBeNull()
expect(store().error).toBeNull()
})
})

View file

@ -0,0 +1,390 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-require-imports */
/**
* Section 25 "App helpers" — push notifications.
*
* Rows: NOTIF-01..07 (`registerForPushNotificationsAsync`),
* NOTIFC-01..05 (`NotificationProvider` + `NotifChecker`) and
* NOTIFR-01..07 (`NotifRegionSync`).
*
* Native swap-ins come from the shared mocks: `expo-notifications` is the
* configurable `tests/mocks/expo-notifications-mock`, `expo-device` defaults to a
* physical device and `expo-constants` carries a project id.
*
* `NotifRegionSync` reads the region through `useRegion` (covered by its own
* suite, `REGION-01..15`) so here it is replaced by a settable stub — otherwise
* every case would drag in the location fix + region resolve machinery.
*/
import * as React from 'react'
import { Linking, Modal, Platform } from 'react-native'
import { waitFor, fireEvent } from '@testing-library/react-native'
import { NOTIF_PERMISSION_DENIED } from 'common-ui/src/lib/const-strs'
import { registerForPushNotificationsAsync } from '@/services/notif-service/notif-register'
import {
NotificationProvider,
NotificationContext,
} from '@/services/notif-service/notif-context'
import NotifChecker from '@/services/notif-service/notif-checker'
import NotifRegionSync from '@/src/components/NotifRegionSync'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastProcedureInput,
procedureMutationCalls,
setProcedure,
} from '../mocks/trpc-client'
import {
__configure as configureNotifications,
getExpoPushTokenAsync,
requestPermissionsAsync,
setNotificationChannelAsync,
} from '../mocks/expo-notifications-mock'
import { __setAuthState } from '../mocks/auth-context'
import { AUTH_USER } from '../fixtures'
/**
* `NotifRegionSync`'s only region dependency. `jest.mock` hoists above the
* imports, but the stub object is read lazily at render time.
*/
const mockUseRegion: { regionId: number | null; bound: { id: number } | null } = {
regionId: null,
bound: null,
}
jest.mock('@/src/hooks/useRegion', () => ({
useRegion: () => ({
region: null,
regionId: mockUseRegion.regionId,
boundId: null,
bound: mockUseRegion.bound,
regionGeneration: 0,
hydrated: true,
coords: null,
locationStatus: 'granted',
isResolvingRegion: false,
setRegion: jest.fn(),
clearRegion: jest.fn(),
refreshLocation: jest.fn(),
}),
}))
// Deterministic auth for `NotifChecker` (same replacement the README documents).
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
const IOS: typeof Platform.OS = 'ios'
function setPlatform(os: typeof Platform.OS) {
;(Platform as any).OS = os
}
function renderChecker(auth: boolean) {
__setAuthState({
isAuthenticated: auth,
isLoading: false,
user: auth ? AUTH_USER : null,
})
return renderWithProviders(
<NotificationProvider>
<NotifChecker />
</NotificationProvider>,
{ auth: auth ? 'in' : 'out' }
)
}
interface RegionSyncState {
token: string | null
notifPermission: 'pending' | 'granted' | 'denied'
regionId?: number | null
bound?: { id: number } | null
}
/** Builds a *fresh* element so `rerender` never bails out on identity. */
function regionSyncElement(state: RegionSyncState) {
mockUseRegion.regionId = state.regionId ?? null
mockUseRegion.bound = state.bound ?? null
return (
<NotificationContext.Provider
value={
{
expoPushToken: state.token,
notification: null,
error: null,
notifPermission: state.notifPermission,
} as any
}
>
<NotifRegionSync />
</NotificationContext.Provider>
)
}
function renderRegionSync(state: RegionSyncState) {
return renderWithProviders(regionSyncElement(state), { auth: false })
}
describe('notification helpers', () => {
beforeEach(() => {
resetAllMocks()
})
afterEach(() => {
setPlatform(IOS)
})
describe('registerForPushNotificationsAsync', () => {
it('NOTIF-01: Android creates the default notification channel', async () => {
setPlatform('android')
const token = await registerForPushNotificationsAsync()
expect(setNotificationChannelAsync).toHaveBeenCalledWith(
'default',
expect.objectContaining({ name: 'default', importance: 5 })
)
expect(token).toBe('ExponentPushToken[test-token]')
})
it('NOTIF-02: an already granted permission is not re-requested', async () => {
configureNotifications({ permission: 'granted' })
const token = await registerForPushNotificationsAsync()
expect(requestPermissionsAsync).not.toHaveBeenCalled()
expect(getExpoPushTokenAsync).toHaveBeenCalledWith({ projectId: 'test-project-id' })
expect(token).toBe('ExponentPushToken[test-token]')
})
it('NOTIF-03: a permission granted after the request returns the Expo token', async () => {
configureNotifications({ permission: 'undetermined', requestResult: 'granted' })
const token = await registerForPushNotificationsAsync()
expect(requestPermissionsAsync).toHaveBeenCalledTimes(1)
expect(token).toBe('ExponentPushToken[test-token]')
})
it('NOTIF-04: a denied permission throws the permission error', async () => {
configureNotifications({ permission: 'denied', requestResult: 'denied' })
await expect(registerForPushNotificationsAsync()).rejects.toThrow(
NOTIF_PERMISSION_DENIED
)
expect(getExpoPushTokenAsync).not.toHaveBeenCalled()
})
it('NOTIF-05: a missing project id throws', async () => {
// Freshly required module so the local `expo-constants` stub (no project
// id anywhere) is the one `notif-register` captured.
let isolated: typeof import('@/services/notif-service/notif-register') | undefined
jest.isolateModules(() => {
jest.doMock('expo-constants', () => ({
__esModule: true,
default: { expoConfig: { extra: {} }, easConfig: {} },
Constants: { expoConfig: { extra: {} }, easConfig: {} },
}))
isolated = require('@/services/notif-service/notif-register')
})
await expect(isolated!.registerForPushNotificationsAsync()).rejects.toThrow(
'Project ID not found'
)
})
it('NOTIF-06: a non-physical device throws', async () => {
let isolated: typeof import('@/services/notif-service/notif-register') | undefined
jest.isolateModules(() => {
jest.doMock('expo-device', () => ({ __esModule: true, isDevice: false }))
isolated = require('@/services/notif-service/notif-register')
})
await expect(isolated!.registerForPushNotificationsAsync()).rejects.toThrow(
'Must use physical device for push notifications'
)
})
it('NOTIF-07: a failing getExpoPushToken is wrapped', async () => {
getExpoPushTokenAsync.mockRejectedValueOnce(new Error('token boom'))
// The wrap replaces the error but keeps its message.
await expect(registerForPushNotificationsAsync()).rejects.toThrow('token boom')
})
})
describe('NotificationProvider / NotifChecker', () => {
it('NOTIFC-01: a granted token is saved through savePushToken', async () => {
renderChecker(true)
await waitFor(() =>
expect(lastProcedureInput('user.user.savePushToken')).toEqual({
token: 'ExponentPushToken[test-token]',
})
)
expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1)
})
it('NOTIFC-02: a signed-out user still saves the token (current behaviour)', async () => {
// GAP: the effect lists `isAuthenticated` as a dependency but the guard
// never reads it, so the token is posted while signed out too. Pin the
// current behaviour; update when an auth check is added.
renderChecker(false)
await waitFor(() =>
expect(lastProcedureInput('user.user.savePushToken')).toEqual({
token: 'ExponentPushToken[test-token]',
})
)
})
it('NOTIFC-03: a denied permission opens the permission dialog', async () => {
configureNotifications({ permission: 'denied', requestResult: 'denied' })
const { getByText } = renderChecker(true)
await waitFor(() => expect(getByText('Notification Permission Denied')).toBeTruthy())
})
it('NOTIFC-04: the Settings button opens the device settings', async () => {
configureNotifications({ permission: 'denied', requestResult: 'denied' })
const openSettings = jest
.spyOn(Linking, 'openSettings')
.mockImplementation(async () => undefined)
const { getByText } = renderChecker(true)
await waitFor(() => expect(getByText('Notification Permission Denied')).toBeTruthy())
fireEvent.press(getByText('Settings'))
expect(openSettings).toHaveBeenCalledTimes(1)
})
it('NOTIFC-05: Cancel closes the dialog', async () => {
configureNotifications({ permission: 'denied', requestResult: 'denied' })
const { getByText, UNSAFE_getByType } = renderChecker(true)
await waitFor(() => expect(UNSAFE_getByType(Modal).props.visible).toBe(true))
fireEvent.press(getByText('Cancel'))
// NOTE: the RN Modal keeps its children mounted on iOS after the first
// show (`isRendered`), so the close state is asserted on the prop, not on
// the copy disappearing.
expect(UNSAFE_getByType(Modal).props.visible).toBe(false)
})
})
describe('NotifRegionSync', () => {
it('NOTIFR-01: no token, no region or a pending permission makes no call', async () => {
const cases: RegionSyncState[] = [
{ token: null, notifPermission: 'granted', regionId: 1 },
{ token: 'tok', notifPermission: 'granted', regionId: null },
{ token: 'tok', notifPermission: 'pending', regionId: 1 },
]
for (const state of cases) {
const view = renderRegionSync(state)
await flush()
expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(0)
expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(0)
view.unmount()
}
})
it('NOTIFR-02: a granted token + region saves the token with the region', async () => {
renderRegionSync({ token: 'tok', notifPermission: 'granted', regionId: 1 })
await waitFor(() =>
expect(lastProcedureInput('user.user.savePushToken')).toEqual({
token: 'tok',
regionId: 1,
})
)
expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(0)
})
it('NOTIFR-03: a location-derived bound also records the tracked region', async () => {
renderRegionSync({
token: 'tok',
notifPermission: 'granted',
regionId: 1,
bound: { id: 7 },
})
await waitFor(() =>
expect(lastProcedureInput('user.user.recordTrackedRegion')).toEqual({ regionId: 1 })
)
expect(lastProcedureInput('user.user.savePushToken')).toEqual({ token: 'tok', regionId: 1 })
})
it('NOTIFR-04: an address-derived region does not record a tracked region', async () => {
renderRegionSync({ token: 'tok', notifPermission: 'granted', regionId: 2, bound: null })
await waitFor(() =>
expect(lastProcedureInput('user.user.savePushToken')).toEqual({
token: 'tok',
regionId: 2,
})
)
expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(0)
})
it('NOTIFR-05: the same token/region/source is deduped', async () => {
const view = renderRegionSync({
token: 'tok',
notifPermission: 'granted',
regionId: 1,
bound: { id: 7 },
})
await waitFor(() => expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1))
// Another location bound for the same region re-runs the effect but keeps
// the (token, region, 'loc') key.
view.rerender(
regionSyncElement({
token: 'tok',
notifPermission: 'granted',
regionId: 1,
bound: { id: 9 },
})
)
await flush()
expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1)
expect(procedureMutationCalls('user.user.recordTrackedRegion')).toHaveLength(1)
})
it('NOTIFR-06: a region change triggers a new sync', async () => {
const view = renderRegionSync({
token: 'tok',
notifPermission: 'granted',
regionId: 1,
})
await waitFor(() => expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1))
view.rerender(
regionSyncElement({ token: 'tok', notifPermission: 'granted', regionId: 2 })
)
await waitFor(() =>
expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(2)
)
expect(lastProcedureInput('user.user.savePushToken')).toEqual({ token: 'tok', regionId: 2 })
})
it('NOTIFR-07: a failing save is logged and not retried', async () => {
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined)
setProcedure('user.user.savePushToken', { mode: 'error', error: new Error('save boom') })
renderRegionSync({ token: 'tok', notifPermission: 'granted', regionId: 1 })
await waitFor(() => expect(consoleError).toHaveBeenCalled())
const logged = consoleError.mock.calls.some((call) =>
String(call[0]).includes('[NotifRegionSync] saving the region with the push token failed')
)
expect(logged).toBe(true)
// Best-effort telemetry: one attempt, no retry.
await flush(3)
expect(procedureMutationCalls('user.user.savePushToken')).toHaveLength(1)
})
})
})

View file

@ -0,0 +1,347 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 25 — "Prominent API hooks" (`tests/lib/prominent-api-hooks.test.tsx`).
*
* API-01..19: the regional discovery layer (`src/hooks/prominent-api-hooks.ts`).
* CDN URLs are asserted through the `fetch-json` mock (`jsonCallsFor`), and the
* tRPC input through the procedure registry (`lastProcedureInput`).
*
* Location is forced `denied` so the `useRegion()` startup check never overrides
* the seeded region/bound while a hook is under test.
*/
import * as React from 'react'
import { act, waitFor } from '@testing-library/react-native'
import { resetAllMocks } from '../helpers/reset'
import {
renderWithProviders,
flush,
seedRegion,
seedSelectedAddress,
} from '../helpers/test-utils'
import {
setJsonResponse,
setJsonError,
jsonCalls,
jsonCallsFor,
} from '../mocks/fetch-json'
import {
setProcedure,
clearProcedure,
lastProcedureInput,
procedureCallCount,
} from '../mocks/trpc-client'
import { __set as setSecureItem } from '../mocks/secure-store-mock'
import { __setAuthState } from '../mocks/auth-context'
import { __configure as configureLocation } from '../mocks/expo-location-mock'
import {
useGetEssentialConsts,
useRegionalConsts,
useAllProducts,
useAvailability,
useStores,
useSlots,
useStoreWithProducts,
} from '@/src/hooks/prominent-api-hooks'
import { useRegionStore } from '@/src/store/regionStore'
import {
A1,
A2,
AVAILABILITY,
AVAILABILITY_RESPONSE,
CONSTS,
PRODUCTS,
PRODUCTS_RESPONSE,
REGION_1,
REGION_2,
SLOTS_RESPONSE,
STORES_RESPONSE,
STORE_DETAIL_1,
availabilityCacheUrl,
productsCacheUrl,
slotsCacheUrl,
storeDetailCacheUrl,
storesCacheUrl,
} from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
interface Probe<T> {
element: React.ReactElement
result: { current: T }
}
function makeProbe<T>(hook: () => T): Probe<T> {
const result: { current: T } = { current: null as any }
const Probe = () => {
result.current = hook()
return null
}
return { element: React.createElement(Probe), result }
}
describe('prominent API hooks', () => {
beforeEach(() => {
resetAllMocks()
configureLocation({ permission: 'denied' })
seedRegion(REGION_1 as any, 7)
})
it('API-01: queries essential consts for the active bound and reads the threshold', async () => {
const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data).toBeTruthy())
expect(lastProcedureInput('common.essentialConsts')).toEqual({ boundId: 7 })
expect(result.current.data!.freeDeliveryThreshold).toBe(249)
})
it('API-02: a same-region selected address bound overrides the active bound', async () => {
__setAuthState({ isAuthenticated: true, isLoading: false })
seedSelectedAddress(A1.id)
setProcedure('user.address.getUserAddresses', { data: { data: [{ ...A1, boundId: 8 }] } })
const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(lastProcedureInput('common.essentialConsts')).toEqual({ boundId: 8 }))
expect(result.current.data).toBeTruthy()
})
it('API-03: a selected address in another region is ignored', async () => {
__setAuthState({ isAuthenticated: true, isLoading: false })
seedSelectedAddress(A2.id)
const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data).toBeTruthy())
// A2 belongs to region 2, so the region-1 active bound (7) wins.
expect(lastProcedureInput('common.essentialConsts')).toEqual({ boundId: 7 })
})
it('API-04: with no region/bound the consts query stays disabled', async () => {
useRegionStore.getState().clearRegion()
const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false })
await flush(2)
expect(procedureCallCount('common.essentialConsts')).toBe(0)
expect(result.current.isLoading).toBe(false)
})
it('API-05: a cached consts payload per bound is a placeholder; corrupt cache is ignored', async () => {
clearProcedure('common.essentialConsts')
// Corrupt cache must not throw and must surface no placeholder.
setSecureItem('essential_consts_b7', 'not-json')
const corrupt = makeProbe(() => useGetEssentialConsts())
const corruptView = renderWithProviders(corrupt.element, { auth: false })
await flush(2)
expect(corrupt.result.current.data).toBeUndefined()
corruptView.unmount()
// A valid cached payload is served immediately as placeholder data.
setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 999 }))
const cached = makeProbe(() => useGetEssentialConsts())
renderWithProviders(cached.element, { auth: false })
await waitFor(() => expect(cached.result.current.data?.freeDeliveryThreshold).toBe(999))
})
it('API-06: the consts cache is keyed per bound (no cross-bound leak)', async () => {
clearProcedure('common.essentialConsts')
setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 }))
setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 222 }))
seedRegion(REGION_1 as any, 8)
const { element, result } = makeProbe(() => useGetEssentialConsts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.freeDeliveryThreshold).toBe(222))
expect(result.current.data!.freeDeliveryThreshold).not.toBe(111)
})
it('API-07: builds the versioned products CDN URL', async () => {
setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE)
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1))
expect(jsonCallsFor(productsCacheUrl())).toEqual([productsCacheUrl(1, 12)])
})
it('API-08: builds the availability-versioned CDN URL', async () => {
setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE)
const { element, result } = makeProbe(() => useAvailability())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.availability).toBeTruthy())
expect(jsonCallsFor(availabilityCacheUrl())).toEqual([availabilityCacheUrl(1, 34)])
})
it('API-09: builds the slots CDN URL with the ?v=123 suffix', async () => {
const slotsUrl = `${slotsCacheUrl()}?v=123`
setJsonResponse(slotsUrl, SLOTS_RESPONSE)
const { element, result } = makeProbe(() => useSlots())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.slots).toBeTruthy())
expect(jsonCallsFor(slotsUrl)).toEqual([slotsUrl])
})
it('API-10: builds the versioned stores CDN URL', async () => {
setJsonResponse(storesCacheUrl(), STORES_RESPONSE)
const { element, result } = makeProbe(() => useStores())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.stores).toBeTruthy())
expect(jsonCallsFor(storesCacheUrl())).toEqual([storesCacheUrl(1, 12)])
})
it('API-11: builds the versioned per-store detail CDN URL', async () => {
setJsonResponse(storeDetailCacheUrl(2), STORE_DETAIL_1)
const { element, result } = makeProbe(() => useStoreWithProducts(2))
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.store).toBeTruthy())
expect(jsonCallsFor(storeDetailCacheUrl(2))).toEqual([storeDetailCacheUrl(2, 1, 12)])
})
it('API-12: missing URL parts disable the hook and issue no fetch', async () => {
setProcedure('common.essentialConsts', { data: { ...CONSTS, assetsDomain: null } })
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await flush(3)
expect(jsonCalls()).toHaveLength(0)
expect(result.current.isLoading).toBe(false)
})
it('API-13: merges the availability row into each product', async () => {
const availability = AVAILABILITY.map((entry) =>
entry.id === 5 ? { ...entry, isSuspended: true } : entry
)
setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(), { availability, count: availability.length })
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1))
const byId = (id: number): any => result.current.data!.products.find((p: any) => p.id === id)
expect(byId(8)).toMatchObject({
price: 90,
marketPrice: 100,
flashPrice: 75,
isFlashAvailable: true,
})
expect(byId(6).isOutOfStock).toBe(true)
expect(byId(7).isOffer).toBe(true)
expect(byId(5).isSuspended).toBe(true)
})
it('API-14: a product without an availability row gets zeroed defaults', async () => {
const availability = AVAILABILITY.filter((entry) => entry.id !== 10)
setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(), { availability, count: availability.length })
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1))
const product = result.current.data!.products.find((p: any) => p.id === 10) as any
expect(product).toMatchObject({
price: 0,
marketPrice: null,
flashPrice: null,
isFlashAvailable: false,
isOutOfStock: false,
isSuspended: false,
isOffer: false,
})
})
it('API-15: combo-only SKUs are filtered out of the merged list', async () => {
setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE)
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1))
expect(result.current.data!.products.some((p: any) => p.id === 149)).toBe(false)
})
it('API-16: a products fetch error is surfaced', async () => {
setJsonResponse(availabilityCacheUrl(), AVAILABILITY_RESPONSE)
setJsonError(productsCacheUrl(), new Error('offline'))
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.isError).toBe(true))
expect(result.current.error?.message).toBe('offline')
})
it('API-17: when availability fails the products still render with defaults (current)', async () => {
setJsonResponse(productsCacheUrl(), PRODUCTS_RESPONSE)
setJsonError(availabilityCacheUrl(), new Error('avail-down'))
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.data?.products).toHaveLength(PRODUCTS.length - 1))
// The products query itself succeeded; each row falls back to the zeroed
// defaults because its availability entry was never fetched.
expect(result.current.isError).toBe(false)
const chicken = result.current.data!.products.find((p: any) => p.id === 2) as any
expect(chicken.price).toBe(0)
expect(chicken.marketPrice).toBeNull()
expect(chicken.isFlashAvailable).toBe(false)
})
it('API-18: a region change produces a new CDN URL / query key', async () => {
setProcedure('common.essentialConsts', {
impl: () => ({ ...CONSTS, regionId: useRegionStore.getState().selectedRegionId }),
})
setJsonResponse(productsCacheUrl(1), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(1), AVAILABILITY_RESPONSE)
setJsonResponse(productsCacheUrl(2), PRODUCTS_RESPONSE)
setJsonResponse(availabilityCacheUrl(2), AVAILABILITY_RESPONSE)
const { element, result } = makeProbe(() => useAllProducts())
renderWithProviders(element, { auth: false })
await waitFor(() => expect(jsonCallsFor(productsCacheUrl(1))).toHaveLength(1))
await act(async () => {
useRegionStore.getState().setRegion(REGION_2 as any, 8)
})
await waitFor(() => expect(jsonCallsFor(productsCacheUrl(2))).toHaveLength(1))
expect(result.current.data).toBeTruthy()
})
it('API-19: useRegionalConsts passes through the essential consts data', async () => {
const { element, result } = makeProbe(() => {
const essentialConsts = useGetEssentialConsts()
const regionalConsts = useRegionalConsts()
return { essentialConsts, regionalConsts }
})
renderWithProviders(element, { auth: false })
await waitFor(() => expect(result.current.regionalConsts).toBeTruthy())
expect(result.current.regionalConsts).toEqual(result.current.essentialConsts.data)
})
})

View file

@ -0,0 +1,453 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* ROUTE-*, JWT-*, TRPC-*, HIDE-*, PSI-*, PENDING-01..04, FETCH-01..04 from
* JEST-TEST-CASES.md section 25.
*
* Route/auth-gating cases use the deterministic `auth-context` mock. The trpc
* link and `fetch-json` cases load the *real* modules (the jest moduleNameMapper
* only rewrites the `@/src/...` bare specifier, so requiring the file with an
* explicit extension gives us the real implementation and a shared registry).
*/
import * as React from 'react'
import { Text, DeviceEventEmitter } from 'react-native'
import { act, waitFor } from '@testing-library/react-native'
import axios from 'axios'
import { StorageServiceCasual } from 'common-ui'
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
import { useAuthenticatedRoute } from '@/hooks/useAuthenticatedRoute'
import {
saveAuthToken,
getAuthToken,
deleteAuthToken,
saveUserId,
getUserId,
AUTH_TOKEN_KEY,
USER_ID_KEY,
} from '@/hooks/useJWT'
import { useHideTabNav } from '@/src/hooks/useHideTabNav'
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'
import {
savePendingAddress,
getPendingAddress,
clearPendingAddress,
} from '@/src/lib/pending-address'
import { useAppStore } from '@/src/store/appStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import constants from '@/src/constants'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { router } from '../mocks/expo-router-mock'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { __setAuthState } from '../mocks/auth-context'
import { TEST_JWT } from '../fixtures'
// Real implementations (moduleNameMapper only matches the extension-less specifier).
const realTrpcClient: any = require('../../src/trpc-client.ts').trpcClient
const realFetchJson: any = require('../../src/lib/fetch-json.ts')
const originalFetch: any = (global as any).fetch
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
/* -------------------------------------------------------------------------- */
/* ROUTE-01..04 */
/* -------------------------------------------------------------------------- */
function RouteProbe({ options }: { options?: any }) {
useAuthenticatedRoute(options)
return <Text testID="route-probe">route</Text>
}
describe('useAuthenticatedRoute', () => {
beforeEach(() => resetAllMocks())
it('ROUTE-01: does not redirect while auth is loading', async () => {
__setAuthState({ isLoading: true, isAuthenticated: false })
renderWithProviders(<RouteProbe />, { auth: false })
await flush()
expect(router.push).not.toHaveBeenCalled()
expect(__snapshot()[constants.AUTH_REDIRECT_KEY]).toBeUndefined()
})
it('ROUTE-02: does not redirect an authenticated user', async () => {
__setAuthState({ isLoading: false, isAuthenticated: true })
renderWithProviders(<RouteProbe />, { auth: false })
await flush()
expect(router.push).not.toHaveBeenCalled()
expect(__snapshot()[constants.AUTH_REDIRECT_KEY]).toBeUndefined()
})
it('ROUTE-03: stores redirect state and pushes login when unauthenticated', async () => {
__setAuthState({ isLoading: false, isAuthenticated: false })
renderWithProviders(<RouteProbe options={{ targetUrl: '/orders', queryParams: { id: 1 } }} />, {
auth: false,
})
await waitFor(() => expect(router.push).toHaveBeenCalledWith('/(auth)/login'))
const stored = JSON.parse(__snapshot()[constants.AUTH_REDIRECT_KEY])
expect(stored.targetUrl).toBe('/orders')
expect(stored.queryParams).toEqual({ id: 1 })
expect(typeof stored.timestamp).toBe('number')
})
it('ROUTE-04: still pushes login when the storage write fails', async () => {
__setAuthState({ isLoading: false, isAuthenticated: false })
const spy = jest
.spyOn(StorageServiceCasual, 'setItem')
.mockRejectedValueOnce(new Error('quota'))
renderWithProviders(<RouteProbe />, { auth: false })
await waitFor(() => expect(router.push).toHaveBeenCalledWith('/(auth)/login'))
spy.mockRestore()
})
})
/* -------------------------------------------------------------------------- */
/* JWT-01..03 */
/* -------------------------------------------------------------------------- */
describe('useJWT', () => {
beforeEach(() => resetAllMocks())
it('JWT-01: round-trips the auth token through save/get/delete', async () => {
await saveAuthToken('token-1')
expect(await getAuthToken()).toBe('token-1')
await deleteAuthToken()
expect(await getAuthToken()).toBeNull()
})
it('JWT-02: round-trips the userId', async () => {
await saveUserId('42')
expect(await getUserId()).toBe('42')
})
it('JWT-03: uses the authToken/userId storage keys', async () => {
expect(AUTH_TOKEN_KEY).toBe('authToken')
expect(USER_ID_KEY).toBe('userId')
await saveAuthToken('token-1')
await saveUserId('7')
expect(__snapshot()[AUTH_TOKEN_KEY]).toBe('token-1')
expect(__snapshot()[USER_ID_KEY]).toBe('7')
})
})
/* -------------------------------------------------------------------------- */
/* TRPC-01..06 (real src/trpc-client) */
/* -------------------------------------------------------------------------- */
function makeResponse(status: number, body: any) {
return {
status,
ok: status >= 200 && status < 300,
json: async () => body,
clone: () => ({ json: async () => body }),
headers: { get: () => 'application/json' },
text: async () => JSON.stringify(body),
}
}
describe('trpc client link', () => {
beforeEach(() => resetAllMocks())
afterEach(() => {
;(global as any).fetch = originalFetch
})
it('TRPC-01: emits force-logout on a 401 UNAUTHORIZED response', async () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit')
;(global as any).fetch = jest.fn(async () =>
makeResponse(401, [{ error: { message: 'UNAUTHORIZED' } }])
)
await realTrpcClient.common.healthCheck.query().catch(() => undefined)
await flush()
expect(emitSpy).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
emitSpy.mockRestore()
})
it('TRPC-02: does not emit on a 401 with another message', async () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit')
;(global as any).fetch = jest.fn(async () =>
makeResponse(401, [{ error: { message: 'TOKEN_EXPIRED' } }])
)
await realTrpcClient.common.healthCheck.query().catch(() => undefined)
await flush()
expect(emitSpy).not.toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
emitSpy.mockRestore()
})
it('TRPC-03: does not emit on a 500 response', async () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit')
;(global as any).fetch = jest.fn(async () => makeResponse(500, []))
await realTrpcClient.common.healthCheck.query().catch(() => undefined)
await flush()
expect(emitSpy).not.toHaveBeenCalled()
emitSpy.mockRestore()
})
it('TRPC-04: sends a bearer header only when a token is stored', async () => {
const fetchMock = jest.fn(async () =>
makeResponse(200, [{ result: { data: { ok: true } } }])
)
;(global as any).fetch = fetchMock
await saveAuthToken(TEST_JWT)
await realTrpcClient.common.healthCheck.query().catch(() => undefined)
expect(((fetchMock.mock.calls as any)[0][1]).headers.Authorization).toBe(`Bearer ${TEST_JWT}`)
await deleteAuthToken()
await realTrpcClient.common.healthCheck.query().catch(() => undefined)
expect(((fetchMock.mock.calls as any)[1][1]).headers.Authorization).toBeUndefined()
})
it('TRPC-05: aborts the request after the JSON fetch timeout', async () => {
jest.useFakeTimers()
let captured: AbortSignal | undefined
;(global as any).fetch = jest.fn((_url: string, options: any) => {
captured = options.signal
return new Promise((_resolve, reject) => {
options.signal?.addEventListener('abort', () => reject(new Error('aborted')))
})
})
const pending = realTrpcClient.common.healthCheck.query().catch(() => undefined)
// Let the batched dispatch timer fire so the link hands the signal to fetch.
await jest.advanceTimersByTimeAsync(1)
expect(captured).toBeDefined()
expect(captured?.aborted).toBe(false)
await jest.advanceTimersByTimeAsync(90_000)
expect(captured?.aborted).toBe(true)
await pending
jest.useRealTimers()
})
it('TRPC-06: forwards an upstream abort to the request signal', async () => {
let captured: AbortSignal | undefined
;(global as any).fetch = jest.fn((_url: string, options: any) => {
captured = options.signal
return new Promise((_resolve, reject) => {
options.signal?.addEventListener('abort', () => reject(new Error('aborted')))
})
})
const upstream = new AbortController()
const pending = realTrpcClient.common.healthCheck
.query({}, { signal: upstream.signal })
.catch(() => undefined)
await flush()
expect(captured).toBeDefined()
expect(captured?.aborted).toBe(false)
upstream.abort()
expect(captured?.aborted).toBe(true)
await pending
})
})
/* -------------------------------------------------------------------------- */
/* HIDE-01..03 */
/* -------------------------------------------------------------------------- */
function HideProbe({ caller }: { caller?: string }) {
useHideTabNav(caller)
return <Text testID="hide-probe">hide</Text>
}
describe('useHideTabNav', () => {
beforeEach(() => resetAllMocks())
it('HIDE-01: hides tabs for the caller key on focus', () => {
renderWithProviders(<HideProbe caller="productDetail" />, { auth: false })
expect(useAppStore.getState().hideTabsNav.productDetail).toBe(true)
})
it('HIDE-02: uses the "default" key when no caller is given', () => {
renderWithProviders(<HideProbe />, { auth: false })
expect(useAppStore.getState().hideTabsNav.default).toBe(true)
})
it('HIDE-03: shows tabs again on blur (unmount)', () => {
const view = renderWithProviders(<HideProbe caller="cart" />, { auth: false })
expect(useAppStore.getState().hideTabsNav.cart).toBe(true)
act(() => view.unmount())
expect(useAppStore.getState().hideTabsNav.cart).toBe(false)
})
})
/* -------------------------------------------------------------------------- */
/* PSI-01..04 */
/* -------------------------------------------------------------------------- */
const HOUR = 60 * 60 * 1000
const slot = (id: number, offsetMs: number) => ({
id,
deliveryTime: new Date(Date.now() + offsetMs).toISOString(),
freezeTime: new Date(Date.now() + offsetMs - HOUR).toISOString(),
products: [],
})
let getQuickestSlot: (productId: number) => number | null
function PsiProbe() {
const api = useProductSlotIdentifier()
getQuickestSlot = api.getQuickestSlot
return <Text testID="psi-probe">psi</Text>
}
function seedSlots(slots: any[], map: Record<number, any>) {
useCentralSlotStore.setState({ slots, productSlotsMap: map })
}
describe('useProductSlotIdentifier', () => {
beforeEach(() => resetAllMocks())
it('PSI-01: returns the id of the earliest future slot for the product', () => {
const soon = slot(100, 2 * HOUR)
const later = slot(200, 4 * HOUR)
seedSlots([soon], { 2: { slots: [later, soon] } })
renderWithProviders(<PsiProbe />, { auth: false })
expect(getQuickestSlot(2)).toBe(100)
})
it('PSI-02: returns null when the product only has past slots', () => {
const past = slot(1, -2 * HOUR)
seedSlots([past], { 2: { slots: [past] } })
renderWithProviders(<PsiProbe />, { auth: false })
expect(getQuickestSlot(2)).toBeNull()
})
it('PSI-03: returns null with no map entry or no slots', () => {
seedSlots([], {})
renderWithProviders(<PsiProbe />, { auth: false })
expect(getQuickestSlot(2)).toBeNull()
act(() => useCentralSlotStore.setState({ slots: [slot(1, HOUR)] as any, productSlotsMap: {} }))
expect(getQuickestSlot(2)).toBeNull()
})
it('PSI-04: sorts by delivery time and returns the earliest', () => {
const two = slot(2, 2 * HOUR)
const four = slot(4, 4 * HOUR)
const six = slot(6, 6 * HOUR)
seedSlots([six], { 2: { slots: [six, two, four] } })
renderWithProviders(<PsiProbe />, { auth: false })
expect(getQuickestSlot(2)).toBe(2)
})
})
/* -------------------------------------------------------------------------- */
/* PENDING-01..04 */
/* -------------------------------------------------------------------------- */
const PENDING_ADDRESS = {
regionId: 1,
name: 'Home',
phone: '9876543210',
addressLine1: '12 Main Road',
city: 'Mahabubnagar',
state: 'Telangana',
latitude: 17,
longitude: 78,
}
describe('pending-address', () => {
beforeEach(() => resetAllMocks())
it('PENDING-01: saves and reads back a pending address', async () => {
await savePendingAddress(PENDING_ADDRESS)
expect(await getPendingAddress()).toEqual(PENDING_ADDRESS)
})
it('PENDING-02: returns null when nothing was saved', async () => {
expect(await getPendingAddress()).toBeNull()
})
it('PENDING-03: clearPendingAddress removes it', async () => {
await savePendingAddress(PENDING_ADDRESS)
await clearPendingAddress()
expect(await getPendingAddress()).toBeNull()
})
it('PENDING-04: returns null for corrupt stored JSON', async () => {
__set('freshyo_pending_address', '{not json')
expect(await getPendingAddress()).toBeNull()
})
})
/* -------------------------------------------------------------------------- */
/* FETCH-01..04 (real src/lib/fetch-json) */
/* -------------------------------------------------------------------------- */
describe('fetch-json', () => {
beforeEach(() => resetAllMocks())
afterEach(() => {
jest.restoreAllMocks()
jest.useRealTimers()
})
it('FETCH-01: returns the JSON payload on success', async () => {
const getSpy = jest
.spyOn(axios, 'get')
.mockResolvedValue({ data: { hello: 'world' } } as any)
const data = await realFetchJson.fetchJson('https://cdn.test/a.json')
expect(data).toEqual({ hello: 'world' })
expect(getSpy).toHaveBeenCalledWith(
'https://cdn.test/a.json',
expect.objectContaining({ signal: expect.anything() })
)
})
it('FETCH-02: aborts the request when the timeout elapses', async () => {
jest.useFakeTimers()
let captured: AbortSignal | undefined
jest.spyOn(axios, 'get').mockImplementation(((_url: string, config: any) => {
captured = config.signal
return new Promise((_resolve, reject) => {
config.signal?.addEventListener('abort', () => reject(new Error('aborted')))
})
}) as any)
const pending = realFetchJson.fetchJson('https://cdn.test/slow.json').catch(() => undefined)
expect(captured).toBeDefined()
expect(captured?.aborted).toBe(false)
jest.advanceTimersByTime(realFetchJson.JSON_FETCH_TIMEOUT_MS)
expect(captured?.aborted).toBe(true)
await pending
})
it('FETCH-03: isAbortError recognises axios and fetch cancellations', () => {
expect(realFetchJson.isAbortError({ name: 'CanceledError' })).toBe(true)
expect(realFetchJson.isAbortError({ name: 'AbortError' })).toBe(true)
expect(realFetchJson.isAbortError({ code: 'ERR_CANCELED' })).toBe(true)
})
it('FETCH-04: isAbortError is false for other errors', () => {
expect(realFetchJson.isAbortError(new Error('boom'))).toBe(false)
expect(realFetchJson.isAbortError(null)).toBe(false)
expect(realFetchJson.isAbortError('nope')).toBe(false)
})
})

View file

@ -0,0 +1,205 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 25 — "Stores" (`tests/lib/stores.test.ts`).
*
* Direct unit tests over the real Zustand stores: no rendering, only actions and
* the resulting state. `resetAllMocks()` restores every store to its boot state
* before each case.
*/
import { resetAllMocks } from '../helpers/reset'
import { __set, __snapshot } from '../mocks/secure-store-mock'
import { useAppStore } from '@/src/store/appStore'
import { useAddressStore } from '@/src/store/addressStore'
import { useCartStore } from '@/src/store/cartStore'
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 { useCheckoutStore } from '@/src/store/checkoutStore'
import { useCentralProductStore } from '@/src/store/centralProductStore'
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
import { useRegionStore } from '@/src/store/regionStore'
import { useSlotStore } from '@/components/stores/slotStore'
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
import {
AVAILABILITY,
MERGED_PRODUCTS,
P_CHICKEN,
PRODUCT_AVAILABILITY,
REGION_1,
REGION_2,
SLOTS,
} from '../fixtures'
const addedProduct = P_CHICKEN as any
describe('stores', () => {
beforeEach(() => {
resetAllMocks()
})
it('STORE-01: appStore updates the hideTabsNav map immutably', () => {
const before = useAppStore.getState().hideTabsNav
useAppStore.getState().setHideTabsNavKey('quick_delivery', true)
const hidden = useAppStore.getState().hideTabsNav
expect(hidden).toEqual({ quick_delivery: true })
expect(hidden).not.toBe(before)
useAppStore.getState().setHideTabsNavKey('quick_delivery', false)
expect(useAppStore.getState().hideTabsNav).toEqual({ quick_delivery: false })
})
it('STORE-02: addressStore selects and clears an address id', () => {
useAddressStore.getState().setSelectedAddressId(11)
expect(useAddressStore.getState().selectedAddressId).toBe(11)
useAddressStore.getState().setSelectedAddressId(null)
expect(useAddressStore.getState().selectedAddressId).toBeNull()
})
it('STORE-03: cartStore queues and clears the added-to-cart product', () => {
useCartStore.getState().setAddedToCartProduct(addedProduct)
expect(useCartStore.getState().addedToCartProduct).toBe(addedProduct)
useCartStore.getState().clearAddedToCartProduct()
expect(useCartStore.getState().addedToCartProduct).toBeNull()
})
it('STORE-04: flashCartStore queues and clears the added flash product', () => {
useFlashCartStore.getState().setAddedFlashProduct(addedProduct)
expect(useFlashCartStore.getState().addedFlashProduct).toBe(addedProduct)
useFlashCartStore.getState().clearAddedFlashProduct()
expect(useFlashCartStore.getState().addedFlashProduct).toBeNull()
})
it('STORE-05: navigationStore sets and clears its flags', () => {
useNavigationStore.getState().setNavigatedFromHome(true)
useNavigationStore.getState().setSelectedStoreId(2)
expect(useNavigationStore.getState().isNavigatedFromHome).toBe(true)
expect(useNavigationStore.getState().selectedStoreId).toBe(2)
useNavigationStore.getState().setNavigatedFromHome(false)
useNavigationStore.getState().setSelectedStoreId(null)
expect(useNavigationStore.getState().isNavigatedFromHome).toBe(false)
expect(useNavigationStore.getState().selectedStoreId).toBeNull()
})
it('STORE-06: quickDeliveryStore sets the selected slot id', () => {
useQuickDeliveryStore.getState().setSelectedSlotId(1849)
expect(useQuickDeliveryStore.getState().selectedSlotId).toBe(1849)
useQuickDeliveryStore.getState().setSelectedSlotId(null)
expect(useQuickDeliveryStore.getState().selectedSlotId).toBeNull()
})
it('STORE-07: storeHeaderStore sets the header title', () => {
useStoreHeaderStore.getState().setTitle('The Freshyo Meat House')
expect(useStoreHeaderStore.getState().title).toBe('The Freshyo Meat House')
})
it('STORE-08: slotStore sets the slot and store ids', () => {
useSlotStore.getState().setSlotId(1849)
useSlotStore.getState().setStoreId(2)
expect(useSlotStore.getState().slotId).toBe(1849)
expect(useSlotStore.getState().storeId).toBe(2)
useSlotStore.getState().setSlotId(undefined)
useSlotStore.getState().setStoreId(undefined)
expect(useSlotStore.getState().slotId).toBeUndefined()
expect(useSlotStore.getState().storeId).toBeUndefined()
})
it('STORE-09: flashNavigationStore flag is set then reset', () => {
useFlashNavigationStore.getState().setShouldNavigateToCart(true)
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(true)
useFlashNavigationStore.getState().reset()
expect(useFlashNavigationStore.getState().shouldNavigateToCart).toBe(false)
})
it('STORE-10: centralProductStore maps products by id', () => {
useCentralProductStore.getState().setProducts(MERGED_PRODUCTS as any)
const state = useCentralProductStore.getState()
expect(state.products).toHaveLength(MERGED_PRODUCTS.length)
expect(state.productsById[2]?.name).toBe('Chicken Breast')
expect(Object.keys(state.productsById)).toHaveLength(MERGED_PRODUCTS.length)
})
it('STORE-11: centralProductStore accepts a refetch setter', async () => {
const refetch = jest.fn(async () => undefined)
useCentralProductStore.getState().setRefetchProducts(refetch)
expect(useCentralProductStore.getState().refetchProducts).toBe(refetch)
await useCentralProductStore.getState().refetchProducts?.()
expect(refetch).toHaveBeenCalledTimes(1)
})
it('STORE-12: centralSlotStore builds a slot map for every product with flags', () => {
useCentralSlotStore.getState().setSlotsData(SLOTS as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any)
const state = useCentralSlotStore.getState()
expect(state.isSlotsLoaded).toBe(true)
expect(state.slots).toBe(SLOTS)
// Every productAvailability row gets an entry, even those in no slot.
expect(Object.keys(state.productSlotsMap)).toHaveLength(PRODUCT_AVAILABILITY.length)
expect(state.productSlotsMap[2].slots.map((slot: any) => slot.id)).toEqual([1849, 1850, 1851, 1852])
expect(state.productSlotsMap[5].slots).toHaveLength(2)
expect(state.productSlotsMap[6].slots).toHaveLength(0)
// Flags come from the availability rows.
expect(state.productSlotsMap[6].isOutOfStock).toBe(true)
expect(state.productSlotsMap[8].isFlashAvailable).toBe(true)
})
it('STORE-13: centralSlotStore accepts a refetch setter', async () => {
const refetch = jest.fn(async () => undefined)
useCentralSlotStore.getState().setRefetchSlots(refetch)
expect(useCentralSlotStore.getState().refetchSlots).toBe(refetch)
await useCentralSlotStore.getState().refetchSlots?.()
expect(refetch).toHaveBeenCalledTimes(1)
})
it('STORE-14: checkoutStore sets the delivery notes', () => {
useCheckoutStore.getState().setUserNotes('Leave at the door')
expect(useCheckoutStore.getState().userNotes).toBe('Leave at the door')
})
it('STORE-15: regionStore sets the region and bumps the generation', () => {
useRegionStore.getState().setRegion(REGION_1 as any, 7)
const state = useRegionStore.getState()
expect(state.selectedRegionId).toBe(1)
expect(state.selectedRegion).toEqual(REGION_1)
expect(state.selectedBoundId).toBe(7)
expect(state.regionGeneration).toBe(1)
})
it('STORE-16: regionStore setRegion with the identical region does not bump', () => {
useRegionStore.getState().setRegion(REGION_1 as any, 7)
const generation = useRegionStore.getState().regionGeneration
useRegionStore.getState().setRegion(REGION_1 as any, 7)
expect(useRegionStore.getState().regionGeneration).toBe(generation)
})
it('STORE-17: regionStore clearRegion nulls the region and bumps', () => {
useRegionStore.getState().setRegion(REGION_2 as any, 8)
const generation = useRegionStore.getState().regionGeneration
useRegionStore.getState().clearRegion()
const state = useRegionStore.getState()
expect(state.selectedRegionId).toBeNull()
expect(state.selectedRegion).toBeNull()
expect(state.selectedBoundId).toBeNull()
expect(state.regionGeneration).toBe(generation + 1)
})
it('STORE-18: regionStore clearRegion on an empty region does not bump', () => {
expect(useRegionStore.getState().regionGeneration).toBe(0)
useRegionStore.getState().clearRegion()
expect(useRegionStore.getState().regionGeneration).toBe(0)
})
it('STORE-19: regionStore is memory-only and never persists', () => {
// An unrelated key proves the snapshot comparison below is meaningful.
__set('unrelated_key', 'keep-me')
const before = __snapshot()
useRegionStore.getState().setRegion(REGION_1 as any, 7)
useRegionStore.getState().clearRegion()
// No zustand persist middleware: the storage snapshot is untouched.
expect(__snapshot()).toEqual(before)
expect(Object.keys(__snapshot()).some((key) => key.includes('region'))).toBe(false)
})
})

View file

@ -0,0 +1,21 @@
/**
* Smoke test for the harness: STR-01..STR-03 from JEST-TEST-CASES.md.
*/
import { orderStatusManipulator } from '@/src/lib/string-manipulators'
describe('orderStatusManipulator', () => {
it('STR-01: maps pending to Confirmed', () => {
expect(orderStatusManipulator('pending')).toBe('Confirmed')
})
it('STR-02: is case-insensitive', () => {
expect(orderStatusManipulator('PENDING')).toBe('Confirmed')
expect(orderStatusManipulator('Pending')).toBe('Confirmed')
})
it('STR-03: leaves other statuses (and empty) unchanged', () => {
expect(orderStatusManipulator('packaged')).toBe('packaged')
expect(orderStatusManipulator('success')).toBe('success')
expect(orderStatusManipulator('')).toBe('')
})
})

View file

@ -0,0 +1,365 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 25 — "Region and location" (`tests/lib/use-region.test.tsx`).
*
* REGION-01..15: the `useRegion()` startup region-resolution state machine.
*
* `useRegion` keeps the launch decision in module-level singletons
* (`startupCheckDone` / `startupLaunchRegionId`), so every case runs against a
* freshly loaded module registry (`jest.isolateModulesAsync`) together with its
* own copies of the harness modules (stores, trpc mock, fetch-json mock, ...).
* The trpc mock re-seeds its defaults on import, so nothing leaks across cases.
*
* Re-importing `@testing-library/react-native` per case would re-run its
* top-level `afterEach`/`afterAll` registration, which Jest forbids inside a
* running test; `RNTL_SKIP_AUTO_CLEANUP` suppresses that and we clean up by hand.
*/
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
async function withFreshModules(fn: (ctx: any) => Promise<void>) {
await jest.isolateModulesAsync(async () => {
const previousSkip = process.env.RNTL_SKIP_AUTO_CLEANUP
process.env.RNTL_SKIP_AUTO_CLEANUP = 'true'
const React = require('react')
const rtl = require('@testing-library/react-native')
require('../helpers/reset').resetAllMocks()
if (previousSkip === undefined) delete process.env.RNTL_SKIP_AUTO_CLEANUP
else process.env.RNTL_SKIP_AUTO_CLEANUP = previousSkip
const ctx: any = {
React,
rtl,
auth: require('../mocks/auth-context'),
locationMock: require('../mocks/expo-location-mock'),
trpc: require('../mocks/trpc-client'),
testUtils: require('../helpers/test-utils'),
fixtures: require('../fixtures'),
secure: require('../mocks/secure-store-mock'),
regionStore: require('@/src/store/regionStore').useRegionStore,
locationStore: require('@/src/store/locationStore').useLocationStore,
useRegion: require('@/src/hooks/useRegion').useRegion,
}
ctx.renderRegion = () => {
const result: { current: any } = { current: null }
const Probe = () => {
result.current = ctx.useRegion()
return null
}
const element = React.createElement(Probe)
const view = ctx.testUtils.renderWithProviders(element, { auth: false })
return { result, view, element }
}
try {
await fn(ctx)
} finally {
rtl.cleanup()
}
})
}
describe('useRegion', () => {
it('REGION-01: with no region and no coords it resolves then falls back to the chooser', async () => {
await withFreshModules(async (ctx) => {
ctx.locationMock.__configure({ permission: 'denied' })
const { result, view } = ctx.renderRegion()
expect(result.current.isResolvingRegion).toBe(true)
expect(result.current.regionId).toBeNull()
await ctx.testUtils.flush(3)
expect(result.current.isResolvingRegion).toBe(false)
expect(result.current.regionId).toBeNull()
expect(result.current.locationStatus).toBe('denied')
view.unmount()
})
})
it('REGION-02: a resolved region with no saved region is adopted without clearing the cart', async () => {
await withFreshModules(async (ctx) => {
const { CART_REG } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
ctx.secure.__set('cart_items', CART_REG)
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
// Adopted as the first region of the launch -> no cart clear, no switch.
expect(ctx.regionStore.getState().regionGeneration).toBe(1)
expect(ctx.secure.__snapshot().cart_items).toBe(CART_REG)
view.unmount()
})
})
it('REGION-03: a resolved different region with no default confirms the switch', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2 } = ctx.fixtures
ctx.regionStore.getState().setRegion(REGION_1, 7)
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: { region: REGION_2, bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' } },
})
ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(6)
expect(result.current.regionId).toBe(2)
expect(ctx.regionStore.getState().selectedRegionId).toBe(2)
view.unmount()
})
})
it('REGION-04: a resolved same region with a new bound updates the bound', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1 } = ctx.fixtures
ctx.regionStore.getState().setRegion(REGION_1, 7)
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: { region: REGION_1, bound: { id: 9, regionId: 1, priority: 1, name: 'Bound 9' } },
})
ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(9)
view.unmount()
})
})
it('REGION-05: a signed-in default in the resolved region adopts the default bound', async () => {
await withFreshModules(async (ctx) => {
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
// Default address A1 -> region 1, bound 7.
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
view.unmount()
})
})
it('REGION-06: a default in another region with a differently resolved region clears for the chooser', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.regionStore.getState().setRegion(REGION_1, 7)
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
data: { region: REGION_2, bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' } },
})
ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBeNull()
view.unmount()
})
})
it('REGION-07: no serviceable region with a default adopts the default', async () => {
await withFreshModules(async (ctx) => {
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.locationMock.__configure({ permission: 'denied' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
view.unmount()
})
})
it('REGION-08: it waits while auth is loading, then settles once auth resolves', async () => {
await withFreshModules(async (ctx) => {
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: true })
ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(3)
expect(result.current.isResolvingRegion).toBe(true)
expect(result.current.regionId).toBeNull()
ctx.auth.__setAuthState({ isLoading: false })
// Auth is read from the mocked context; bump the trpc store so the hook
// re-renders and picks the settled auth state up.
await ctx.rtl.act(async () => {
ctx.trpc.setProcedure('common.healthCheck', { data: { ok: true } })
})
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
view.unmount()
})
})
it('REGION-09: it waits while the default address is loading, then settles', async () => {
await withFreshModules(async (ctx) => {
const { A1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.trpc.setProcedure('user.address.getDefaultAddress', { mode: 'pending' })
ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(3)
expect(result.current.isResolvingRegion).toBe(true)
expect(result.current.regionId).toBeNull()
await ctx.rtl.act(async () => {
ctx.trpc.setProcedure('user.address.getDefaultAddress', {
mode: 'success',
data: { data: A1 },
})
})
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1)
view.unmount()
})
})
it('REGION-10: a manual region pick before the fix resolves is respected', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, BOUND_1 } = ctx.fixtures
ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'pending' })
ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(3)
expect(result.current.regionId).toBeNull()
expect(result.current.isResolvingRegion).toBe(true)
await ctx.rtl.act(async () => {
ctx.regionStore.getState().setRegion(REGION_2, 8)
})
// The late fix now resolves to region 1; the manual pick must win.
await ctx.rtl.act(async () => {
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
mode: 'success',
data: { region: REGION_1, bound: BOUND_1 },
})
})
await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(2)
view.unmount()
})
})
it('REGION-11: a resolve that hangs 8s settles via the safety-net timer', async () => {
await withFreshModules(async (ctx) => {
ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'pending' })
ctx.locationMock.__configure({ permission: 'granted' })
jest.useFakeTimers()
const { result, view } = ctx.renderRegion()
await ctx.rtl.act(async () => {
await Promise.resolve()
})
await ctx.rtl.act(async () => {
await Promise.resolve()
})
expect(result.current.isResolvingRegion).toBe(true)
await ctx.rtl.act(async () => {
jest.advanceTimersByTime(8000)
})
expect(result.current.isResolvingRegion).toBe(false)
expect(result.current.regionId).toBeNull()
jest.useRealTimers()
view.unmount()
})
})
it('REGION-12: a saved region absent from listRegions is left untouched (current behaviour)', async () => {
await withFreshModules(async (ctx) => {
const { REGIONS } = ctx.fixtures
ctx.trpc.setProcedure('common.listRegions', { data: REGIONS })
ctx.regionStore
.getState()
.setRegion({ id: 99, name: 'Ghost', description: 'Stale', effectiveBoundId: 1 } as any, 7)
ctx.locationMock.__configure({ permission: 'denied' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(4)
// The hook has no membership validation against `listRegions`, so a stale
// region id is currently retained rather than cleared.
expect(result.current.regionId).toBe(99)
view.unmount()
})
})
it('REGION-13: a missing stored bound is filled from the derived active bound', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1 } = ctx.fixtures
ctx.regionStore.getState().setRegion(REGION_1, null)
ctx.locationMock.__configure({ permission: 'denied' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(4)
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
expect(result.current.boundId).toBe(7)
view.unmount()
})
})
it('REGION-14: an existing stored bound is not overwritten by the active bound', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1 } = ctx.fixtures
ctx.regionStore.getState().setRegion(REGION_1, 99)
ctx.locationMock.__configure({ permission: 'denied' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(4)
expect(result.current.boundId).toBe(99)
expect(ctx.regionStore.getState().selectedBoundId).toBe(99)
view.unmount()
})
})
it('REGION-15: refreshLocation re-arms the startup check and can adopt a region', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, BOUND_1 } = ctx.fixtures
ctx.locationMock.__configure({ permission: 'denied' })
const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(4)
expect(result.current.regionId).toBeNull()
expect(result.current.isResolvingRegion).toBe(false)
// The user now grants location and taps "use my location".
ctx.locationMock.__configure({ permission: 'granted' })
await ctx.rtl.act(async () => {
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
mode: 'success',
data: { region: REGION_1, bound: BOUND_1 },
})
result.current.refreshLocation()
})
await ctx.testUtils.flush(6)
expect(result.current.regionId).toBe(1)
view.unmount()
})
})
})

View file

@ -0,0 +1,69 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Deterministic AuthContext replacement.
*
* Tests that need an exact auth state (loading / signed-out / signed-in without
* the real provider's async bootstrap) mock the module:
*
* jest.mock('@/src/contexts/AuthContext', () => require('../../mocks/auth-context'))
* __setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
*/
import * as React from 'react'
export interface MockAuthState {
user: any
userDetails: any
isAuthenticated: boolean
isLoading: boolean
token: string | null
}
const initialState: MockAuthState = {
user: null,
userDetails: null,
isAuthenticated: false,
isLoading: false,
token: null,
}
let state: MockAuthState = { ...initialState }
export const login = jest.fn(async () => undefined)
export const loginWithToken = jest.fn(async () => undefined)
export const register = jest.fn(async () => undefined)
export const logout = jest.fn(async () => undefined)
export const updateUser = jest.fn()
export const updateUserDetails = jest.fn()
export function __setAuthState(next: Partial<MockAuthState>) {
state = { ...state, ...next }
}
export function __resetAuthState() {
state = { ...initialState }
login.mockClear()
loginWithToken.mockClear()
register.mockClear()
logout.mockClear()
}
export function getAuthState(): MockAuthState {
return state
}
export const AuthProvider = ({ children }: any) => React.createElement(React.Fragment, null, children)
export const useAuth = () => ({
...state,
login,
loginWithToken,
register,
logout,
updateUser,
updateUserDetails,
})
export const useAuthOptional = () => useAuth()
export const useUserDetails = () => state.userDetails
export default { AuthProvider, useAuth, useAuthOptional, useUserDetails }

View file

@ -0,0 +1,103 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Configurable stand-in for `expo-location`.
*
* `__configure` lets a test pick permission / services / fix / failure per case.
*/
interface Position {
coords: {
latitude: number
longitude: number
accuracy?: number | null
altitude?: number | null
altitudeAccuracy?: number | null
heading?: number | null
speed?: number | null
}
timestamp: number
}
interface LocationConfig {
permission: 'granted' | 'denied' | 'undetermined'
servicesEnabled: boolean
position: Position | null
throwOnPermission: boolean
throwOnServices: boolean
throwOnPosition: boolean
}
const defaultPosition: Position = {
coords: { latitude: 17.00012, longitude: 78.00034, accuracy: 5 },
timestamp: 1_700_000_000_000,
}
const config: LocationConfig = {
permission: 'granted',
servicesEnabled: true,
position: defaultPosition,
throwOnPermission: false,
throwOnServices: false,
throwOnPosition: false,
}
export function __configure(next: Partial<LocationConfig>) {
Object.assign(config, next)
}
export function __reset() {
config.permission = 'granted'
config.servicesEnabled = true
config.position = defaultPosition
config.throwOnPermission = false
config.throwOnServices = false
config.throwOnPosition = false
}
export const Accuracy = {
Lowest: 1,
Low: 2,
Balanced: 3,
High: 4,
Highest: 5,
BestForNavigation: 6,
} as const
export async function requestForegroundPermissionsAsync() {
if (config.throwOnPermission) throw new Error('permission request failed')
return { status: config.permission, granted: config.permission === 'granted', canAskAgain: true }
}
export async function getForegroundPermissionsAsync() {
if (config.throwOnPermission) throw new Error('permission read failed')
return { status: config.permission, granted: config.permission === 'granted', canAskAgain: true }
}
export async function hasServicesEnabledAsync() {
if (config.throwOnServices) throw new Error('services check failed')
return config.servicesEnabled
}
export async function getCurrentPositionAsync(_options?: unknown): Promise<Position> {
if (config.throwOnPosition) throw new Error('no fix')
if (!config.position) throw new Error('no fix')
return config.position
}
export function watchPositionAsync(): { remove: () => void } {
return { remove: jest.fn() }
}
export const LocationAccuracy = Accuracy
export const GeofencingEventType = { Enter: 1, Exit: 2 }
export default {
Accuracy,
requestForegroundPermissionsAsync,
getForegroundPermissionsAsync,
hasServicesEnabledAsync,
getCurrentPositionAsync,
watchPositionAsync,
__configure,
__reset,
}

View file

@ -0,0 +1,113 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Configurable stand-in for `expo-notifications`.
*
* Tests can flip the permission result and fire the received/response listeners
* that `NotificationProvider` subscribes to.
*/
interface NotifConfig {
permission: 'granted' | 'denied' | 'undetermined'
requestResult: 'granted' | 'denied'
token: string
projectId: string | null
}
const config: NotifConfig = {
permission: 'granted',
requestResult: 'granted',
token: 'ExponentPushToken[test-token]',
projectId: 'test-project-id',
}
type Listener = (payload: any) => void
const receivedListeners: Listener[] = []
const responseListeners: Listener[] = []
export function __configure(next: Partial<NotifConfig>) {
Object.assign(config, next)
}
export function __reset() {
config.permission = 'granted'
config.requestResult = 'granted'
config.token = 'ExponentPushToken[test-token]'
config.projectId = 'test-project-id'
receivedListeners.length = 0
responseListeners.length = 0
}
export function __emitNotification(notification: any) {
receivedListeners.forEach((listener) => listener(notification))
}
export function __emitResponse(response: any) {
responseListeners.forEach((listener) => listener(response))
}
export const AndroidImportance = { MAX: 5, HIGH: 4, DEFAULT: 3, LOW: 2, MIN: 1 }
export const setNotificationHandler = jest.fn()
export const setNotificationChannelAsync = jest.fn(async () => null)
export const getPermissionsAsync = jest.fn(async () => ({
status: config.permission,
granted: config.permission === 'granted',
canAskAgain: true,
}))
export const requestPermissionsAsync = jest.fn(async () => ({
status: config.requestResult,
granted: config.requestResult === 'granted',
canAskAgain: true,
}))
export const getExpoPushTokenAsync = jest.fn(async (_args?: any) => ({ data: config.token }))
export const getDevicePushTokenAsync = jest.fn(async () => ({ data: config.token }))
export const scheduleNotificationAsync = jest.fn(async () => 'notification-id')
export const cancelAllScheduledNotificationsAsync = jest.fn(async () => undefined)
export const getLastNotificationResponseAsync = jest.fn(async () => null)
export function addNotificationReceivedListener(listener: Listener) {
receivedListeners.push(listener)
return {
remove: () => {
const index = receivedListeners.indexOf(listener)
if (index >= 0) receivedListeners.splice(index, 1)
},
}
}
export function addNotificationResponseReceivedListener(listener: Listener) {
responseListeners.push(listener)
return {
remove: () => {
const index = responseListeners.indexOf(listener)
if (index >= 0) responseListeners.splice(index, 1)
},
}
}
export const removeNotificationSubscription = jest.fn((subscription: any) => {
subscription?.remove?.()
})
export const useLastNotificationResponse = () => null
export default {
AndroidImportance,
setNotificationHandler,
setNotificationChannelAsync,
getPermissionsAsync,
requestPermissionsAsync,
getExpoPushTokenAsync,
getDevicePushTokenAsync,
scheduleNotificationAsync,
cancelAllScheduledNotificationsAsync,
getLastNotificationResponseAsync,
addNotificationReceivedListener,
addNotificationResponseReceivedListener,
removeNotificationSubscription,
useLastNotificationResponse,
__configure,
__reset,
__emitNotification,
__emitResponse,
}

View file

@ -0,0 +1,140 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Manual mock for `expo-router` (and `expo-router/tabs`, `expo-router/drawer`).
*
* Navigation is recorded, never performed. Layout primitives render their
* children so route files can be mounted directly.
*/
import * as React from 'react'
type AnyRecord = Record<string, any>
function fn() {
return jest.fn()
}
export const router = {
push: fn(),
replace: fn(),
back: fn(),
navigate: fn(),
dismiss: fn(),
dismissTo: fn(),
dismissAll: fn(),
canGoBack: jest.fn(() => true),
setParams: fn(),
reload: fn(),
prefetch: fn(),
}
let params: AnyRecord = {}
let pathname = '/'
let segments: string[] = []
export function __setParams(next: AnyRecord) {
params = next ?? {}
}
export function __setPathname(next: string) {
pathname = next
}
export function __setSegments(next: string[]) {
segments = next ?? []
}
export function __resetRouterMock() {
params = {}
pathname = '/'
segments = []
Object.values(router).forEach((value) => {
if (typeof (value as any).mockClear === 'function') (value as any).mockClear()
})
router.canGoBack.mockReturnValue(true)
}
export const useRouter = () => router
export const useLocalSearchParams = () => params
export const useGlobalSearchParams = () => params
export const usePathname = () => pathname
export const useSegments = () => segments
export const useNavigationContainerRef = () => ({
addListener: jest.fn(() => jest.fn()),
isReady: () => true,
navigate: fn(),
})
export const useRootNavigationState = () => ({ key: 'root', routes: [] })
export const useIsFocused = () => true
export const useFocusEffect = (callback: () => void | (() => void)) => {
React.useEffect(() => {
const cleanup = callback()
return typeof cleanup === 'function' ? cleanup : undefined
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
}
export const useNavigation = () => ({
setOptions: fn(),
addListener: jest.fn(() => jest.fn()),
removeListener: fn(),
dispatch: fn(),
goBack: fn(),
canGoBack: jest.fn(() => true),
getParent: jest.fn(() => undefined),
navigate: fn(),
push: fn(),
replace: fn(),
})
export const useNavigationState = () => ({ index: 0, routes: [] })
export const Redirect = ({ href }: { href: any }) => {
router.replace(href)
return null
}
export const Link = ({ children, href, ...rest }: any) => {
if (React.isValidElement(children)) {
return React.cloneElement(children as any, {
...rest,
onPress: (event: any) => {
;(children as any).props?.onPress?.(event)
router.push(href)
},
})
}
return React.createElement(React.Fragment, null, children)
}
const makeLayout = (name: string) => {
const Layout = ({ children, ...rest }: any) =>
React.createElement(React.Fragment, null, children)
Layout.displayName = name
Layout.Screen = (_props: any) => null
Layout.Trigger = (_props: any) => null
Layout.Protected = ({ children }: any) =>
React.createElement(React.Fragment, null, children)
return Layout
}
export const Stack = makeLayout('Stack')
export const Tabs = makeLayout('Tabs')
export const Drawer = makeLayout('Drawer')
export const Slot = ({ children }: any) =>
React.createElement(React.Fragment, null, children)
export const ErrorBoundary = ({ children }: any) =>
React.createElement(React.Fragment, null, children)
export default {
router,
useRouter,
useLocalSearchParams,
useGlobalSearchParams,
usePathname,
useSegments,
useNavigation,
useFocusEffect,
Redirect,
Link,
Stack,
Tabs,
Drawer,
Slot,
ErrorBoundary,
}

View file

@ -0,0 +1,102 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Manual mock for `@/src/lib/fetch-json`.
*
* The catalogue pages load products/slots/stores/availability from versioned
* CDN JSON documents. This mock keys responses by URL (exact string, RegExp or
* predicate) so tests can seed and override those documents per case.
*/
type Matcher = string | RegExp | ((url: string) => boolean)
interface JsonEntry {
matcher: Matcher
data?: any
error?: unknown
pending?: boolean
once?: boolean
}
const entries: JsonEntry[] = []
const calls: string[] = []
export const JSON_FETCH_TIMEOUT_MS = 90_000
export function isAbortError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const candidate = error as { name?: string; code?: string }
return (
candidate.name === 'CanceledError' ||
candidate.name === 'AbortError' ||
candidate.code === 'ERR_CANCELED'
)
}
function matches(matcher: Matcher, url: string): boolean {
if (typeof matcher === 'string') return matcher === url
if (matcher instanceof RegExp) return matcher.test(url)
return matcher(url)
}
function findEntry(url: string): JsonEntry | undefined {
for (let i = entries.length - 1; i >= 0; i -= 1) {
const entry = entries[i]
if (matches(entry.matcher, url)) {
if (entry.once) entries.splice(i, 1)
return entry
}
}
return undefined
}
export function setJsonResponse(matcher: Matcher, data: any, options: { once?: boolean } = {}) {
entries.push({ matcher, data, once: options.once })
}
export function setJsonError(matcher: Matcher, error?: unknown, options: { once?: boolean } = {}) {
entries.push({
matcher,
error: error ?? new Error(`JSON fetch failed for ${String(matcher)}`),
once: options.once,
})
}
export function setJsonPending(matcher: Matcher) {
entries.push({ matcher, pending: true })
}
export function resetJsonMocks() {
entries.length = 0
calls.length = 0
}
export function jsonCalls(): string[] {
return [...calls]
}
export function jsonCallsFor(matcher: Matcher): string[] {
return calls.filter((url) => matches(matcher, url))
}
export function resetJsonCalls() {
calls.length = 0
}
export async function fetchJson<T>(url: string, _timeoutMs?: number): Promise<T> {
calls.push(url)
const entry = findEntry(url)
if (!entry) {
throw new Error(`[fetch-json mock] no response registered for ${url}`)
}
if (entry.pending) {
return new Promise<T>(() => {
/* never settles */
})
}
if (entry.error !== undefined) {
throw entry.error
}
return entry.data as T
}
export default { fetchJson }

View file

@ -0,0 +1,129 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Shared named-export shims for the stateless native/Expo modules.
*
* Mapped by `jest.config.js` moduleNameMapper so that every copy of a package
* (root node_modules and packages/ui/node_modules) resolves to the same mock.
*/
import * as React from 'react'
import { View } from 'react-native'
/* expo-image */
export const Image = ({ testID, source, ...props }: any) =>
React.createElement(View, {
...props,
testID: testID ?? 'expo-image',
accessibilityLabel: typeof source === 'object' ? source?.uri : undefined,
})
export const ImageBackground = Image
/* expo-linear-gradient */
export const LinearGradient = ({ children, testID, ...props }: any) =>
React.createElement(View, { ...props, testID: testID ?? 'linear-gradient' }, children)
/* expo-blur */
export const BlurView = ({ children, testID, ...props }: any) =>
React.createElement(View, { ...props, testID: testID ?? 'blur-view' }, children)
/* expo-status-bar */
export const StatusBar = (props: any) =>
React.createElement(View, { ...props, testID: props.testID ?? 'status-bar' })
export const StatusBarStyle = { Light: 'light', Dark: 'dark', Auto: 'auto' }
/* expo-font */
export const useFonts = jest.fn(() => [true, null])
export const loadAsync = jest.fn(async () => undefined)
export const isLoaded = jest.fn(() => true)
/* expo-updates */
export const checkForUpdateAsync = jest.fn(async () => ({ isAvailable: false }))
export const fetchUpdateAsync = jest.fn(async () => ({}))
export const reloadAsync = jest.fn(async () => undefined)
export const updateId = 'test-update-id'
/* expo-splash-screen */
export const preventAutoHideAsync = jest.fn(async () => undefined)
export const hideAsync = jest.fn(async () => undefined)
export const setOptions = jest.fn()
/* expo-web-browser */
export const openBrowserAsync = jest.fn(async () => ({ type: 'dismiss' }))
export const dismissBrowser = jest.fn(async () => undefined)
export const maybeCompleteAuthSession = jest.fn()
/* expo-linking */
export const openURL = jest.fn(async () => true)
export const openSettings = jest.fn(async () => undefined)
export const canOpenURL = jest.fn(async () => true)
export const createURL = jest.fn((path: string) => `freshyo://${path}`)
export const getInitialURL = jest.fn(async () => null)
export const addEventListener = jest.fn(() => ({ remove: jest.fn() }))
export const parse = jest.fn(() => ({ queryParams: {} }))
export const useURL = jest.fn(() => null)
/* expo-haptics */
export const impactAsync = jest.fn(async () => undefined)
export const notificationAsync = jest.fn(async () => undefined)
export const selectionAsync = jest.fn(async () => undefined)
export const ImpactFeedbackStyle = { Light: 'light', Medium: 'medium', Heavy: 'heavy' }
export const NotificationFeedbackType = { Success: 'success', Warning: 'warning', Error: 'error' }
/* expo-image-picker */
export const launchImageLibraryAsync = jest.fn(async () => ({ canceled: true, assets: null }))
export const launchCameraAsync = jest.fn(async () => ({ canceled: true, assets: null }))
export const requestMediaLibraryPermissionsAsync = jest.fn(async () => ({
granted: true,
status: 'granted',
}))
export const requestCameraPermissionsAsync = jest.fn(async () => ({ granted: true, status: 'granted' }))
export const MediaTypeOptions = { All: 'All', Images: 'Images', Videos: 'Videos' }
export const MediaType = { Images: 'images' }
/* expo-document-picker */
export const getDocumentAsync = jest.fn(async () => ({ canceled: true, assets: null }))
/* expo-device */
export const isDevice = true
export const deviceName = 'Test Device'
export const modelName = 'Test Model'
export const osName = 'iOS'
export const osVersion = '17.0'
export const DeviceType = { PHONE: 1, TABLET: 2 }
/* expo-auth-session */
export const makeRedirectUri = jest.fn(() => 'freshyo://redirect')
export const useAuthRequest = jest.fn(() => [null, null, jest.fn()])
export const ResponseType = { Token: 'token', IdToken: 'id_token' }
export const useIdTokenAuthRequest = jest.fn(() => [null, null, jest.fn()])
/* react-native-webview */
export const WebView = React.forwardRef((props: any, ref: any) =>
React.createElement(View, { ...props, ref, testID: props.testID ?? 'webview' })
)
;(WebView as any).displayName = 'WebView'
/* react-native-safe-area-context */
const insets = { top: 0, right: 0, bottom: 0, left: 0 }
const frame = { width: 390, height: 844, x: 0, y: 0 }
export const SafeAreaProvider = ({ children }: any) =>
React.createElement(React.Fragment, null, children)
export const SafeAreaView = ({ children, testID, ...props }: any) =>
React.createElement(View, { ...props, testID: testID ?? 'safe-area-view' }, children)
export const SafeAreaInsetsContext = React.createContext(insets)
export const SafeAreaFrameContext = React.createContext(frame)
export const initialWindowMetrics = { insets, frame }
export const useSafeAreaInsets = () => insets
export const useSafeAreaFrame = () => frame
export const withSafeAreaInsets = (Component: any) => Component
export const Rect = { __type: 'Rect' }
export default {
Image,
ImageBackground,
LinearGradient,
BlurView,
StatusBar,
WebView,
SafeAreaView,
SafeAreaProvider,
}

View file

@ -0,0 +1,10 @@
const Constants = {
executionEnvironment: 'standalone',
expoConfig: {
version: '1.2.0',
extra: { eas: { projectId: 'test-project-id' } },
},
easConfig: { projectId: 'test-project-id' },
}
export { Constants }
export default Constants

View file

@ -0,0 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import { View } from 'react-native'
const DateTimePicker = (props: any) => React.createElement(View, props)
DateTimePicker.displayName = 'DateTimePicker'
export const DateTimePickerAndroid = { open: jest.fn(), dismiss: jest.fn() }
export default DateTimePicker

View file

@ -0,0 +1,2 @@
export * from '../expo-router-mock'
export { default } from '../expo-router-mock'

View file

@ -0,0 +1,12 @@
export const GoogleSignin = {
configure: jest.fn(),
hasPlayServices: jest.fn(async () => true),
signIn: jest.fn(async () => ({ data: { idToken: 'google-id-token' } })),
signOut: jest.fn(async () => undefined),
}
export const statusCodes = {
SIGN_IN_CANCELLED: 'SIGN_IN_CANCELLED',
IN_PROGRESS: 'IN_PROGRESS',
PLAY_SERVICES_NOT_AVAILABLE: 'PLAY_SERVICES_NOT_AVAILABLE',
}
export default { GoogleSignin, statusCodes }

View file

@ -0,0 +1,2 @@
export * from '../expo-location-mock'
export { default } from '../expo-location-mock'

View file

@ -0,0 +1,2 @@
export * from '../expo-notifications-mock'
export { default } from '../expo-notifications-mock'

View file

@ -0,0 +1,7 @@
const PhonePe = {
init: jest.fn(async () => 'success'),
startTransaction: jest.fn(async () => ({ status: 'SUCCESS' })),
getPackageSignatureForAndroid: jest.fn(async () => 'signature'),
getPackageSignatureForIOS: jest.fn(async () => 'signature'),
}
export default PhonePe

View file

@ -0,0 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import { View } from 'react-native'
export const Picker = ({ children, testID, ...props }: any) =>
React.createElement(View, { ...props, testID: testID ?? 'picker' }, children)
Picker.Item = (props: any) => React.createElement(View, props)
export default Picker

View file

@ -0,0 +1,2 @@
export const razorpayCheckout = jest.fn(async () => ({ razorpay_payment_id: 'test-payment-id' }))
export default razorpayCheckout

View file

@ -0,0 +1,2 @@
export * from '../react-navigation-mock'
export { default } from '../react-navigation-mock'

View file

@ -0,0 +1,2 @@
export * from '../secure-store-mock'
export { default } from '../secure-store-mock'

View file

@ -0,0 +1,24 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import { View } from 'react-native'
const make = (name: string) => {
const Component = (props: any) => React.createElement(View, props)
Component.displayName = name
return Component
}
export const Svg = make('Svg')
export const Path = make('Path')
export const Circle = make('Circle')
export const Rect = make('Rect')
export const G = make('G')
export const Line = make('Line')
export const Polygon = make('Polygon')
export const Polyline = make('Polyline')
export const Defs = make('Defs')
export const ClipPath = make('ClipPath')
export const LinearGradient = make('SvgLinearGradient')
export const Stop = make('Stop')
export default Svg

View file

@ -0,0 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react'
import { View } from 'react-native'
export const Toast = (props: any) =>
React.createElement(View, { ...props, testID: 'toast-host' })
Toast.show = jest.fn()
Toast.hide = jest.fn()
export default Toast

View file

@ -0,0 +1,82 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Manual mock for `@react-navigation/native`.
*
* `useFocusEffect` is used by `useMarkDataFetchers` / `useDrawerTitle` /
* `useFocusCallback`; outside a NavigationContainer the real one throws. Here it
* behaves like a mount effect so focus-driven refreshes can be asserted.
*/
import * as React from 'react'
export const useFocusEffect = (callback: () => void | (() => void)) => {
React.useEffect(() => {
const cleanup = callback()
return typeof cleanup === 'function' ? cleanup : undefined
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
}
export const useIsFocused = () => true
export const useNavigation = () => ({
setOptions: jest.fn(),
addListener: jest.fn(() => jest.fn()),
removeListener: jest.fn(),
dispatch: jest.fn(),
goBack: jest.fn(),
canGoBack: jest.fn(() => true),
navigate: jest.fn(),
getParent: jest.fn(() => undefined),
getState: jest.fn(() => ({ routes: [] })),
})
export const useRoute = () => ({ key: 'test-route', name: 'test', params: {} })
export const useNavigationState = () => ({ index: 0, routes: [] })
export const useIsFocusedEffect = useFocusEffect
const ThemeProvider = ({ children }: any) => React.createElement(React.Fragment, null, children)
const NavigationContainer = React.forwardRef(({ children }: any, ref: any) =>
React.createElement(React.Fragment, null, children)
)
NavigationContainer.displayName = 'NavigationContainer'
const DefaultTheme = { dark: false, colors: {}, fonts: {} }
const DarkTheme = { dark: true, colors: {}, fonts: {} }
const CommonActions = {
navigate: (payload: any) => ({ type: 'NAVIGATE', payload }),
goBack: () => ({ type: 'GO_BACK' }),
reset: (payload: any) => ({ type: 'RESET', payload }),
setParams: (payload: any) => ({ type: 'SET_PARAMS', payload }),
}
const StackActions = {
push: (name: string, params?: any) => ({ type: 'PUSH', payload: { name, params } }),
replace: (name: string, params?: any) => ({ type: 'REPLACE', payload: { name, params } }),
pop: (count?: number) => ({ type: 'POP', payload: { count } }),
popToTop: () => ({ type: 'POP_TO_TOP' }),
}
const DrawerActions = {
openDrawer: () => ({ type: 'OPEN_DRAWER' }),
closeDrawer: () => ({ type: 'CLOSE_DRAWER' }),
toggleDrawer: () => ({ type: 'TOGGLE_DRAWER' }),
}
export const createNavigationContainerRef = () => ({
isReady: () => true,
navigate: jest.fn(),
dispatch: jest.fn(),
getCurrentRoute: () => undefined,
addListener: jest.fn(() => jest.fn()),
})
export const useNavigationContainerRef = createNavigationContainerRef
export { ThemeProvider, NavigationContainer, DefaultTheme, DarkTheme, CommonActions, StackActions, DrawerActions }
export default {
useFocusEffect,
useIsFocused,
useNavigation,
useRoute,
ThemeProvider,
NavigationContainer,
DefaultTheme,
DarkTheme,
CommonActions,
StackActions,
DrawerActions,
createNavigationContainerRef,
}

View file

@ -0,0 +1,75 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* In-memory stand-in for `expo-secure-store`.
*
* The real module is native-only. Both `StorageService` (auth token) and
* `StorageServiceCasual` (cart/region/OTP keys) run against this store, so
* persistence can be asserted directly instead of via mocks.
*/
const store = new Map<string, string>()
export const __store = store
export function __reset() {
store.clear()
}
export function __snapshot(): Record<string, string> {
return Object.fromEntries(store.entries())
}
/** Synchronous seeding for test setup (avoids waiting a microtask). */
export function __set(key: string, value: string) {
store.set(key, value)
}
export function __delete(key: string) {
store.delete(key)
}
export async function setItemAsync(key: string, value: string): Promise<void> {
if (typeof value !== 'string') {
throw new Error(`expo-secure-store mock: value for "${key}" must be a string`)
}
store.set(key, value)
}
export async function getItemAsync(key: string): Promise<string | null> {
return store.has(key) ? (store.get(key) as string) : null
}
export async function deleteItemAsync(key: string): Promise<void> {
store.delete(key)
}
export async function isAvailableAsync(): Promise<boolean> {
return true
}
export async function getItem(key: string): Promise<string | null> {
return getItemAsync(key)
}
export async function setItem(key: string, value: string): Promise<void> {
return setItemAsync(key, value)
}
export async function removeItem(key: string): Promise<void> {
return deleteItemAsync(key)
}
export const AFTER_FIRST_UNLOCK = 'AFTER_FIRST_UNLOCK'
export const WHEN_UNLOCKED = 'WHEN_UNLOCKED'
export default {
setItemAsync,
getItemAsync,
deleteItemAsync,
isAvailableAsync,
getItem,
setItem,
removeItem,
__reset,
__store,
}

View file

@ -0,0 +1,447 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Manual mock for `@/src/trpc-client`.
*
* Every backend procedure is a keyed entry in a registry. Tests set the outcome
* (`success` / `error` / `pending`), the payload, or a dynamic `impl`, then the
* page under test reads it through the same `trpc.<path>.useQuery/useMutation`
* surface it uses in production.
*
* Call recording powers the catalogue's "assert the procedure name and exact
* input" rule: `lastProcedureInput`, `procedureMutationCalls`, ...
*/
import * as React from 'react'
import { defaultProcedures } from './trpc-defaults'
export type ProcedureMode = 'success' | 'error' | 'pending'
export interface ProcedureConfig {
mode?: ProcedureMode
data?: any
error?: unknown
impl?: (input: any) => any
}
interface ProcedureRecord {
config: ProcedureConfig
queryCalls: any[]
mutationCalls: any[]
invalidations: any[]
}
const procedures = new Map<string, ProcedureRecord>()
let version = 0
const listeners = new Set<() => void>()
function bump() {
version += 1
listeners.forEach((listener) => listener())
}
function subscribe(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
const getVersion = () => version
function record(path: string): ProcedureRecord {
let entry = procedures.get(path)
if (!entry) {
entry = { config: {}, queryCalls: [], mutationCalls: [], invalidations: [] }
procedures.set(path, entry)
}
return entry
}
export function setProcedure(path: string, config: ProcedureConfig) {
const entry = record(path)
entry.config = { ...entry.config, ...config }
bump()
}
export function setProcedures(map: Record<string, ProcedureConfig>) {
Object.entries(map).forEach(([path, config]) => {
const entry = record(path)
entry.config = { ...entry.config, ...config }
})
bump()
}
export function clearProcedure(path: string) {
const entry = procedures.get(path)
if (entry) entry.config = {}
bump()
}
export function getProcedureConfig(path: string): ProcedureConfig {
return procedures.get(path)?.config ?? {}
}
export function seedDefaultProcedures() {
setProcedures(defaultProcedures)
}
export function resetTrpcMocks() {
procedures.clear()
version = 0
listeners.clear()
seedDefaultProcedures()
}
export function procedureQueryCalls(path: string): any[] {
return [...(procedures.get(path)?.queryCalls ?? [])]
}
export function procedureMutationCalls(path: string): any[] {
return [...(procedures.get(path)?.mutationCalls ?? [])]
}
export function procedureInvalidations(path: string): any[] {
return [...(procedures.get(path)?.invalidations ?? [])]
}
export function procedureCallCount(path: string): number {
const entry = procedures.get(path)
if (!entry) return 0
return entry.queryCalls.length + entry.mutationCalls.length
}
export function lastProcedureInput(path: string): any {
const entry = procedures.get(path)
if (!entry) return undefined
const all = [...entry.queryCalls, ...entry.mutationCalls]
if (all.length === 0) return undefined
return all[all.length - 1]
}
export function lastMutationInput(path: string): any {
const calls = procedures.get(path)?.mutationCalls ?? []
return calls.length ? calls[calls.length - 1] : undefined
}
export function expectProcedureCalled(path: string, times?: number) {
const count = procedureCallCount(path)
if (times === undefined) {
expect(count).toBeGreaterThan(0)
} else {
expect(count).toBe(times)
}
}
export function expectNoProcedureCall(path: string) {
expect(procedureCallCount(path)).toBe(0)
}
function resolveData(config: ProcedureConfig, input: any): any {
if (config.impl) return config.impl(input)
return config.data
}
function useQueryImpl(path: string, input: any, options: any = {}) {
React.useSyncExternalStore(subscribe, getVersion, getVersion)
const enabled = options?.enabled !== false
const entry = record(path)
const inputKey = JSON.stringify(input ?? null)
React.useEffect(() => {
if (enabled) entry.queryCalls.push(input)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [enabled, inputKey])
const config = entry.config
const mode = enabled ? config.mode ?? 'success' : 'success'
const isPending = enabled && mode === 'pending'
const isError = enabled && mode === 'error'
const error = isError ? config.error ?? new Error(`[trpc mock] ${path} failed`) : null
let data: any = undefined
if (enabled && !isPending && !isError) {
data = resolveData(config, input)
if (data === undefined) data = options?.placeholderData
if (options?.select && data !== undefined && data !== null) data = options.select(data)
}
return {
data,
error,
status: isPending ? 'pending' : isError ? 'error' : 'success',
isLoading: isPending,
isPending,
isFetching: isPending,
isRefetching: false,
isSuccess: enabled && !isPending && !isError,
isError,
isFetched: enabled && !isPending,
isFetchedAfterMount: enabled && !isPending,
isPlaceholderData: false,
isStale: false,
failureCount: isError ? 1 : 0,
failureReason: error,
dataUpdatedAt: 0,
errorUpdatedAt: 0,
refetch: jest.fn(async () => ({ data, error })),
}
}
function useInfiniteQueryImpl(path: string, input: any, options: any = {}) {
const base = useQueryImpl(path, input, options)
const pages = base.data && Array.isArray((base.data as any).pages) ? (base.data as any).pages : []
return {
...base,
data: base.data ? { pages, pageParams: pages.map((_: any, index: number) => index) } : undefined,
fetchNextPage: jest.fn(async () => undefined),
fetchPreviousPage: jest.fn(async () => undefined),
hasNextPage: false,
hasPreviousPage: false,
isFetchingNextPage: false,
isFetchingPreviousPage: false,
}
}
function useMutationImpl(path: string, options: any = {}) {
React.useSyncExternalStore(subscribe, getVersion, getVersion)
const entry = record(path)
const optionsRef = React.useRef(options)
optionsRef.current = options
const [state, setState] = React.useState<{
status: 'idle' | 'pending' | 'success' | 'error'
data?: any
error?: unknown
}>({ status: 'idle' })
const run = React.useCallback(
async (input: any) => {
entry.mutationCalls.push(input)
const current = optionsRef.current ?? {}
const config = entry.config
const mode = config.mode ?? 'success'
setState({ status: 'pending' })
if (mode === 'pending') {
return new Promise<any>(() => {
/* never settles */
})
}
if (mode === 'error') {
const error = config.error ?? new Error(`[trpc mock] ${path} failed`)
setState({ status: 'error', error })
try {
current.onError?.(error, input, undefined)
} catch {
/* ignore */
}
try {
current.onSettled?.(undefined, error, input, undefined)
} catch {
/* ignore */
}
throw error
}
const data = resolveData(config, input)
setState({ status: 'success', data })
try {
current.onSuccess?.(data, input, undefined)
} catch {
/* ignore */
}
try {
current.onSettled?.(data, null, input, undefined)
} catch {
/* ignore */
}
return data
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[path]
)
const mutate = React.useCallback(
(input: any, mutateOptions?: any) => {
run(input).then(
(data) => mutateOptions?.onSuccess?.(data, input, undefined),
(error) => mutateOptions?.onError?.(error, input, undefined)
)
},
[run]
)
return {
mutate,
mutateAsync: run,
reset: () => setState({ status: 'idle' }),
data: state.data,
error: state.error,
status: state.status,
isPending: state.status === 'pending',
isLoading: state.status === 'pending',
isError: state.status === 'error',
isSuccess: state.status === 'success',
isIdle: state.status === 'idle',
failureCount: 0,
variables: undefined,
}
}
function queryNode(path: string): any {
return {
useQuery: (input?: any, options?: any) => useQueryImpl(path, input, options),
useInfiniteQuery: (input?: any, options?: any) => useInfiniteQueryImpl(path, input, options),
useMutation: (options?: any) => useMutationImpl(path, options),
}
}
function procedureNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'useQuery' || prop === 'useInfiniteQuery' || prop === 'useMutation') {
return queryNode(path)[prop]
}
const next = path ? `${path}.${prop}` : prop
return procedureNode(next)
},
}
)
}
function recordInvalidation(path: string) {
const entry = record(path)
const spy = jest.fn(() => {
entry.invalidations.push({ path })
return Promise.resolve()
})
return spy
}
function utilsNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'invalidate':
return recordInvalidation(path)
case 'refetch':
return jest.fn(async () => ({ data: resolveData(getProcedureConfig(path), undefined) }))
case 'fetch':
return jest.fn(async (input?: any) => resolveData(getProcedureConfig(path), input))
case 'setData':
return jest.fn()
case 'getData':
return jest.fn(() => resolveData(getProcedureConfig(path), undefined))
case 'cancel':
return jest.fn(async () => undefined)
case 'remove':
return jest.fn()
case 'setInfiniteData':
return jest.fn()
case 'getInfiniteData':
return jest.fn(() => undefined)
case 'invalidateQueries':
return jest.fn(async () => undefined)
default:
return utilsNode(path ? `${path}.${prop}` : prop)
}
},
}
)
}
const utilsProxy: any = new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'invalidate') return recordInvalidation('root')
if (prop === 'refetch') return jest.fn(async () => undefined)
if (prop === 'setData') return jest.fn()
if (prop === 'getData') return jest.fn(() => undefined)
if (prop === 'cancel') return jest.fn(async () => undefined)
if (prop === 'remove') return jest.fn()
if (prop === 'invalidateQueries') return jest.fn(async () => undefined)
return utilsNode(prop)
},
}
)
const TrpcProvider = ({ children }: { children?: React.ReactNode }) =>
React.createElement(React.Fragment, null, children)
function makeRootProxy(): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'Provider':
return TrpcProvider
case 'createClient':
return () => ({ __mockTrpcClient: true })
case 'useUtils':
return () => utilsProxy
case 'useContext':
return () => ({})
default:
return procedureNode(prop)
}
},
}
)
}
export const trpc: any = makeRootProxy()
function clientNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'query':
return async (input?: any) => {
const entry = record(path)
entry.queryCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'mutate':
return async (input?: any) => {
const entry = record(path)
entry.mutationCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'subscribe':
return () => ({ unsubscribe: jest.fn() })
default:
return clientNode(path ? `${path}.${prop}` : prop)
}
},
}
)
}
export const trpcClient: any = clientNode('')
// Seed on import so components always have data unless a test overrides it.
seedDefaultProcedures()
export default { trpc, trpcClient }

View file

@ -0,0 +1,94 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Default outcome per backend procedure.
*
* Tests override individual entries with `setProcedure(path, { ... })`. Anything
* not listed here resolves with `undefined` (the mocked hook then reports the
* "success + no data" state).
*/
import {
A1,
ADDRESSES_RESPONSE,
AUTH_USER,
CART_SLOTS_RESPONSE,
C4,
COMPLAINTS_RESPONSE,
CONSTS,
ELIGIBLE_COUPONS_RESPONSE,
MY_COUPONS_RESPONSE,
O1,
ORDERS_RESPONSE,
PRODUCT_DETAILS,
REGIONS,
REGION_1,
BOUND_1,
REVIEWS_RESPONSE,
SELF_DATA_RESPONSE,
SLOTS,
} from '../fixtures'
export interface ProcConfig {
mode?: 'success' | 'error' | 'pending'
data?: any
error?: unknown
impl?: (input: any) => any
}
export const defaultProcedures: Record<string, ProcConfig> = {
// ---- common ----
'common.healthCheck': { data: { ok: true, status: 'healthy' } },
'common.listRegions': { data: REGIONS },
'common.resolveRegionByLocation': { data: { region: REGION_1, bound: BOUND_1 } },
'common.resolveBound': { data: { regionId: 1, boundId: 7 } },
'common.activeBound': { data: { regionId: 1, boundId: 7 } },
'common.regionSettings': { data: {} },
'common.essentialConsts': { data: CONSTS },
'common.generateUploadUrls': { data: { uploadUrls: ['https://upload.test/img-1.jpg'] } },
// ---- auth ----
'user.auth.sendOtp': { data: { success: true, message: 'OTP sent successfully' } },
'user.auth.verifyOtp': { data: { success: true, token: 'test-token', user: AUTH_USER } },
'user.auth.login': { data: { data: { token: 'test-token', user: AUTH_USER } } },
'user.auth.register': { data: { data: { token: 'test-token', user: AUTH_USER } } },
'user.auth.updateProfile': { data: { data: { token: 'test-token', user: AUTH_USER } } },
'user.auth.updatePassword': { data: { success: true } },
'user.auth.deleteAccount': { data: { success: true } },
// ---- user ----
'user.user.getSelfData': { data: SELF_DATA_RESPONSE },
'user.user.savePushToken': { data: { success: true } },
'user.user.recordTrackedRegion': { data: { success: true } },
// ---- address ----
'user.address.getUserAddresses': { data: ADDRESSES_RESPONSE },
'user.address.getDefaultAddress': { data: { data: A1 } },
'user.address.createAddress': { data: { data: A1 } },
'user.address.updateAddress': { data: { data: A1 } },
'user.address.deleteAddress': { data: { success: true } },
// ---- catalogue ----
'user.product.getProductDetails': { data: PRODUCT_DETAILS },
'user.product.getProductReviews': { data: REVIEWS_RESPONSE },
'user.product.createReview': { data: { success: true } },
'user.slots.getSlots': { data: { slots: SLOTS, count: SLOTS.length } },
'user.cart.getCartSlots': { data: CART_SLOTS_RESPONSE },
// ---- coupons ----
'user.coupon.getEligible': { data: ELIGIBLE_COUPONS_RESPONSE },
'user.coupon.getMyCoupons': { data: MY_COUPONS_RESPONSE },
'user.coupon.redeemReservedCoupon': { data: { success: true, data: C4 } },
// ---- complaints ----
'user.complaint.getAll': { data: COMPLAINTS_RESPONSE },
'user.complaint.raise': { data: { success: true } },
// ---- orders ----
'user.order.getOrders': { data: ORDERS_RESPONSE },
'user.order.getOrderById': { data: O1 },
'user.order.placeOrder': { data: { data: { orders: [O1] } } },
'user.order.cancelOrder': { data: { success: true } },
'user.order.updateUserNotes': { data: { success: true } },
// ---- uploads ----
'user.fileUpload.generateUploadUrls': { data: { uploadUrls: ['https://upload.test/img-1.jpg'] } },
}

View file

@ -0,0 +1,423 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 17.1 — the saved-address list
* (`app/(drawer)/(tabs)/me/addresses/index.tsx`, ADDR-01..20).
*
* `AddressForm` has its own suite (ADDRF-*), so this file only exercises the
* list: loading/error/empty states, the card actions and the modal wiring.
*
* A tiny wrapper around the tRPC mock records how often each query's `refetch`
* is invoked. The shared mock's refetch is a no-op, so without this probe the
* catalogue's "refetch" assertions would not be observable.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import Addresses from '@/app/(drawer)/(tabs)/me/addresses/index'
import AddressForm from '@/src/components/AddressForm'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastMutationInput,
procedureInvalidations,
procedureMutationCalls,
} from '../mocks/trpc-client'
import { A1, A2, A3 } from '../fixtures'
jest.mock('@/src/trpc-client', () => {
const actual = jest.requireActual('../mocks/trpc-client')
const state: Record<string, number> = ((globalThis as any).__trpcRefetchProbe = {})
const wrap = (node: any, path: string): any =>
new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
const next = path ? `${path}.${prop}` : prop
const value = node[prop]
if (prop === 'useQuery') {
return (input?: any, options?: any) => {
const result = value.call(node, input, options)
return {
...result,
refetch: (...args: any[]) => {
state[path] = (state[path] ?? 0) + 1
return result.refetch(...args)
},
}
}
}
if (value == null) return value
if (typeof value === 'function') return value
return wrap(value, next)
},
}
)
return {
...actual,
trpc: wrap(actual.trpc, ''),
}
})
/** Focus listeners registered through the (narrowed) navigation mock. */
const mockFocusCallbacks = new Set<() => void>()
jest.mock('@react-navigation/native', () => {
const React = require('react')
const actual = jest.requireActual(__dirname + '/../mocks/react-navigation-mock')
return {
...actual,
useFocusEffect: (callback: () => void | (() => void)) => {
React.useEffect(() => {
mockFocusCallbacks.add(callback)
const cleanup = callback()
return () => {
mockFocusCallbacks.delete(callback)
if (typeof cleanup === 'function') cleanup()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
},
}
})
const ADDRESSES_PATH = 'user.address.getUserAddresses'
/** Map the backend fixture onto the list/page `UserAddress` shape. */
const ser = (address: any) => ({
...address,
addressLine1: address.line1,
addressLine2: address.line2,
phone: address.mobile,
})
const S1 = ser(A1) // Home, region 1, default
const S2 = ser(A2) // Work, region 2
const S3 = ser(A3) // NoRegion
let alertSpy: jest.SpyInstance
function setAddresses(addresses: any[]) {
setProcedure(ADDRESSES_PATH, { data: { data: addresses } })
}
function refetchCount(path = ADDRESSES_PATH) {
return ((globalThis as any).__trpcRefetchProbe?.[path] ?? 0) as number
}
function resetRefetchProbe() {
const state = (globalThis as any).__trpcRefetchProbe
if (state) Object.keys(state).forEach((key) => delete state[key])
}
function renderPage() {
return renderWithProviders(<Addresses />, { auth: false })
}
function alertButtons(callIndex = -1) {
const calls = alertSpy.mock.calls
return calls[calls.length + callIndex]?.[2] ?? []
}
async function pressAlertButton(text: string) {
const button = alertButtons().find((candidate: any) => candidate.text === text)
if (!button) throw new Error(`Alert button ${text} not found`)
await act(async () => {
button.onPress?.()
})
await flush()
}
async function emitFocus() {
await act(async () => {
Array.from(mockFocusCallbacks).forEach((callback) => callback())
})
}
describe('Addresses (ADDR-01..ADDR-20)', () => {
beforeEach(() => {
resetAllMocks()
resetRefetchProbe()
mockFocusCallbacks.clear()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('ADDR-01: shows loading copy while the address query is pending', () => {
setProcedure(ADDRESSES_PATH, { mode: 'pending' })
const { getByText } = renderPage()
expect(getByText('Loading addresses...')).toBeTruthy()
})
it('ADDR-02: a failed query shows the error state and Retry refetches', async () => {
setProcedure(ADDRESSES_PATH, { mode: 'error', error: new Error('offline') })
const { getByText, getByTestId } = renderPage()
expect(getByText('Failed to load addresses. Please try again.')).toBeTruthy()
const before = refetchCount()
fireEvent.press(getByTestId('addresses-retry-button'))
await flush()
expect(refetchCount()).toBeGreaterThan(before)
})
it('ADDR-03: an empty list shows the empty copy and opens the form from Add Address', async () => {
setAddresses([])
const { getByText, getByTestId } = renderPage()
expect(getByText('No addresses found')).toBeTruthy()
fireEvent.press(getByTestId('addresses-empty-add-button'))
await flush()
expect(getByTestId('address-name')).toBeTruthy()
})
it('ADDR-04: renders name, phone and the formatted address line', () => {
setAddresses([S1])
const { getByText } = renderPage()
expect(getByText('Home')).toBeTruthy()
expect(getByText('📞 9876543210')).toBeTruthy()
expect(getByText('📍 12 Main Road, Near Temple, Mahabubnagar, Telangana')).toBeTruthy()
})
it('ADDR-05: the default address carries the badge and no Set Default action', () => {
setAddresses([S1])
const { getByText, queryByTestId } = renderPage()
expect(getByText('Default')).toBeTruthy()
expect(queryByTestId('address-set-default-11')).toBeNull()
})
it('ADDR-06: a non-default address offers Set Default', () => {
setAddresses([S1, S2])
const { getByTestId } = renderPage()
expect(getByTestId('address-set-default-12')).toBeTruthy()
})
it('ADDR-07: Add opens the form in add mode', async () => {
setAddresses([S1])
const view = renderPage()
fireEvent.press(view.getByTestId('addresses-add-button'))
await flush()
expect(view.getByTestId('address-name')).toBeTruthy()
expect(view.UNSAFE_getByType(AddressForm).props.isEdit).toBe(false)
})
it('ADDR-08: Edit opens the form prefilled with the address', async () => {
setAddresses([S1])
const view = renderPage()
fireEvent.press(view.getByTestId('address-edit-11'))
await flush()
const form = view.UNSAFE_getByType(AddressForm)
expect(form.props.isEdit).toBe(true)
expect(form.props.initialValues).toMatchObject({
id: 11,
regionId: 1,
name: 'Home',
phone: '9876543210',
addressLine1: '12 Main Road',
addressLine2: 'Near Temple',
city: 'Mahabubnagar',
state: 'Telangana',
isDefault: true,
latitude: 17,
longitude: 78,
})
expect(form.props.initialValues.googleMapsUrl).toBeUndefined()
})
it('ADDR-09: deleting the only address is refused before the confirmation', async () => {
setAddresses([S1])
const view = renderPage()
fireEvent.press(view.getByTestId('address-delete-11'))
await flush()
expect(
view.getByText('This is your only address. Add another address before deleting this one.')
).toBeTruthy()
expect(alertSpy).not.toHaveBeenCalled()
expect(procedureMutationCalls('user.address.deleteAddress')).toHaveLength(0)
})
it('ADDR-10: deleting with more than one address asks for confirmation and Cancel does nothing', async () => {
setAddresses([S1, S2])
const view = renderPage()
fireEvent.press(view.getByTestId('address-delete-12'))
expect(alertSpy).toHaveBeenCalledWith(
'Delete Address',
'Are you sure you want to delete this address?',
expect.any(Array)
)
await pressAlertButton('Cancel')
expect(procedureMutationCalls('user.address.deleteAddress')).toHaveLength(0)
})
it('ADDR-11: confirming delete mutates, refetches, invalidates the default and alerts', async () => {
setAddresses([S1, S2])
const view = renderPage()
const before = refetchCount()
fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete')
expect(lastMutationInput('user.address.deleteAddress')).toEqual({ id: 12 })
expect(refetchCount()).toBeGreaterThan(before)
expect(procedureInvalidations('user.address.getDefaultAddress').length).toBeGreaterThan(0)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Address deleted successfully')
})
it('ADDR-12: a rejected delete shows the Cannot delete address sheet', async () => {
setProcedure('user.address.deleteAddress', {
mode: 'error',
error: new Error('Address is used by an open order'),
})
setAddresses([S1, S2])
const view = renderPage()
fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete')
expect(view.getByText('Cannot delete address')).toBeTruthy()
expect(view.getByText('Address is used by an open order')).toBeTruthy()
fireEvent.press(view.getByTestId('address-delete-error-ok'))
await flush()
expect(view.queryByText('Cannot delete address')).toBeNull()
})
it('ADDR-13: the current list does not pass isDeleting, so no Deleting... label appears', async () => {
setProcedure('user.address.deleteAddress', { mode: 'pending' })
setAddresses([S1, S2])
const view = renderPage()
fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete')
expect(view.queryByText('Deleting...')).toBeNull()
expect(view.getByTestId('address-delete-12')).toBeTruthy()
expect(procedureMutationCalls('user.address.deleteAddress')).toHaveLength(1)
})
it('ADDR-14: setting a null-region address as default alerts without mutating', async () => {
setAddresses([S1, S3])
const view = renderPage()
fireEvent.press(view.getByTestId('address-set-default-13'))
await flush()
expect(alertSpy).toHaveBeenCalledWith(
'Error',
'This address has no region. Please edit it and choose a region first.'
)
expect(procedureMutationCalls('user.address.updateAddress')).toHaveLength(0)
})
it('ADDR-15: Set Default preserves the address fields and sends isDefault true', async () => {
setAddresses([S1, S2])
const view = renderPage()
fireEvent.press(view.getByTestId('address-set-default-12'))
await flush()
expect(lastMutationInput('user.address.updateAddress')).toEqual({
id: 12,
regionId: 2,
name: 'Work',
phone: '9876543211',
addressLine1: '45 Office Street',
addressLine2: undefined,
city: 'Hyderabad',
state: 'Telangana',
isDefault: true,
latitude: 18,
longitude: 79,
})
expect(procedureInvalidations('user.address.getDefaultAddress').length).toBeGreaterThan(0)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Default address updated')
})
it('ADDR-16: a rejected Set Default alerts with the server message', async () => {
setProcedure('user.address.updateAddress', {
mode: 'error',
error: new Error('Region mismatch'),
})
setAddresses([S1, S2])
const view = renderPage()
fireEvent.press(view.getByTestId('address-set-default-12'))
await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Region mismatch')
})
it('ADDR-17: a successful form submit closes the modal and refetches the list', async () => {
setAddresses([S1])
const view = renderPage()
const before = refetchCount()
fireEvent.press(view.getByTestId('addresses-add-button'))
await flush()
await act(async () => {
view.UNSAFE_getByType(AddressForm).props.onSuccess()
})
await flush()
expect(view.queryByTestId('address-name')).toBeNull()
expect(refetchCount()).toBeGreaterThan(before)
})
it('ADDR-18: re-focusing through useMarkDataFetchers refetches the list', async () => {
setAddresses([S1])
renderPage()
await flush()
const before = refetchCount()
await emitFocus()
await flush()
expect(refetchCount()).toBeGreaterThan(before)
})
it('ADDR-19: an address without line 2 is formatted without a double comma', () => {
setAddresses([S2])
const { getByText } = renderPage()
expect(getByText('📍 45 Office Street, Hyderabad, Telangana')).toBeTruthy()
})
it('ADDR-20: a Google Maps address passes coords as undefined to the form', async () => {
const mapped = {
...S2,
googleMapsUrl: 'https://maps.google.com/?q=18,79',
latitude: 18,
longitude: 79,
}
setAddresses([mapped])
const view = renderPage()
fireEvent.press(view.getByTestId('address-edit-12'))
await flush()
const values = view.UNSAFE_getByType(AddressForm).props.initialValues
expect(values.googleMapsUrl).toBe('https://maps.google.com/?q=18,79')
expect(values.latitude).toBeUndefined()
expect(values.longitude).toBeUndefined()
})
})

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more