enh
This commit is contained in:
parent
ee317f2cd1
commit
ba2cfd1224
219 changed files with 3432 additions and 39050 deletions
18
.pi/mcp.json
18
.pi/mcp.json
|
|
@ -7,5 +7,23 @@
|
|||
],
|
||||
"description": "Maestro mobile/web UI automation: list devices, drive and inspect the screen, run YAML flows locally or on Maestro Cloud."
|
||||
}
|
||||
},
|
||||
"_notes": {
|
||||
"added": "2026-10-18 (FR-2026-10-18-01 regression run)",
|
||||
"known_issues": [
|
||||
"MCP can wedge with 'Device became unreachable during deviceInfo'. Later calls then fail instantly because the failure state is cached, so retrying does not help.",
|
||||
"Observed cause: a stale/duplicate 'maestro.cli.AppKt mcp' java process and/or stale '~/.maestro/deps/simulator-server ios --id <udid>' children. Killing the simulator-server children alone did not recover it.",
|
||||
"Recovery that worked: kill the java process running 'maestro.cli.AppKt mcp' (pgrep -f 'maestro.cli.AppKt mcp'). pi respawns it on the next tool call; list_devices and run then work again.",
|
||||
"After a respawn the Maestro Viewer URL changes (seen at http://127.0.0.1:10000/ and http://127.0.0.1:9999/). Surface the URL from the tool output instead of hardcoding it.",
|
||||
"take_screenshot returns null content on iOS (the image is still shown to the assistant). On iOS prefer 'xcrun simctl io <udid> screenshot <file>'. On the 'chromium' device take_screenshot returns real base64 image content.",
|
||||
"Maestro text matchers are FULL-STRING regex with IGNORE_CASE: text 'Foo' does not match 'Foo bar'. Use '.*Foo.*' or an anchored regex.",
|
||||
"React Native placeholders are not accessibility text nodes (e.g. the cart's 'Select a coupon'); tap/assert those by point.",
|
||||
"Leftover modals (Remove Item / Delete Address / iOS Save Password) silently block every subsequent tap in a flow; dismiss them explicitly.",
|
||||
"The MCP server is a long-lived JVM; after heavy flow churn restart it before starting a new batch."
|
||||
],
|
||||
"device_ids": {
|
||||
"ios_simulator": "5A64695E-F4D4-4E2E-90F3-EC3493A2B457",
|
||||
"web": "chromium"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
BIN
after_logout.png
Normal file
BIN
after_logout.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 118 KiB |
|
|
@ -1,242 +0,0 @@
|
|||
# Known bugs — apps/admin-ui
|
||||
|
||||
Found while writing the integration test suite (`tests/`). Each entry names the
|
||||
file and line, what the code does, what was expected, and the evidence. Severity
|
||||
is my judgement of user impact.
|
||||
|
||||
---
|
||||
|
||||
## High — user-facing breakage
|
||||
|
||||
### 1. Add Product / Add Variant crashes (Formik empty-string normalisation)
|
||||
|
||||
`src/components/ProductForm.tsx:80`
|
||||
|
||||
```ts
|
||||
const variantSignature = (attributes: Attribute[]): string =>
|
||||
attributes
|
||||
.map((a) => `${(a.featureName ?? '').trim().toLowerCase()}::${a.featureValue.trim().toLowerCase()}`)
|
||||
```
|
||||
|
||||
`featureName` is guarded, `featureValue` is not. Formik's `validateYupSchema`
|
||||
normalises empty strings to `undefined` before running Yup, so the `variants`
|
||||
`unique-variants` `.test()` receives attributes whose `featureValue` is
|
||||
`undefined` (`defaultAttribute`/`quantityAttribute` both start as `''`) and
|
||||
`a.featureValue.trim()` throws `TypeError`.
|
||||
|
||||
**Impact:** every keystroke on the Add Product form (validation runs on change)
|
||||
and the "Add Variant" / "Add Feature" buttons throw. Creating a product is
|
||||
unusable. Editing only works when the fetched SKUs already have non-empty
|
||||
feature values.
|
||||
|
||||
**Expected:** `(a.featureValue ?? '').trim()`.
|
||||
|
||||
**Pinned by:** `tests/components/product-form.test.tsx`,
|
||||
`tests/screens/products-add.test.tsx`.
|
||||
|
||||
### 2. Coupon code list crashes on validation
|
||||
|
||||
`src/components/CouponForm.tsx:68`
|
||||
|
||||
```ts
|
||||
const codes = (value.couponCodes || []).map((c: string) => c.trim()).filter(Boolean);
|
||||
```
|
||||
|
||||
The sibling `codes-required` test on line 61 guards with `c && c.trim()`; this
|
||||
one does not. Formik normalises the default `couponCodes: ['']` to `[undefined]`,
|
||||
so `c.trim()` throws.
|
||||
|
||||
**Impact:** toggling "Is Reserved Coupon", switching discount type, "+ Add Code",
|
||||
or selecting a user (`setFieldValue`) crashes the coupon form.
|
||||
|
||||
**Expected:** `(c || '').trim()` or filter first.
|
||||
|
||||
**Pinned by:** `tests/components/coupon-form.test.tsx`.
|
||||
|
||||
### 3. Prices Overview saves the SKU id as the product id
|
||||
|
||||
`app/(drawer)/dashboard/prices-overview/index.tsx:270` (and `:276`)
|
||||
|
||||
```ts
|
||||
const update: any = { productId: sku?.id };
|
||||
```
|
||||
|
||||
`pendingChanges` is keyed by SKU id and `sku` is resolved from `allSkus`, so the
|
||||
payload carries a **SKU** id. The backend `admin.product.updateProductPrices`
|
||||
resolves `productId` against `productInfo.id` (`apps/backend/.../product.ts:436`
|
||||
→ `packages/db_helper_*/src/admin-apis/product.ts`), so it throws
|
||||
`Invalid product IDs: ...` for every row.
|
||||
|
||||
**Expected:** send the SKU's parent product id (`sku.productId`).
|
||||
|
||||
**Pinned by:** `tests/screens/prices-overview.test.tsx`.
|
||||
|
||||
### 4. Product Groupings save SKU ids as product ids
|
||||
|
||||
`components/ProductGroupForm.tsx:44,119` + `components/ProductsSelector.tsx:117`
|
||||
|
||||
`ProductsSelector` emits `value: sku.id` (a SKU id) and the form forwards it as
|
||||
`product_ids`. `createProductGroup` / `updateProductGroup` insert those into
|
||||
`product_group_membership.productId`, which FKs `productInfo.id`. Create and
|
||||
edit are also inconsistent: edit seeds `group.products.map(p => p.id)` (product
|
||||
ids).
|
||||
|
||||
**Expected:** emit/insert product ids.
|
||||
|
||||
**Pinned by:** `tests/components/product-group-form.test.tsx`.
|
||||
|
||||
### 5. "Popular Items" add silently drops the selected product
|
||||
|
||||
`app/(drawer)/dashboard/customize-app/popular-items.tsx:184`
|
||||
|
||||
```ts
|
||||
const newProducts = selectedProductIds
|
||||
.map(id => allProducts?.products.find(p => p.id === id))
|
||||
```
|
||||
|
||||
`selectedProductIds` are SKU ids (from `ProductsSelector`), matched against
|
||||
product ids, so the lookup misses and the dialog closes with nothing added.
|
||||
The label formatter also runs `labelFormat({ productName, price })` on a
|
||||
`SkuSummary` that has no `price`, rendering `₹undefined`.
|
||||
|
||||
**Expected:** match on `sku.productId`.
|
||||
|
||||
**Pinned by:** `tests/screens/customize-app-popular-items.test.tsx`.
|
||||
|
||||
### 6. StoreForm bypasses Formik validation
|
||||
|
||||
`components/StoreForm.tsx:111,183`
|
||||
|
||||
The submit button calls a local `submit()` that invokes the `onSubmit` prop
|
||||
directly; Formik's `handleSubmit` is destructured (`:110`) but never called, so
|
||||
`validationSchema` never runs. Combined with `owner` initialised to `0`
|
||||
(`stores/add.tsx:35`) and `Yup.number().required()` accepting `0`, an ownerless
|
||||
store is submitted and rejected by the backend instead of inline.
|
||||
|
||||
**Expected:** `onPress={handleSubmit}`.
|
||||
|
||||
**Pinned by:** `tests/components/store-form.test.tsx`,
|
||||
`tests/screens/stores-add.test.tsx`.
|
||||
|
||||
---
|
||||
|
||||
## Medium
|
||||
|
||||
### 7. Dashboard Banners fires duplicate `updateBanner` calls on save
|
||||
|
||||
`app/(drawer)/dashboard/dashboard-banners/index.tsx:75-116`
|
||||
|
||||
`handleSave` collects `bannersToUpdate` in a per-banner loop and again in a
|
||||
per-slot loop. A banner whose slot changed is pushed by both, so the same
|
||||
`updateBanner({ id, serialNum })` fires twice; moving a banner between slots can
|
||||
emit contradictory updates.
|
||||
|
||||
**Expected:** de-duplicate by banner id.
|
||||
|
||||
**Pinned by:** `tests/screens/banners-index.test.tsx`.
|
||||
|
||||
### 8. Banner edit screen shows "Banner not found" on mount
|
||||
|
||||
`app/(drawer)/dashboard/dashboard-banners/edit/[id].tsx:42-73`
|
||||
|
||||
`useEffect(..., [bannerId, bannerData])` calls `loadBanner` on the first render,
|
||||
when `bannerData` is still `undefined`, taking the `else` branch:
|
||||
`Alert.alert('Error', 'Banner not found')` + `router.back()` — before the query
|
||||
resolves. The form then renders anyway.
|
||||
|
||||
**Expected:** wait for the query to settle before treating "no data" as missing.
|
||||
|
||||
**Pinned by:** `tests/screens/banners-edit.test.tsx`.
|
||||
|
||||
### 9. Refund / cancellation-coupon actions are unreachable
|
||||
|
||||
`app/(drawer)/dashboard/manage-orders/order-details/[id].tsx:697-769`
|
||||
|
||||
The entire Refund Details block is commented out. It is the only caller of
|
||||
`setInitiateRefundDialogOpen(true)` and `setGenerateCouponDialogOpen(true)`, so
|
||||
`admin.payments.initiateRefund` and `admin.coupon.generateCancellationCoupon`
|
||||
can never fire from the UI. The `initiateRefund` success alert (lines 66-69)
|
||||
also drops the amount from its template string.
|
||||
|
||||
**Expected:** re-enable the block when the feature ships.
|
||||
|
||||
**Pinned by:** `tests/screens/order-details.test.tsx` (documents the gap).
|
||||
|
||||
### 10. Complaints resolve can send an empty response the backend rejects
|
||||
|
||||
`app/(drawer)/dashboard/complaints/index.tsx:66`
|
||||
|
||||
```ts
|
||||
resolveComplaint.mutate({ id: String(selectedComplaintId), response: response ?? '' }, ...)
|
||||
```
|
||||
|
||||
The backend input requires `response: z.string().min(1)`. Confirming Resolve with
|
||||
no comment sends `''` and gets a server error (surfaced as a generic alert)
|
||||
instead of being blocked client-side.
|
||||
|
||||
**Expected:** require a response, or make it optional server-side.
|
||||
|
||||
**Pinned by:** `tests/screens/complaints-index.test.tsx`.
|
||||
|
||||
---
|
||||
|
||||
## Low
|
||||
|
||||
### 11. Inline "Packaged" toggle in the orders list is inert
|
||||
|
||||
`app/(drawer)/dashboard/manage-orders/orders/index.tsx:218`
|
||||
`onPress={() => {}}`. Packaged changes only work through `OrderOptionsMenu`.
|
||||
|
||||
### 12. CancelOrderDialog has an unreachable validation branch
|
||||
|
||||
`components/CancelOrderDialog.tsx:18-21` alerts on an empty reason, but the
|
||||
confirm button is disabled while the reason is empty (`:85`), so the branch
|
||||
never runs.
|
||||
|
||||
### 13. Send Notifications shows the error alert twice
|
||||
|
||||
`app/(drawer)/dashboard/send-notifications/index.tsx:48-50,87-96` — the mutation
|
||||
has an `onError` alert and the caller also try/catches and alerts.
|
||||
|
||||
### 14. Product Groupings "N Products" does nothing
|
||||
|
||||
`app/(drawer)/dashboard/product-groupings/index.tsx:11,130` — `BottomDialog` is
|
||||
imported and `viewProducts` is set by `onViewProducts`, but no dialog renders.
|
||||
|
||||
### 15. `NotificationToast` calls a hook outside a component
|
||||
|
||||
`services/toaster.tsx:39-40` — `NotificationToast` calls `useRouter()` though it
|
||||
is exported as an event helper, not rendered as a component (Rules of Hooks).
|
||||
|
||||
### 16. Upload key parsing assumes path-style S3 URLs
|
||||
|
||||
`hooks/useUploadToObjectStore.ts:99-104` — `extractKeyFromPresignedUrl` strips the
|
||||
first path segment (`slice(1)`). Correct for the backend's current
|
||||
`<endpoint>/<bucket>/<key>` URLs, but breaks for virtual-host-style
|
||||
(`<bucket>.<host>/<key>`). The backend's own `s3-client.ts` uses `slice(-2)`.
|
||||
|
||||
---
|
||||
|
||||
## Test-harness limitations (not app bugs)
|
||||
|
||||
- **`expo-image-picker` / `expo-document-picker` mocks do not reach `packages/ui`.**
|
||||
`packages/ui` resolves its own copy of those modules, so `common-ui`'s
|
||||
`usePickImage`/`ImageUploader` call the real (native) picker and cannot be
|
||||
driven from a test. Image-upload flows are therefore exercised by mocking the
|
||||
upload hook or seeding state, and upload integration is not covered.
|
||||
- **`@expo/vector-icons` has a duplicate copy under `packages/ui/node_modules`,**
|
||||
so `UNSAFE_getAllByType(MaterialIcons)` from the app's copy does not find the
|
||||
`common-ui` icons. Prefer text/testID-based queries.
|
||||
- **`react-native-draggable-flatlist` mock** ignores `ListHeaderComponent` /
|
||||
`ListFooterComponent` and never calls `onDragEnd`, so drag-reorder save flows
|
||||
cannot be asserted through the mock.
|
||||
|
||||
## Already fixed during this work
|
||||
|
||||
- `stores/edit.tsx` now invalidates `admin.store.getStores` (only `getStoreById`
|
||||
was refetched before).
|
||||
- `coupons/create.tsx` + `coupons/edit/[id].tsx` invalidate
|
||||
`admin.coupon.getAll` / `getReservedCoupons` instead of refetching with a
|
||||
hardcoded `search: ''` that missed the list's key when a search was active.
|
||||
- `tests/mocks/native.ts` `tabViewMock` `SceneMap` returned the raw map instead
|
||||
of a `renderScene` function (corrected).
|
||||
|
|
@ -1,120 +0,0 @@
|
|||
/**
|
||||
* BannerForm component (components/BannerForm.tsx) — validation, submit
|
||||
* gating, submit/cancel callbacks and the existing-image (edit) display.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import BannerForm, { BannerFormData } from '@/components/BannerForm'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const onSubmit = jest.fn()
|
||||
const onCancel = jest.fn()
|
||||
|
||||
const initialValues: BannerFormData = {
|
||||
name: '',
|
||||
imageUrl: '',
|
||||
description: '',
|
||||
skuIds: [],
|
||||
redirectUrl: '',
|
||||
}
|
||||
|
||||
const blur = (placeholder: string, name: string) => {
|
||||
fireEvent(screen.getByPlaceholderText(placeholder), 'blur', {
|
||||
target: { name },
|
||||
persist: () => {},
|
||||
})
|
||||
}
|
||||
|
||||
const renderForm = (props: Partial<React.ComponentProps<typeof BannerForm>> = {}) =>
|
||||
renderWithProviders(
|
||||
<BannerForm
|
||||
initialValues={initialValues}
|
||||
onSubmit={onSubmit}
|
||||
onCancel={onCancel}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
describe('BannerForm', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
onSubmit.mockClear()
|
||||
onCancel.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
setupApiMocks()
|
||||
})
|
||||
|
||||
it('renders the banner fields', () => {
|
||||
renderForm()
|
||||
|
||||
expect(screen.getByPlaceholderText('Enter banner name')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter banner description (optional)')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('https://example.com/redirect')).toBeVisible()
|
||||
expect(screen.getByText('Create Banner')).toBeVisible()
|
||||
})
|
||||
|
||||
it('requires a banner name', async () => {
|
||||
renderForm()
|
||||
|
||||
blur('Enter banner name', 'name')
|
||||
|
||||
expect(await screen.findByText('Banner name is required')).toBeVisible()
|
||||
})
|
||||
|
||||
it('rejects a malformed redirect URL', async () => {
|
||||
renderForm()
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('https://example.com/redirect'), 'nope')
|
||||
blur('https://example.com/redirect', 'redirectUrl')
|
||||
|
||||
expect(await screen.findByText('Please enter a valid URL')).toBeVisible()
|
||||
})
|
||||
|
||||
it('does not submit until the form is valid and dirty', async () => {
|
||||
renderForm()
|
||||
|
||||
fireEvent.press(screen.getByText('Create Banner'))
|
||||
expect(onSubmit).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
|
||||
})
|
||||
fireEvent.press(screen.getByText('Create Banner'))
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit.mock.calls[0][0]).toMatchObject({ name: 'My Banner' })
|
||||
expect(onSubmit.mock.calls[0][1]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('uses the provided submit button label', () => {
|
||||
renderForm({ submitButtonText: 'Update Banner' })
|
||||
|
||||
expect(screen.getByText('Update Banner')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the saving state', () => {
|
||||
renderForm({ isSubmitting: true })
|
||||
|
||||
expect(screen.getByText('Saving...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('calls onCancel', () => {
|
||||
renderForm()
|
||||
|
||||
fireEvent.press(screen.getByText('Cancel'))
|
||||
|
||||
expect(onCancel).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the existing image as filling the single-image slot', async () => {
|
||||
renderForm({ existingImageUrl: 'https://cdn.example.com/seven.jpg' })
|
||||
|
||||
// ImageUploader blocks the add tile once an existing image is present.
|
||||
expect(await screen.findByText('Only one image allowed')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,98 +0,0 @@
|
|||
/**
|
||||
* CancelOrderDialog — reason gating, the cancelOrder mutation and callbacks.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import CancelOrderDialog from '@/components/CancelOrderDialog'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
describe('CancelOrderDialog', () => {
|
||||
const onClose = jest.fn()
|
||||
const onSuccess = jest.fn()
|
||||
|
||||
beforeEach(async () => {
|
||||
onClose.mockClear()
|
||||
onSuccess.mockClear()
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
setupApiMocks({ procedures: { 'admin.order.cancelOrder': { success: true, message: 'ok' } } })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the dialog chrome and reason input', () => {
|
||||
renderWithProviders(
|
||||
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
|
||||
)
|
||||
|
||||
expect(screen.getAllByText('Cancel Order')).toHaveLength(2)
|
||||
expect(screen.getByText(/refund record will be created/)).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
|
||||
expect(screen.getByText('Keep Order')).toBeVisible()
|
||||
})
|
||||
|
||||
it('does not submit and does not confirm when the reason is empty', () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.order.cancelOrder': { success: true, message: 'ok' } },
|
||||
})
|
||||
|
||||
renderWithProviders(
|
||||
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
|
||||
)
|
||||
|
||||
const confirm = screen.getAllByText('Cancel Order').pop()!
|
||||
fireEvent.press(confirm)
|
||||
|
||||
expect(Alert.alert).not.toHaveBeenCalled()
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('asks for confirmation then cancels with the typed reason', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.order.cancelOrder': { success: true, message: 'cancelled' } },
|
||||
})
|
||||
|
||||
renderWithProviders(
|
||||
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
|
||||
)
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter reason for cancellation...'),
|
||||
'Out of stock'
|
||||
)
|
||||
fireEvent.press(screen.getAllByText('Cancel Order').pop()!)
|
||||
|
||||
const call = (Alert.alert as jest.Mock).mock.calls.find((c) => c[0] === 'Cancel Order')
|
||||
expect(call).toBeTruthy()
|
||||
const buttons = call![2] as { text: string; onPress?: () => void }[]
|
||||
const yes = buttons.find((b) => b.text === 'Yes, Cancel')!
|
||||
|
||||
await act(async () => {
|
||||
yes.onPress?.()
|
||||
})
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.cancelOrder'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.cancelOrder')).toEqual({
|
||||
orderId: 7,
|
||||
reason: 'Out of stock',
|
||||
})
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(onSuccess).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the order via the secondary button', () => {
|
||||
renderWithProviders(
|
||||
<CancelOrderDialog orderId={7} open onClose={onClose} onSuccess={onSuccess} />
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Keep Order'))
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,170 +0,0 @@
|
|||
/**
|
||||
* CouponForm component (src/components/CouponForm.tsx) — Formik validation,
|
||||
* discount-type switching, coupon-code entry (incl. bulk generation) and the
|
||||
* applicable-users lookup dialog.
|
||||
*
|
||||
* NOTE: The default form starts with an empty coupon-code slot, and Formik
|
||||
* normalises `['']` to `[undefined]` before Yup runs, which makes the
|
||||
* `codes-unique` test call `.trim()` on `undefined` (see the reported bug).
|
||||
* Every interaction that triggers validation is therefore exercised from a
|
||||
* valid `initialValues` seed; the code-entry flow is covered by typing a code
|
||||
* first.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import CouponForm from '@/src/components/CouponForm'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import { lastProcedureInput } from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const onSubmit = jest.fn()
|
||||
|
||||
const validInitialValues = {
|
||||
couponCodes: ['SAVE10'],
|
||||
isUserBased: false,
|
||||
isApplyForAll: false,
|
||||
targetUsers: [],
|
||||
discountPercent: 10,
|
||||
applicableUsers: [],
|
||||
skuIds: [],
|
||||
exclusiveApply: false,
|
||||
isFirstOrderOnly: false,
|
||||
isReservedCoupon: false,
|
||||
}
|
||||
|
||||
const usersProcedure = {
|
||||
users: [
|
||||
{ id: 11, name: 'Alice', mobile: '9000000001' },
|
||||
{ id: 12, name: 'Bob', mobile: '9000000002' },
|
||||
],
|
||||
}
|
||||
|
||||
describe('CouponForm', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
onSubmit.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.coupon.getUsersMiniInfo': usersProcedure },
|
||||
})
|
||||
})
|
||||
|
||||
it('renders the default form', () => {
|
||||
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
|
||||
|
||||
expect(screen.getByText('Coupon Codes')).toBeVisible()
|
||||
expect(screen.getByText('Discount Type *')).toBeVisible()
|
||||
expect(screen.getByText('Is Reserved Coupon')).toBeVisible()
|
||||
expect(screen.getByText('Create Coupon')).toBeVisible()
|
||||
})
|
||||
|
||||
it('validates the form before calling onSubmit', async () => {
|
||||
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
|
||||
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Create Coupon')).toBeVisible())
|
||||
expect(onSubmit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uppercases the coupon code and submits the entered values', async () => {
|
||||
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'save10')
|
||||
fireEvent.press(screen.getByText('Percentage'))
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., 10'), '10')
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit.mock.calls[0][0]).toMatchObject({
|
||||
couponCodes: ['SAVE10'],
|
||||
discountPercent: 10,
|
||||
isUserBased: false,
|
||||
isApplyForAll: false,
|
||||
isReservedCoupon: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('switches between percentage and flat discount fields', () => {
|
||||
renderWithProviders(
|
||||
<CouponForm
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
initialValues={validInitialValues}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByPlaceholderText('e.g., 10')).toBeVisible()
|
||||
expect(screen.queryByPlaceholderText('e.g., 50')).toBeNull()
|
||||
|
||||
fireEvent.press(screen.getByText('Flat Amount'))
|
||||
|
||||
expect(screen.getByPlaceholderText('e.g., 50')).toBeVisible()
|
||||
expect(screen.queryByPlaceholderText('e.g., 10')).toBeNull()
|
||||
})
|
||||
|
||||
it('disables target audience for reserved coupons', () => {
|
||||
renderWithProviders(
|
||||
<CouponForm
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
initialValues={validInitialValues}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(
|
||||
screen.queryByText('Target Audience (Disabled for Reserved Coupons)')
|
||||
).toBeNull()
|
||||
|
||||
fireEvent.press(screen.getByRole('checkbox'))
|
||||
|
||||
expect(
|
||||
screen.getByText('Target Audience (Disabled for Reserved Coupons)')
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('generates sequential codes from a pattern code', async () => {
|
||||
renderWithProviders(<CouponForm onSubmit={onSubmit} isLoading={false} />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'ABC1')
|
||||
fireEvent.press(screen.getByText('Add Multiple'))
|
||||
|
||||
expect(screen.getByText('Add Multiple Coupons')).toBeVisible()
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., 10'), '2')
|
||||
fireEvent.press(screen.getByText('Generate'))
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('ABC2')).toBeVisible())
|
||||
expect(screen.getByDisplayValue('ABC3')).toBeVisible()
|
||||
})
|
||||
|
||||
it('loads and selects applicable users', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.coupon.getUsersMiniInfo': usersProcedure },
|
||||
})
|
||||
renderWithProviders(
|
||||
<CouponForm
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
initialValues={validInitialValues}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Select users...'))
|
||||
|
||||
expect(await screen.findByText('9000000001 - Alice')).toBeVisible()
|
||||
expect(lastProcedureInput(fetchMock, 'admin.coupon.getUsersMiniInfo')).toMatchObject({
|
||||
search: '',
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
})
|
||||
|
||||
fireEvent.press(screen.getByText('9000000001 - Alice'))
|
||||
fireEvent.press(screen.getByText('Done'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('1 users selected')).toBeVisible())
|
||||
})
|
||||
})
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
/**
|
||||
* OrderNotesForm — empty validation, updateNotes mutation and callbacks.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import { OrderNotesForm } from '@/components/OrderNotesForm'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
describe('OrderNotesForm', () => {
|
||||
const onSuccess = jest.fn()
|
||||
const onCancel = jest.fn()
|
||||
|
||||
beforeEach(async () => {
|
||||
onSuccess.mockClear()
|
||||
onCancel.mockClear()
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
setupApiMocks({ procedures: { 'admin.order.updateNotes': { id: 5 } } })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the initial notes and actions', () => {
|
||||
renderWithProviders(
|
||||
<OrderNotesForm orderId={5} initialNotes="existing" onSuccess={onSuccess} onCancel={onCancel} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Add Order Notes')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('existing')).toBeVisible()
|
||||
expect(screen.getByText('Save Notes')).toBeVisible()
|
||||
expect(screen.getByText('Cancel')).toBeVisible()
|
||||
})
|
||||
|
||||
it('rejects empty notes without calling the mutation', () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.order.updateNotes': { id: 5 } },
|
||||
})
|
||||
|
||||
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
|
||||
|
||||
fireEvent.press(screen.getByText('Save Notes'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter some notes')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('saves trimmed notes and fires onSuccess', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.order.updateNotes': { id: 5 } },
|
||||
})
|
||||
|
||||
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter notes for this order...'),
|
||||
' handle with care '
|
||||
)
|
||||
fireEvent.press(screen.getByText('Save Notes'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.updateNotes'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.updateNotes')).toEqual({
|
||||
orderId: 5,
|
||||
adminNotes: 'handle with care',
|
||||
})
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalled())
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Notes updated successfully')
|
||||
})
|
||||
|
||||
it('calls onCancel when the cancel button is pressed', () => {
|
||||
renderWithProviders(<OrderNotesForm orderId={5} onSuccess={onSuccess} onCancel={onCancel} />)
|
||||
|
||||
fireEvent.press(screen.getByText('Cancel'))
|
||||
|
||||
expect(onCancel).toHaveBeenCalled()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,259 +0,0 @@
|
|||
/**
|
||||
* OrderOptionsMenu — action rows, responder toggles, location attach and
|
||||
* WhatsApp/Dial/Maps intents.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, Linking } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import Ionicons from '@expo/vector-icons/Ionicons'
|
||||
import * as Location from 'expo-location'
|
||||
|
||||
import { OrderOptionsMenu } from '@/components/OrderOptionsMenu'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
type OrderProp = React.ComponentProps<typeof OrderOptionsMenu>['order']
|
||||
|
||||
const baseOrder: OrderProp = {
|
||||
id: 11,
|
||||
readableId: 11,
|
||||
isPackaged: false,
|
||||
isDelivered: false,
|
||||
address: '12 Main St, City, State - 500001, Phone: 9876543210',
|
||||
addressId: 3,
|
||||
adminNotes: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
status: 'pending',
|
||||
}
|
||||
|
||||
function renderMenu(overrides: Partial<OrderProp> = {}, handlers: Record<string, jest.Mock> = {}) {
|
||||
const props = {
|
||||
open: true,
|
||||
onClose: jest.fn(),
|
||||
order: { ...baseOrder, ...overrides },
|
||||
onViewDetails: jest.fn(),
|
||||
onTogglePackaged: jest.fn(),
|
||||
onToggleDelivered: jest.fn(),
|
||||
onOpenAdminNotes: jest.fn(),
|
||||
onCancelOrder: jest.fn(),
|
||||
onAttachLocation: jest.fn(),
|
||||
onWhatsApp: jest.fn(),
|
||||
onDial: jest.fn(),
|
||||
...handlers,
|
||||
}
|
||||
renderWithProviders(<OrderOptionsMenu {...props} />)
|
||||
return props
|
||||
}
|
||||
|
||||
describe('OrderOptionsMenu', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
setupApiMocks({ procedures: { 'admin.order.updateAddressCoords': { success: true } } })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
jest.spyOn(Linking, 'openURL').mockResolvedValue(true)
|
||||
})
|
||||
|
||||
it('renders the header and action rows', () => {
|
||||
renderMenu()
|
||||
|
||||
expect(screen.getByText('Order #11')).toBeVisible()
|
||||
expect(screen.getByText('Select an action to perform')).toBeVisible()
|
||||
expect(screen.getByText('View Details')).toBeVisible()
|
||||
expect(screen.getByText('Packaged')).toBeVisible()
|
||||
expect(screen.getByText('Delivered')).toBeVisible()
|
||||
expect(screen.getByText('Admin Notes')).toBeVisible()
|
||||
expect(screen.getByText('Cancel Order')).toBeVisible()
|
||||
expect(screen.getByText('Attach Location')).toBeVisible()
|
||||
expect(screen.getByText('Message On WhatsApp')).toBeVisible()
|
||||
expect(screen.getByText('Dial Mobile Number')).toBeVisible()
|
||||
})
|
||||
|
||||
it('describes packaged/delivered state in the row subtitles', () => {
|
||||
renderMenu({ isPackaged: true, isDelivered: true })
|
||||
|
||||
expect(screen.getByText('Mark as not packaged')).toBeVisible()
|
||||
expect(screen.getByText('Mark as not delivered')).toBeVisible()
|
||||
})
|
||||
|
||||
it('hides cancel when the order is already cancelled', () => {
|
||||
renderMenu({ status: 'cancelled' })
|
||||
|
||||
expect(screen.queryByText('Cancel Order')).toBeNull()
|
||||
})
|
||||
|
||||
it('invokes view details and closes', () => {
|
||||
const props = renderMenu()
|
||||
|
||||
fireEvent.press(screen.getByText('View Details'))
|
||||
|
||||
expect(props.onViewDetails).toHaveBeenCalled()
|
||||
expect(props.onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('invokes admin notes and closes', () => {
|
||||
const props = renderMenu()
|
||||
|
||||
fireEvent.press(screen.getByText('Admin Notes'))
|
||||
|
||||
expect(props.onOpenAdminNotes).toHaveBeenCalled()
|
||||
expect(props.onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('invokes cancel then closes', () => {
|
||||
const props = renderMenu()
|
||||
|
||||
fireEvent.press(screen.getByText('Cancel Order'))
|
||||
|
||||
expect(props.onCancelOrder).toHaveBeenCalled()
|
||||
expect(props.onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('toggles packaged through the responder', () => {
|
||||
const props = renderMenu({ isPackaged: false, isDelivered: true })
|
||||
|
||||
const icon = screen
|
||||
.UNSAFE_getAllByType(Ionicons)
|
||||
.find((node) => node.props.name === 'square-outline')!
|
||||
fireEvent(icon, 'responderEnd', { stopPropagation: jest.fn() })
|
||||
|
||||
expect(props.onTogglePackaged).toHaveBeenCalled()
|
||||
expect(props.onToggleDelivered).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('toggles delivered through the responder', () => {
|
||||
const props = renderMenu({ isPackaged: true, isDelivered: false })
|
||||
|
||||
const icon = screen
|
||||
.UNSAFE_getAllByType(Ionicons)
|
||||
.find((node) => node.props.name === 'square-outline')!
|
||||
fireEvent(icon, 'responderEnd', { stopPropagation: jest.fn() })
|
||||
|
||||
expect(props.onToggleDelivered).toHaveBeenCalled()
|
||||
expect(props.onTogglePackaged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('attaches location coordinates and reports success', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.order.updateAddressCoords': { success: true } },
|
||||
})
|
||||
const props = renderMenu()
|
||||
|
||||
fireEvent.press(screen.getByText('Attach Location'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.updateAddressCoords'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.updateAddressCoords')).toEqual({
|
||||
addressId: 3,
|
||||
latitude: 16.75,
|
||||
longitude: 78.0,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Location attached to address successfully.'
|
||||
)
|
||||
)
|
||||
expect(props.onAttachLocation).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('warns when location permission is denied and skips the mutation', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.order.updateAddressCoords': { success: true } },
|
||||
})
|
||||
;(Location.requestForegroundPermissionsAsync as jest.Mock).mockResolvedValueOnce({
|
||||
status: 'denied',
|
||||
granted: false,
|
||||
})
|
||||
|
||||
renderMenu()
|
||||
|
||||
fireEvent.press(screen.getByText('Attach Location'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Permission Denied',
|
||||
'Location permission is required to attach coordinates.'
|
||||
)
|
||||
)
|
||||
expect(procCount(fetchMock, 'admin.order.updateAddressCoords')).toBe(0)
|
||||
})
|
||||
it('opens the coordinates in Google Maps only when present', () => {
|
||||
const props = renderMenu({ latitude: 16.75, longitude: 78.0 })
|
||||
|
||||
fireEvent.press(screen.getByText('Open in Maps'))
|
||||
|
||||
expect(Linking.openURL).toHaveBeenCalledWith(
|
||||
'https://www.google.com/maps/search/?api=1&query=16.75,78'
|
||||
)
|
||||
expect(props.onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('alerts instead of opening maps when coordinates are missing', () => {
|
||||
renderMenu({ latitude: null, longitude: null })
|
||||
|
||||
expect(screen.queryByText('Open in Maps')).toBeNull()
|
||||
})
|
||||
|
||||
it('sends WhatsApp to the phone parsed from the address', () => {
|
||||
renderMenu()
|
||||
|
||||
fireEvent.press(screen.getByText('Message On WhatsApp'))
|
||||
|
||||
expect(Linking.openURL).toHaveBeenCalledWith('whatsapp://send?phone=+919876543210')
|
||||
})
|
||||
|
||||
it('shows the welcome message row only for a first order and opens WhatsApp', () => {
|
||||
renderMenu({ isFirstOrder: true })
|
||||
|
||||
expect(screen.getByText('Send Welcome Msg')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('Send Welcome Msg'))
|
||||
|
||||
expect(Linking.openURL).toHaveBeenCalledWith('whatsapp://send?phone=+919876543210')
|
||||
})
|
||||
|
||||
it('hides the welcome message row for repeat orders', () => {
|
||||
renderMenu({ isFirstOrder: false })
|
||||
|
||||
expect(screen.queryByText('Send Welcome Msg')).toBeNull()
|
||||
})
|
||||
|
||||
it('prefills the welcome message when opening the first-order WhatsApp', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.order.updateAddressCoords': { success: true },
|
||||
'admin.region.getRegionConstants': [{ key: 'welcomeMessage', value: 'Hello & welcome!' }],
|
||||
},
|
||||
})
|
||||
renderMenu({ isFirstOrder: true })
|
||||
|
||||
// The constant loads async; retry until the handler sees it.
|
||||
await waitFor(() => {
|
||||
fireEvent.press(screen.getByText('Send Welcome Msg'))
|
||||
expect(Linking.openURL).toHaveBeenCalledWith(
|
||||
'whatsapp://send?phone=+919876543210&text=Hello%20%26%20welcome!'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('dials the phone parsed from the address', () => {
|
||||
renderMenu()
|
||||
|
||||
fireEvent.press(screen.getByText('Dial Mobile Number'))
|
||||
|
||||
expect(Linking.openURL).toHaveBeenCalledWith('tel:9876543210')
|
||||
})
|
||||
|
||||
it('alerts when the address has no phone number', () => {
|
||||
renderMenu({ address: '12 Main St, City' })
|
||||
|
||||
fireEvent.press(screen.getByText('Message On WhatsApp'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith('No phone number found')
|
||||
expect(Linking.openURL).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,275 +0,0 @@
|
|||
/**
|
||||
* ProductForm (src/components/ProductForm.tsx) — the shared create/edit form.
|
||||
* Covers render, store options, variant add/remove, validation gating and the
|
||||
* submit payload.
|
||||
*
|
||||
* KNOWN APP BUG (src/components/ProductForm.tsx:80): `variantSignature` calls
|
||||
* `a.featureValue.trim()` unguarded, so Yup validation throws whenever any
|
||||
* attribute has an empty value. Triggering it from empty fields makes
|
||||
* `validateForm()` reject and the form unusable. The submit tests here seed the
|
||||
* form with valid `initialValues` so no empty attribute is ever validated.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import ProductForm from '@/src/components/ProductForm'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const validValues = (overrides: Record<string, unknown> = {}) => ({
|
||||
name: 'Paneer',
|
||||
shortDescription: 'Fresh',
|
||||
longDescription: 'Very fresh',
|
||||
storeId: 1,
|
||||
productType: 'item' as const,
|
||||
variants: [
|
||||
{
|
||||
id: undefined,
|
||||
name: '',
|
||||
price: 200,
|
||||
marketPrice: null,
|
||||
isFlashAvailable: false,
|
||||
flashPrice: null,
|
||||
isOffer: false,
|
||||
isComboOnly: false,
|
||||
isDeleted: false,
|
||||
isSuspended: false,
|
||||
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
|
||||
comboItems: [],
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const stores = [
|
||||
{ id: 1, name: 'Main Store' },
|
||||
{ id: 2, name: 'Second Store' },
|
||||
]
|
||||
|
||||
describe('ProductForm', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the fields and the seeded variant', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'common.getStoresSummary': { stores } },
|
||||
})
|
||||
renderWithProviders(
|
||||
<ProductForm mode="create" initialValues={validValues()} onSubmit={jest.fn()} isLoading={false} />
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('product-name-input').props.value).toBe('Paneer')
|
||||
expect(screen.getByTestId('variant-0-price').props.value).toBe('200')
|
||||
expect(screen.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
|
||||
expect(screen.getByTestId('variant-0-attr-0-value').props.value).toBe('1 kg')
|
||||
expect(screen.getByText('Create Product')).toBeVisible()
|
||||
})
|
||||
|
||||
it('loads store options from getStoresSummary', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.getStoresSummary': { stores } },
|
||||
})
|
||||
renderWithProviders(
|
||||
<ProductForm mode="create" initialValues={validValues()} onSubmit={jest.fn()} isLoading={false} />
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(api.fetchMock).toHaveBeenCalled()
|
||||
)
|
||||
expect(screen.getByTestId('product-store-dropdown')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows edit-mode labels and the suspend checkbox', () => {
|
||||
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
|
||||
renderWithProviders(
|
||||
<ProductForm
|
||||
mode="edit"
|
||||
initialValues={validValues()}
|
||||
onSubmit={jest.fn()}
|
||||
isLoading={false}
|
||||
existingVariantImages={[[]]}
|
||||
existingVariantImageKeys={[[]]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Save Changes')).toBeVisible()
|
||||
expect(screen.getByTestId('variant-0-suspend')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the saving label while isLoading is true', () => {
|
||||
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
|
||||
renderWithProviders(
|
||||
<ProductForm mode="edit" initialValues={validValues()} onSubmit={jest.fn()} isLoading />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Saving...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('removes a non-existing variant', () => {
|
||||
const onSubmit = jest.fn()
|
||||
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
|
||||
renderWithProviders(
|
||||
<ProductForm
|
||||
mode="create"
|
||||
initialValues={validValues({
|
||||
variants: [
|
||||
{
|
||||
id: undefined,
|
||||
name: 'A',
|
||||
price: 100,
|
||||
marketPrice: null,
|
||||
isFlashAvailable: false,
|
||||
flashPrice: null,
|
||||
isOffer: false,
|
||||
isComboOnly: false,
|
||||
isDeleted: false,
|
||||
isSuspended: false,
|
||||
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
|
||||
comboItems: [],
|
||||
},
|
||||
{
|
||||
id: undefined,
|
||||
name: 'B',
|
||||
price: 120,
|
||||
marketPrice: null,
|
||||
isFlashAvailable: false,
|
||||
flashPrice: null,
|
||||
isOffer: false,
|
||||
isComboOnly: false,
|
||||
isDeleted: false,
|
||||
isSuspended: false,
|
||||
features: [{ featureName: 'quantity', featureValue: '2 kg' }],
|
||||
comboItems: [],
|
||||
},
|
||||
],
|
||||
})}
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('variant-1-price')).toBeVisible()
|
||||
fireEvent.press(screen.getByTestId('variant-1-remove'))
|
||||
expect(screen.queryByTestId('variant-1-price')).toBeNull()
|
||||
})
|
||||
|
||||
it('submits a valid form with the seeded values', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.getStoresSummary': { stores } },
|
||||
})
|
||||
renderWithProviders(
|
||||
<ProductForm mode="create" initialValues={validValues()} onSubmit={onSubmit} isLoading={false} />
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByTestId('create-product-button'))
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
const normalized = onSubmit.mock.calls[0][0]
|
||||
expect(normalized.name).toBe('Paneer')
|
||||
expect(normalized.variants[0].price).toBe(200)
|
||||
expect(normalized.variants[0].features).toEqual([
|
||||
{ featureName: 'quantity', featureValue: '1 kg' },
|
||||
])
|
||||
// create mode passes an empty deleted-keys list.
|
||||
expect(onSubmit.mock.calls[0][2]).toEqual([])
|
||||
expect(api.fetchMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('alerts instead of submitting when a price is invalid', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
setupApiMocks({ procedures: { 'common.getStoresSummary': { stores } } })
|
||||
renderWithProviders(
|
||||
<ProductForm
|
||||
mode="create"
|
||||
initialValues={validValues({
|
||||
variants: [
|
||||
{
|
||||
id: undefined,
|
||||
name: '',
|
||||
price: undefined,
|
||||
marketPrice: null,
|
||||
isFlashAvailable: false,
|
||||
flashPrice: null,
|
||||
isOffer: false,
|
||||
isComboOnly: false,
|
||||
isDeleted: false,
|
||||
isSuspended: false,
|
||||
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
|
||||
comboItems: [],
|
||||
},
|
||||
],
|
||||
})}
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByTestId('create-product-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Check your form', expect.any(String))
|
||||
)
|
||||
expect(onSubmit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lists global stores in the picker and marks them (global)', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'common.getStoresSummary': {
|
||||
stores: [
|
||||
{ id: 1, name: 'Main Store' },
|
||||
{ id: 3, name: 'Meat Store', isGlobal: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(
|
||||
<ProductForm
|
||||
mode="create"
|
||||
initialValues={validValues({ storeId: 3 })}
|
||||
onSubmit={jest.fn()}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
// The selected global store is offered (otherwise the trigger would fall
|
||||
// back to the placeholder) and its label carries the global marker.
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText('Meat Store (global)').length).toBeGreaterThan(0)
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByTestId('product-store-dropdown'))
|
||||
expect(await screen.findByTestId('product-store-dropdown-option-3')).toBeVisible()
|
||||
})
|
||||
|
||||
it('adopts the first regional store when the form seeds no store', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'common.getStoresSummary': {
|
||||
stores: [
|
||||
{ id: 3, name: 'Meat Store', isGlobal: true },
|
||||
{ id: 2, name: 'Second Store' },
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(
|
||||
<ProductForm
|
||||
mode="create"
|
||||
initialValues={validValues({ storeId: 0 })}
|
||||
onSubmit={jest.fn()}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
// Prefers the regional store even though the global one is listed first.
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText('Second Store').length).toBeGreaterThan(0)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,243 +0,0 @@
|
|||
/**
|
||||
* ProductGroupForm (components/ProductGroupForm.tsx) — create/edit titles,
|
||||
* name validation, createGroup/updateGroup payloads, product selection and the
|
||||
* cancel/close handlers.
|
||||
*
|
||||
* NOTE: the embedded ProductsSelector emits SKU ids, but createGroup /
|
||||
* updateGroup expect productInfo ids (db_helper_postgres product.ts:315/345).
|
||||
* The payloads below are asserted as observed and reported as an app bug.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import ProductGroupForm, { ProductGroup } from '@/components/ProductGroupForm'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { createQueryClient, renderWithProviders } from '../helpers/render'
|
||||
|
||||
const skusResponse = {
|
||||
skus: [
|
||||
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
|
||||
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
|
||||
],
|
||||
}
|
||||
|
||||
const procedures = {
|
||||
'common.product.getAllProductsSummary': { products: [] },
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.product.createGroup': {
|
||||
group: { id: 1, groupName: 'Meat', description: null, createdAt: '2024-01-01' },
|
||||
message: 'Group created successfully',
|
||||
},
|
||||
'admin.product.updateGroup': {
|
||||
group: { id: 5, groupName: 'Meat', description: 'Bundle', createdAt: '2024-01-01' },
|
||||
message: 'Group updated successfully',
|
||||
},
|
||||
}
|
||||
|
||||
const existingGroup: ProductGroup = {
|
||||
id: 5,
|
||||
groupName: 'Beef Box',
|
||||
description: 'Bundle',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
products: [{ id: 10 }, { id: 11 }],
|
||||
productCount: 2,
|
||||
}
|
||||
|
||||
describe('ProductGroupForm', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders in create mode', () => {
|
||||
renderWithProviders(
|
||||
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Create Product Group')).toBeVisible()
|
||||
expect(screen.getByText('Group Name *')).toBeVisible()
|
||||
expect(screen.getByText('Description')).toBeVisible()
|
||||
expect(screen.getByText('Save')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders in edit mode with the group seeded', () => {
|
||||
renderWithProviders(
|
||||
<ProductGroupForm
|
||||
group={existingGroup}
|
||||
onClose={jest.fn()}
|
||||
onSuccess={jest.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Edit Product Group')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Beef Box')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Bundle')).toBeVisible()
|
||||
})
|
||||
|
||||
it('blocks submission when the group name is empty', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
renderWithProviders(
|
||||
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
expect(await screen.findByText('Group name is required')).toBeVisible()
|
||||
expect(procCount(fetchMock, 'admin.product.createGroup')).toBe(0)
|
||||
})
|
||||
|
||||
it('creates a group with the entered values', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const onSuccess = jest.fn()
|
||||
renderWithProviders(
|
||||
<ProductGroupForm onClose={jest.fn()} onSuccess={onSuccess} />
|
||||
)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter description (optional)'),
|
||||
'Protein'
|
||||
)
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.createGroup'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.product.createGroup')).toEqual({
|
||||
group_name: 'Meat',
|
||||
description: 'Protein',
|
||||
product_ids: [],
|
||||
})
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it('creates a group carrying the selected SKU ids as product_ids', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
renderWithProviders(
|
||||
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
|
||||
fireEvent.press(screen.getByText('Select products'))
|
||||
fireEvent.press(await screen.findByLabelText('undefined-option-1'))
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.createGroup'))
|
||||
// Observed bug: product_ids contains the selected SKU id (1), not product id 10.
|
||||
expect(lastProcedureInput(fetchMock, 'admin.product.createGroup')).toMatchObject({
|
||||
group_name: 'Meat',
|
||||
product_ids: [1],
|
||||
})
|
||||
})
|
||||
|
||||
it('updates the group with its seeded product ids', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const onSuccess = jest.fn()
|
||||
renderWithProviders(
|
||||
<ProductGroupForm
|
||||
group={existingGroup}
|
||||
onClose={jest.fn()}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.changeText(screen.getByDisplayValue('Beef Box'), 'Beef Combo')
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.updateGroup'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.product.updateGroup')).toEqual({
|
||||
id: 5,
|
||||
group_name: 'Beef Combo',
|
||||
description: 'Bundle',
|
||||
product_ids: [10, 11],
|
||||
})
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it('invalidates the getGroups query with the tRPC array key on create and update', async () => {
|
||||
// Spy on an injected client: utils.admin.product.getGroups.invalidate() calls
|
||||
// queryClient.invalidateQueries({ queryKey }), and getGroups is not mounted by
|
||||
// this form, so nothing hits fetch — the invalidation itself is the observable.
|
||||
const client = createQueryClient()
|
||||
const invalidateSpy = jest.spyOn(client, 'invalidateQueries') // keeps calling through
|
||||
|
||||
// tRPC keys are [pathArray, ...]. The old bug passed a dotted string
|
||||
// ('admin.product.getGroups'); only the array form is correct.
|
||||
const pathOf = (call: unknown[]) => {
|
||||
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
|
||||
return Array.isArray(key) ? key[0] : null
|
||||
}
|
||||
|
||||
// Create path — same props/flow as 'creates a group with the entered values'.
|
||||
const created = renderWithProviders(
|
||||
<ProductGroupForm onClose={jest.fn()} onSuccess={jest.fn()} />,
|
||||
{ queryClient: client }
|
||||
)
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
|
||||
expect(invalidateSpy.mock.calls.map(pathOf)).toContainEqual([
|
||||
'admin',
|
||||
'product',
|
||||
'getGroups',
|
||||
])
|
||||
|
||||
created.unmount()
|
||||
|
||||
// Update path — same props/flow as 'updates the group with its seeded product ids'.
|
||||
const callsAfterCreate = invalidateSpy.mock.calls.length
|
||||
renderWithProviders(
|
||||
<ProductGroupForm
|
||||
group={existingGroup}
|
||||
onClose={jest.fn()}
|
||||
onSuccess={jest.fn()}
|
||||
/>,
|
||||
{ queryClient: client }
|
||||
)
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(invalidateSpy.mock.calls.length).toBeGreaterThan(callsAfterCreate)
|
||||
)
|
||||
expect(invalidateSpy.mock.calls.slice(callsAfterCreate).map(pathOf)).toContainEqual([
|
||||
'admin',
|
||||
'product',
|
||||
'getGroups',
|
||||
])
|
||||
})
|
||||
|
||||
it('calls onClose from the Cancel button', () => {
|
||||
const onClose = jest.fn()
|
||||
renderWithProviders(
|
||||
<ProductGroupForm onClose={onClose} onSuccess={jest.fn()} />
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Cancel'))
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('calls onClose from the header close icon', () => {
|
||||
const onClose = jest.fn()
|
||||
renderWithProviders(
|
||||
<ProductGroupForm onClose={onClose} onSuccess={jest.fn()} />
|
||||
)
|
||||
|
||||
const closeIcon = screen
|
||||
.UNSAFE_getAllByType(MaterialIcons)
|
||||
.find((i) => i.props.name === 'close') as Parameters<typeof fireEvent.press>[0]
|
||||
fireEvent.press(closeIcon)
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
/**
|
||||
* ProductListDialog (components/ProductListDialog.tsx) — a read-only bottom
|
||||
* dialog listing the products passed in as props.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { screen } from '@testing-library/react-native'
|
||||
|
||||
import { ProductListDialog } from '@/components/ProductListDialog'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const products = [
|
||||
{ id: 1, name: 'Chicken' },
|
||||
{ id: 2, name: 'Mutton' },
|
||||
{ id: 3, name: 'Fish' },
|
||||
]
|
||||
|
||||
describe('ProductListDialog', () => {
|
||||
it('renders the product count and each product when open', () => {
|
||||
renderWithProviders(
|
||||
<ProductListDialog open onClose={jest.fn()} products={products} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Products (3)')).toBeVisible()
|
||||
expect(screen.getByText('Chicken')).toBeVisible()
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
expect(screen.getByText('Fish')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows a count of zero for an empty list', () => {
|
||||
renderWithProviders(
|
||||
<ProductListDialog open onClose={jest.fn()} products={[]} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Products (0)')).toBeVisible()
|
||||
})
|
||||
|
||||
it('hides its content while closed', () => {
|
||||
renderWithProviders(
|
||||
<ProductListDialog open={false} onClose={jest.fn()} products={products} />
|
||||
)
|
||||
|
||||
// A closed Modal does not mount its children in the tree.
|
||||
expect(screen.queryByText('Products (3)')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
/**
|
||||
* ProductsSelector (components/ProductsSelector.tsx) — a dropdown-backed SKU
|
||||
* picker with optional product-group selection.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import ProductsSelector from '@/components/ProductsSelector'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const skus = [
|
||||
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
|
||||
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
|
||||
]
|
||||
|
||||
const skusResponse = { skus }
|
||||
|
||||
describe('ProductsSelector', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
})
|
||||
|
||||
it('loads SKUs from getAllSkusSummary', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(<ProductsSelector value={[]} onChange={jest.fn()} testID="sku-select" />)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
expect(screen.getByTestId('sku-select')).toBeVisible()
|
||||
})
|
||||
|
||||
it('selects a product and reports the numeric id', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
const onChange = jest.fn()
|
||||
renderWithProviders(
|
||||
<ProductsSelector value={[]} onChange={onChange} multiple={false} testID="sku-select" />
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
|
||||
fireEvent.press(screen.getByTestId('sku-select'))
|
||||
fireEvent.press(await screen.findByTestId('sku-select-option-1'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('toggles multiple selection', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
const onChange = jest.fn()
|
||||
renderWithProviders(
|
||||
<ProductsSelector value={[1]} onChange={onChange} multiple testID="sku-select" />
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
fireEvent.press(screen.getByTestId('sku-select'))
|
||||
fireEvent.press(await screen.findByTestId('sku-select-option-2'))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith([1, 2])
|
||||
})
|
||||
|
||||
it('adds a group\'s SKUs when a group is selected', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
const onChange = jest.fn()
|
||||
const onGroupChange = jest.fn()
|
||||
renderWithProviders(
|
||||
<ProductsSelector
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
groups={[{ id: 100, groupName: 'Meat', products: [{ id: 10 }] }]}
|
||||
selectedGroupIds={[]}
|
||||
onGroupChange={onGroupChange}
|
||||
testID="sku-select"
|
||||
/>
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
await waitFor(() => expect(screen.getByTestId('product-groups-dropdown')).toBeVisible())
|
||||
// Opening the SKU dropdown proves allSkus has loaded into state.
|
||||
fireEvent.press(screen.getByTestId('sku-select'))
|
||||
await screen.findByTestId('sku-select-option-1')
|
||||
fireEvent.press(screen.getByTestId('product-groups-dropdown'))
|
||||
fireEvent.press(await screen.findByTestId('product-groups-dropdown-option-100'))
|
||||
|
||||
expect(onGroupChange).toHaveBeenCalledWith([100])
|
||||
expect(onChange).toHaveBeenCalledWith([1])
|
||||
})
|
||||
|
||||
it('labels a SKU that came from a selected group', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<ProductsSelector
|
||||
value={[]}
|
||||
onChange={jest.fn()}
|
||||
groups={[{ id: 100, groupName: 'Meat', products: [{ id: 10 }] }]}
|
||||
selectedGroupIds={[100]}
|
||||
showGroups
|
||||
testID="sku-select"
|
||||
/>
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
|
||||
fireEvent.press(screen.getByTestId('sku-select'))
|
||||
|
||||
expect(await screen.findByTestId('sku-select-option-1')).toBeVisible()
|
||||
// The "(from group)" suffix marks the grouped SKU.
|
||||
expect(screen.getByText(/from group/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('applies a custom labelFormat', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<ProductsSelector
|
||||
value={[]}
|
||||
onChange={jest.fn()}
|
||||
labelFormat={(sku) => `#${sku.id} ${sku.label}`}
|
||||
showGroups={false}
|
||||
testID="sku-select"
|
||||
/>
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
|
||||
fireEvent.press(screen.getByTestId('sku-select'))
|
||||
|
||||
expect(await screen.findByText(/#1 Chicken 1kg/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('passes the search query to filtering', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(<ProductsSelector value={[]} onChange={jest.fn()} testID="sku-select" />)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
await waitFor(() => expect(screen.getByTestId('sku-select')).toBeVisible())
|
||||
fireEvent.press(screen.getByTestId('sku-select'))
|
||||
|
||||
act(() => {
|
||||
fireEvent.changeText(screen.getByTestId('sku-select-search'), 'mutton')
|
||||
})
|
||||
await waitFor(() => expect(screen.getByTestId('sku-select-option-2')).toBeVisible())
|
||||
expect(screen.queryByTestId('sku-select-option-1')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,214 +0,0 @@
|
|||
/**
|
||||
* SlotForm component (components/SlotForm.tsx) — create/update mutations,
|
||||
* validation and vendor-snippet handling.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import SlotForm from '@/components/SlotForm'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const DELIVERY = new Date('2026-10-01T10:00:00.000Z')
|
||||
const FREEZE = new Date('2026-10-01T06:00:00.000Z')
|
||||
|
||||
const procedures = {
|
||||
'admin.product.getGroups': { groups: [] },
|
||||
'common.product.getAllSkusSummary': { skus: [] },
|
||||
'admin.slots.createSlot': {
|
||||
slot: { id: 10 },
|
||||
createdSnippets: [],
|
||||
message: 'Slot created successfully',
|
||||
},
|
||||
'admin.slots.updateSlot': {
|
||||
slot: { id: 7 },
|
||||
createdSnippets: [],
|
||||
message: 'Slot updated successfully',
|
||||
},
|
||||
}
|
||||
|
||||
describe('SlotForm', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the create form', () => {
|
||||
renderWithProviders(
|
||||
<SlotForm initialDeliveryTime={DELIVERY} initialFreezeTime={FREEZE} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Create New Slot')).toBeVisible()
|
||||
expect(screen.getByText('Create Slot')).toBeVisible()
|
||||
expect(screen.getByText('Vendor Snippets')).toBeVisible()
|
||||
expect(screen.getByText('Add Vendor Snippet')).toBeVisible()
|
||||
})
|
||||
|
||||
it('blocks submit when a time is missing', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<SlotForm />)
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please fill all fields')
|
||||
)
|
||||
expect(procCount(fetchMock, 'admin.slots.createSlot')).toBe(0)
|
||||
})
|
||||
|
||||
it('blocks submit when freeze time is after delivery time', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(
|
||||
<SlotForm
|
||||
initialDeliveryTime={FREEZE}
|
||||
initialFreezeTime={DELIVERY}
|
||||
/>
|
||||
)
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Freeze time must be before or equal to delivery time'
|
||||
)
|
||||
)
|
||||
expect(procCount(fetchMock, 'admin.slots.createSlot')).toBe(0)
|
||||
})
|
||||
|
||||
it('creates a slot with the mapped payload and calls onSlotAdded', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const onSlotAdded = jest.fn()
|
||||
|
||||
renderWithProviders(
|
||||
<SlotForm
|
||||
initialDeliveryTime={DELIVERY}
|
||||
initialFreezeTime={FREEZE}
|
||||
initialProductIds={[11, 12]}
|
||||
initialGroupIds={[3]}
|
||||
onSlotAdded={onSlotAdded}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.createSlot')
|
||||
)
|
||||
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.createSlot')).toEqual({
|
||||
deliveryTime: '2026-10-01T10:00:00.000Z',
|
||||
freezeTime: '2026-10-01T06:00:00.000Z',
|
||||
isActive: true,
|
||||
groupIds: [3],
|
||||
skuIds: [11, 12],
|
||||
vendorSnippets: [],
|
||||
})
|
||||
await waitFor(() => expect(onSlotAdded).toHaveBeenCalled())
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot created successfully!')
|
||||
})
|
||||
|
||||
it('includes an added vendor snippet in the create payload', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(
|
||||
<SlotForm initialDeliveryTime={DELIVERY} initialFreezeTime={FREEZE} />
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Add Vendor Snippet'))
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter snippet name'),
|
||||
'Diwali Promo'
|
||||
)
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.createSlot')
|
||||
)
|
||||
|
||||
expect(
|
||||
(lastProcedureInput(fetchMock, 'admin.slots.createSlot') as any).vendorSnippets
|
||||
).toEqual([{ name: 'Diwali Promo', skuIds: [], validTill: '' }])
|
||||
})
|
||||
|
||||
it('updates an existing slot in edit mode', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const onSlotAdded = jest.fn()
|
||||
|
||||
renderWithProviders(
|
||||
<SlotForm
|
||||
slotId={7}
|
||||
initialDeliveryTime={DELIVERY}
|
||||
initialFreezeTime={FREEZE}
|
||||
initialProductIds={[11]}
|
||||
onSlotAdded={onSlotAdded}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Edit Slot')).toBeVisible()
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.updateSlot')
|
||||
)
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.getSlotById')
|
||||
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.updateSlot')).toEqual({
|
||||
id: 7,
|
||||
deliveryTime: '2026-10-01T10:00:00.000Z',
|
||||
freezeTime: '2026-10-01T06:00:00.000Z',
|
||||
isActive: true,
|
||||
groupIds: [],
|
||||
skuIds: [11],
|
||||
vendorSnippets: [],
|
||||
})
|
||||
await waitFor(() => expect(onSlotAdded).toHaveBeenCalled())
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot updated successfully!')
|
||||
})
|
||||
|
||||
it('refetches the mounted slot detail after a successful update in edit mode', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(
|
||||
<SlotForm
|
||||
slotId={7}
|
||||
initialDeliveryTime={DELIVERY}
|
||||
initialFreezeTime={FREEZE}
|
||||
initialProductIds={[11]}
|
||||
/>
|
||||
)
|
||||
|
||||
// Edit mode mounts `admin.slots.getSlotById` with enabled: true, so there is
|
||||
// a live query under `admin.slots` for the invalidation to refetch.
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.slots.getSlotById')).toBeGreaterThan(0)
|
||||
)
|
||||
|
||||
// Baseline captured immediately before the press: the tests share one
|
||||
// module-singleton httpBatchLink client, so counts can leak across cases —
|
||||
// assert a delta, never an absolute number.
|
||||
const before = procCount(fetchMock, 'admin.slots.getSlotById')
|
||||
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.updateSlot')
|
||||
)
|
||||
|
||||
// `utils.admin.slots.invalidate()` (SlotForm.tsx update onSuccess) invalidates
|
||||
// the whole `admin.slots` path, which refetches the mounted detail query.
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.slots.getSlotById')).toBeGreaterThan(
|
||||
before
|
||||
)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,133 +0,0 @@
|
|||
/**
|
||||
* SnippetMenu (components/SnippetMenu.tsx) — per-snippet options dialog:
|
||||
* view orders, edit, copy URL and delete with confirmation.
|
||||
*
|
||||
* The trigger has no testID, so it is located as the first TouchableOpacity
|
||||
* rendered by the component (the dialog's backdrop only mounts while open).
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, Clipboard, TouchableOpacity } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import Toast from 'react-native-toast-message'
|
||||
|
||||
import { SnippetMenu } from '@/components/SnippetMenu'
|
||||
import type { VendorSnippet } from '@/types/vendor-snippets'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const snippet: VendorSnippet = {
|
||||
id: 5,
|
||||
snippetCode: 'VS_5',
|
||||
slotId: 2,
|
||||
isPermanent: false,
|
||||
skuIds: [10],
|
||||
products: [{ id: 10, name: 'Chicken' }],
|
||||
validTill: null,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
accessUrl: 'https://app.freshyo.in/vendor-order-list?id=VS_5',
|
||||
}
|
||||
|
||||
const onEdit = jest.fn()
|
||||
const onDelete = jest.fn()
|
||||
const onViewOrders = jest.fn()
|
||||
|
||||
const renderMenu = (overrides: Partial<VendorSnippet> = {}) =>
|
||||
renderWithProviders(
|
||||
<SnippetMenu
|
||||
snippet={{ ...snippet, ...overrides }}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onViewOrders={onViewOrders}
|
||||
/>
|
||||
)
|
||||
|
||||
const openMenu = (result: ReturnType<typeof renderWithProviders>) => {
|
||||
fireEvent.press(result.UNSAFE_getAllByType(TouchableOpacity)[0])
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('SnippetMenu', () => {
|
||||
beforeEach(() => {
|
||||
onEdit.mockClear()
|
||||
onDelete.mockClear()
|
||||
onViewOrders.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
jest.spyOn(Clipboard, 'setString').mockImplementation(async () => {})
|
||||
})
|
||||
|
||||
it('opens the options dialog with every action', async () => {
|
||||
const result = renderMenu()
|
||||
|
||||
expect(screen.queryByText('Snippet Options')).toBeNull()
|
||||
openMenu(result)
|
||||
|
||||
expect(await screen.findByText('Snippet Options')).toBeVisible()
|
||||
expect(screen.getByText('View Orders')).toBeVisible()
|
||||
expect(screen.getByText('Edit')).toBeVisible()
|
||||
expect(screen.getByText('Copy URL')).toBeVisible()
|
||||
expect(screen.getByText('Delete')).toBeVisible()
|
||||
})
|
||||
|
||||
it('calls onViewOrders with the snippet code', async () => {
|
||||
const result = renderMenu()
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('View Orders'))
|
||||
expect(onViewOrders).toHaveBeenCalledWith('VS_5')
|
||||
})
|
||||
|
||||
it('calls onEdit with the snippet', async () => {
|
||||
const result = renderMenu()
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Edit'))
|
||||
expect(onEdit).toHaveBeenCalledWith(expect.objectContaining({ id: 5 }))
|
||||
})
|
||||
|
||||
it('asks for confirmation before deleting and calls onDelete', async () => {
|
||||
const result = renderMenu()
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Delete'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Delete Snippet',
|
||||
'Are you sure you want to delete this vendor snippet?',
|
||||
expect.any(Array)
|
||||
)
|
||||
expect(onDelete).not.toHaveBeenCalled()
|
||||
|
||||
pressLastAlertButton('Delete')
|
||||
expect(onDelete).toHaveBeenCalledWith(5)
|
||||
})
|
||||
|
||||
it('copies the access URL to the clipboard', async () => {
|
||||
const result = renderMenu()
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Copy URL'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Clipboard.setString).toHaveBeenCalledWith(snippet.accessUrl)
|
||||
)
|
||||
expect(Toast.show).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'success', text1: 'URL copied to clipboard' })
|
||||
)
|
||||
})
|
||||
|
||||
it('alerts when there is no URL to copy', async () => {
|
||||
const result = renderMenu({ accessUrl: undefined })
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Copy URL'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'No URL available to copy')
|
||||
expect(Clipboard.setString).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
/**
|
||||
* SnippetOrdersView (components/SnippetOrdersView.tsx) — read-only list of the
|
||||
* orders matched by a vendor snippet, with per-order totals and an empty state.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, screen } from '@testing-library/react-native'
|
||||
|
||||
import SnippetOrdersView from '@/components/SnippetOrdersView'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
type Order = React.ComponentProps<typeof SnippetOrdersView>['orders'][number]
|
||||
|
||||
const order = (overrides: Partial<Order> = {}): Order => ({
|
||||
orderId: 'ORD1',
|
||||
orderDate: '2026-01-02T09:00:00.000Z',
|
||||
customerName: 'Alice',
|
||||
totalAmount: '100.00',
|
||||
slotInfo: { time: '2026-01-03T10:00:00.000Z', sequence: [] },
|
||||
snippetCode: 'VS_5',
|
||||
matchedProducts: [10],
|
||||
products: [
|
||||
{
|
||||
productId: 10,
|
||||
productName: 'Chicken',
|
||||
quantity: 2,
|
||||
price: 50,
|
||||
unit: 'kg',
|
||||
subtotal: 100,
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('SnippetOrdersView', () => {
|
||||
it('renders the header with snippet code, count and revenue', () => {
|
||||
renderWithProviders(
|
||||
<SnippetOrdersView
|
||||
orders={[order(), order({ orderId: 'ORD2', totalAmount: '50.50', customerName: 'Bob' })]}
|
||||
snippetCode="VS_5"
|
||||
onClose={jest.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Orders for "VS_5"')).toBeVisible()
|
||||
expect(screen.getByText('2 orders • Total: ₹150.50')).toBeVisible()
|
||||
})
|
||||
|
||||
it('pluralises a single order', () => {
|
||||
renderWithProviders(
|
||||
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" onClose={jest.fn()} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('1 order • Total: ₹100.00')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders an order card with products and the matched flag', () => {
|
||||
renderWithProviders(
|
||||
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" onClose={jest.fn()} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('ORD1')).toBeVisible()
|
||||
expect(screen.getByText('Alice')).toBeVisible()
|
||||
// Order total + product subtotal both render ₹100.00.
|
||||
expect(screen.getAllByText('₹100.00')).toHaveLength(2)
|
||||
expect(screen.getByText('Chicken ⭐')).toBeVisible()
|
||||
expect(screen.getByText('2 kg × ₹50')).toBeVisible()
|
||||
expect(
|
||||
screen.getByText('Matched 1 product(s) from snippet "VS_5"')
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no matching orders', () => {
|
||||
renderWithProviders(
|
||||
<SnippetOrdersView orders={[]} snippetCode="VS_5" onClose={jest.fn()} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('0 orders • Total: ₹0.00')).toBeVisible()
|
||||
expect(screen.getByText('No matching orders')).toBeVisible()
|
||||
expect(
|
||||
screen.getByText("No orders found that match this snippet's criteria")
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('closes via the header button', () => {
|
||||
const onClose = jest.fn()
|
||||
renderWithProviders(
|
||||
<SnippetOrdersView orders={[order()]} snippetCode="VS_5" onClose={onClose} />
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('✕'))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,175 +0,0 @@
|
|||
/**
|
||||
* StoreForm component (components/StoreForm.tsx) — validation, owner/product
|
||||
* selection and the submit payload.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import StoreForm, { StoreFormData } from '@/components/StoreForm'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled } from '../mocks/procedures'
|
||||
import { searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const CREATE_INITIAL: StoreFormData = {
|
||||
name: '',
|
||||
description: '',
|
||||
products: [],
|
||||
}
|
||||
|
||||
const procedures = {
|
||||
'admin.staffUser.getStaff': {
|
||||
staff: [
|
||||
{ id: 1, name: 'shafi', role: null, permissions: [] },
|
||||
{ id: 2, name: 'naveen', role: null, permissions: [] },
|
||||
],
|
||||
},
|
||||
'admin.product.getProducts': { products: [], count: 0 },
|
||||
'common.product.getAllSkusSummary': {
|
||||
skus: [
|
||||
{
|
||||
id: 11,
|
||||
productId: 1,
|
||||
productName: 'Chicken',
|
||||
label: 'Chicken 1kg',
|
||||
images: [],
|
||||
storeId: null,
|
||||
price: '100',
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
describe('StoreForm', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the create form', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
renderWithProviders(
|
||||
<StoreForm
|
||||
mode="create"
|
||||
initialValues={CREATE_INITIAL}
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByPlaceholderText('Enter store name')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter store description')).toBeVisible()
|
||||
expect(screen.getByText('Select products')).toBeVisible()
|
||||
expect(screen.getByText('Create Store')).toBeVisible()
|
||||
})
|
||||
|
||||
it('BUG: submits even when the name is empty (validation is bypassed)', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
renderWithProviders(
|
||||
<StoreForm
|
||||
mode="create"
|
||||
initialValues={CREATE_INITIAL}
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Create Store'))
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
// Intended: Yup `name` is required and Formik should block this.
|
||||
// Actual: the button calls the `onSubmit` prop directly, so the
|
||||
// validationSchema never runs.
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: '' })
|
||||
)
|
||||
})
|
||||
|
||||
it('submits the typed name with the selected product', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
renderWithProviders(
|
||||
<StoreForm
|
||||
mode="create"
|
||||
initialValues={CREATE_INITIAL}
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter store name'),
|
||||
'Freshyo Form'
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Select products'))
|
||||
fireEvent.press(await screen.findByText('Chicken - ₹100'))
|
||||
|
||||
fireEvent.press(screen.getByText('Create Store'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
name: 'Freshyo Form',
|
||||
description: '',
|
||||
products: [11],
|
||||
imageUrl: undefined,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('renders edit mode with prefilled values and the update label', () => {
|
||||
const onSubmit = jest.fn()
|
||||
renderWithProviders(
|
||||
<StoreForm
|
||||
mode="edit"
|
||||
initialValues={{
|
||||
name: 'Existing',
|
||||
description: 'Old description',
|
||||
products: [],
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
isLoading={false}
|
||||
storeId={3}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByDisplayValue('Existing')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Old description')).toBeVisible()
|
||||
expect(screen.getByText('Update Store')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the pending label when isLoading', () => {
|
||||
renderWithProviders(
|
||||
<StoreForm
|
||||
mode="create"
|
||||
initialValues={CREATE_INITIAL}
|
||||
onSubmit={jest.fn()}
|
||||
isLoading
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Creating...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('loads products', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
renderWithProviders(
|
||||
<StoreForm
|
||||
mode="create"
|
||||
initialValues={CREATE_INITIAL}
|
||||
onSubmit={jest.fn()}
|
||||
isLoading={false}
|
||||
/>
|
||||
)
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.getProducts'))
|
||||
})
|
||||
})
|
||||
|
|
@ -1,160 +0,0 @@
|
|||
/**
|
||||
* TagForm (src/components/TagForm.tsx) — name/description fields, dashboard
|
||||
* checkbox, related-store dropdown, product selection and submit payload.
|
||||
*
|
||||
* The submit button has no testID in source; it is located by its label.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import TagForm from '@/src/components/TagForm'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { expectProcedureCalled } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const baseValues = {
|
||||
tagName: 'Bestsellers',
|
||||
tagDescription: 'Top picks',
|
||||
isDashboardTag: false,
|
||||
relatedStores: [],
|
||||
productIds: [],
|
||||
}
|
||||
|
||||
const stores = [
|
||||
{ id: 1, name: 'Main Store' },
|
||||
{ id: 2, name: 'Second Store' },
|
||||
]
|
||||
|
||||
const skusResponse = {
|
||||
skus: [
|
||||
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
|
||||
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
|
||||
],
|
||||
}
|
||||
|
||||
describe('TagForm', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
})
|
||||
|
||||
it('renders the create-mode fields with seeded values', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<TagForm mode="create" initialValues={baseValues} onSubmit={jest.fn()} isLoading={false} stores={stores} />
|
||||
)
|
||||
|
||||
expect(screen.getByDisplayValue('Bestsellers')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Top picks')).toBeVisible()
|
||||
expect(screen.getByText('Mark as Dashboard Tag')).toBeVisible()
|
||||
expect(screen.getByText('Create Tag')).toBeVisible()
|
||||
expect(screen.getByText('No products selected yet')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows edit-mode labels', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<TagForm mode="edit" initialValues={baseValues} onSubmit={jest.fn()} isLoading={false} stores={stores} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Update Tag')).toBeVisible()
|
||||
expect(screen.getByText('Tag Image (Upload new to replace)')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the submit-progress label', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<TagForm mode="create" initialValues={baseValues} onSubmit={jest.fn()} isLoading stores={stores} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('Creating...')).toBeVisible()
|
||||
expect(screen.queryByText('Create Tag')).toBeNull()
|
||||
})
|
||||
|
||||
it('submits the current form values', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<TagForm mode="create" initialValues={baseValues} onSubmit={onSubmit} isLoading={false} stores={stores} />
|
||||
)
|
||||
|
||||
fireEvent.changeText(screen.getByDisplayValue('Bestsellers'), 'Featured')
|
||||
fireEvent.press(screen.getByText('Create Tag'))
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
const [values, images, removedExisting] = onSubmit.mock.calls[0]
|
||||
expect(values.tagName).toBe('Featured')
|
||||
expect(values.tagDescription).toBe('Top picks')
|
||||
expect(values.productIds).toEqual([])
|
||||
expect(images).toEqual([])
|
||||
expect(removedExisting).toBe(false)
|
||||
})
|
||||
|
||||
it('toggles the dashboard-tag checkbox', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<TagForm mode="create" initialValues={baseValues} onSubmit={onSubmit} isLoading={false} stores={stores} />
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByRole('checkbox'))
|
||||
fireEvent.press(screen.getByText('Create Tag'))
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit.mock.calls[0][0].isDashboardTag).toBe(true)
|
||||
})
|
||||
|
||||
it('adds a selected product to the ordered list and submits its id', async () => {
|
||||
const onSubmit = jest.fn()
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
const result = renderWithProviders(
|
||||
<TagForm mode="create" initialValues={baseValues} onSubmit={onSubmit} isLoading={false} stores={stores} />
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'common.product.getAllSkusSummary')
|
||||
)
|
||||
|
||||
// ProductsSelector is rendered without a testID. Open the SKU dropdown by
|
||||
// its placeholder text, then pick the first option.
|
||||
fireEvent.press(screen.getByText('Search and select products...'))
|
||||
const option = await screen.findByLabelText('undefined-option-1')
|
||||
fireEvent.press(option)
|
||||
|
||||
await waitFor(() => expect(screen.getAllByText('Chicken 1kg').length).toBeGreaterThan(0))
|
||||
|
||||
fireEvent.press(screen.getByText('Create Tag'))
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
|
||||
expect(onSubmit.mock.calls[0][0].productIds).toEqual([10])
|
||||
})
|
||||
|
||||
it('renders seeded products from productIds', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'common.product.getAllSkusSummary': skusResponse },
|
||||
})
|
||||
renderWithProviders(
|
||||
<TagForm
|
||||
mode="edit"
|
||||
initialValues={{ ...baseValues, productIds: [11] }}
|
||||
onSubmit={jest.fn()}
|
||||
isLoading={false}
|
||||
stores={stores}
|
||||
/>
|
||||
)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Mutton 1kg')).toBeVisible())
|
||||
expect(screen.getByText(/1 items/)).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,118 +0,0 @@
|
|||
/**
|
||||
* TagMenu (src/components/TagMenu.tsx) — per-tag options menu: open dialog,
|
||||
* navigate to edit, and delete with confirmation.
|
||||
*
|
||||
* The trigger has no testID in source, so it is located as the first
|
||||
* TouchableOpacity rendered by the component.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, TouchableOpacity } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import { TagMenu } from '@/src/components/TagMenu'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const openMenu = (result: ReturnType<typeof renderWithProviders>) => {
|
||||
const trigger = result.UNSAFE_getAllByType(TouchableOpacity)[0]
|
||||
fireEvent.press(trigger)
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('TagMenu', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('opens the options dialog', async () => {
|
||||
const result = renderWithProviders(<TagMenu tagId={1} />)
|
||||
|
||||
expect(screen.queryByText('Tag Options')).toBeNull()
|
||||
openMenu(result)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Tag Options')).toBeVisible())
|
||||
expect(screen.getByText('Edit Tag')).toBeVisible()
|
||||
expect(screen.getByText('Delete Tag')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to the edit screen', async () => {
|
||||
const result = renderWithProviders(<TagMenu tagId={7} />)
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Edit Tag'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/product-tags/edit?tagId=7'
|
||||
)
|
||||
})
|
||||
|
||||
it('asks for confirmation before deleting', async () => {
|
||||
const result = renderWithProviders(<TagMenu tagId={7} />)
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Delete Tag'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Delete Tag',
|
||||
'Are you sure you want to delete this tag? This action cannot be undone.',
|
||||
expect.any(Array)
|
||||
)
|
||||
})
|
||||
|
||||
it('deletes the tag and calls onDeleteSuccess', async () => {
|
||||
const onDeleteSuccess = jest.fn()
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.deleteProductTag': { message: 'Tag deleted successfully' },
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(
|
||||
<TagMenu tagId={7} onDeleteSuccess={onDeleteSuccess} />
|
||||
)
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Delete Tag'))
|
||||
pressLastAlertButton('Delete')
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.deleteProductTag'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.deleteProductTag')).toEqual({ id: 7 })
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Tag deleted successfully')
|
||||
)
|
||||
expect(onDeleteSuccess).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows an error alert when deletion fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.deleteProductTag': () => {
|
||||
throw new Error('nope')
|
||||
},
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<TagMenu tagId={7} />)
|
||||
openMenu(result)
|
||||
|
||||
fireEvent.press(await screen.findByText('Delete Tag'))
|
||||
pressLastAlertButton('Delete')
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String))
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,249 +0,0 @@
|
|||
/**
|
||||
* UserIncidentsView (components/UserIncidentsView.tsx) — incident list, empty
|
||||
* state, add-incident dialog, validation and the addUserIncident mutation.
|
||||
*
|
||||
* HARNESS BUG WORKAROUND: tests/mocks/native.ts has a stray top-level `return`
|
||||
* (line 89 → "'return' outside of function"). Re-mock the expo modules that
|
||||
* `common-ui` eagerly imports locally. See report.
|
||||
*/
|
||||
|
||||
jest.mock('expo-image', () => {
|
||||
const React = require('react')
|
||||
const { View } = require('react-native')
|
||||
const Image = (props: Record<string, unknown>) =>
|
||||
React.createElement(View, { testID: 'mock-image', ...props })
|
||||
return { __esModule: true, Image, default: Image }
|
||||
})
|
||||
|
||||
jest.mock('expo-image-picker', () => {
|
||||
const asset = { uri: 'file:///tmp/pick.jpg', fileName: 'pick.jpg', mimeType: 'image/jpeg' }
|
||||
return {
|
||||
__esModule: true,
|
||||
MediaTypeOptions: { Images: 'Images', All: 'All', Videos: 'Videos' },
|
||||
launchImageLibraryAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
launchCameraAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
requestMediaLibraryPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
requestCameraPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('expo-document-picker', () => ({
|
||||
__esModule: true,
|
||||
getDocumentAsync: jest.fn(async () => ({
|
||||
canceled: false,
|
||||
assets: [{ uri: 'file:///tmp/doc.pdf', name: 'doc.pdf', mimeType: 'application/pdf' }],
|
||||
})),
|
||||
}))
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import { UserIncidentsView } from '@/components/UserIncidentsView'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const incident = {
|
||||
id: 1,
|
||||
userId: 3,
|
||||
orderId: 7,
|
||||
dateAdded: '2026-01-01T10:00:00.000Z',
|
||||
adminComment: 'Abusive behaviour',
|
||||
addedBy: 'shafi',
|
||||
negativityScore: 5,
|
||||
orderStatus: 'cancelled',
|
||||
}
|
||||
|
||||
const procedures = (overrides: Record<string, unknown> = {}) => ({
|
||||
'admin.user.getUserIncidents': { incidents: [incident] },
|
||||
'admin.user.addUserIncident': { success: true, data: { id: 2 } },
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderView = (
|
||||
props: { userId: number; orderId: number | null } = { userId: 3, orderId: null },
|
||||
overrides: Record<string, unknown> = {}
|
||||
) => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: procedures(overrides) })
|
||||
renderWithProviders(<UserIncidentsView {...props} />)
|
||||
return { fetchMock }
|
||||
}
|
||||
|
||||
const openDialog = async () => {
|
||||
fireEvent.press(screen.getByText('Add Incident'))
|
||||
await screen.findByText('Add User Incident')
|
||||
}
|
||||
|
||||
const submit = () => {
|
||||
fireEvent.press(screen.getAllByText('Add Incident').pop()!)
|
||||
}
|
||||
|
||||
describe('UserIncidentsView', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the section header and add button', async () => {
|
||||
renderView()
|
||||
|
||||
expect(screen.getByText('User Incidents')).toBeVisible()
|
||||
expect(screen.getByText('Add Incident')).toBeVisible()
|
||||
await screen.findByText('Abusive behaviour')
|
||||
})
|
||||
|
||||
it('queries incidents for the given user', async () => {
|
||||
const { fetchMock } = renderView()
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.user.getUserIncidents')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.getUserIncidents')).toEqual({
|
||||
userId: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('does not query when there is no user id', () => {
|
||||
const { fetchMock } = renderView({ userId: 0, orderId: null })
|
||||
|
||||
expect(procCount(fetchMock, 'admin.user.getUserIncidents')).toBe(0)
|
||||
})
|
||||
|
||||
it('renders each incident with its score, author and order', async () => {
|
||||
renderView()
|
||||
|
||||
expect(await screen.findByText('Abusive behaviour')).toBeVisible()
|
||||
expect(screen.getByText('Score: 5')).toBeVisible()
|
||||
expect(screen.getByText('Added by shafi')).toBeVisible()
|
||||
expect(screen.getByText('Order #7')).toBeVisible()
|
||||
expect(screen.getByText(/Jan 01, 2026/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the empty state when there are no incidents', async () => {
|
||||
renderView({ userId: 3, orderId: null }, { 'admin.user.getUserIncidents': { incidents: [] } })
|
||||
|
||||
expect(
|
||||
await screen.findByText('No incidents recorded for this user')
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the empty state when the query returns null', async () => {
|
||||
renderView({ userId: 3, orderId: null }, { 'admin.user.getUserIncidents': null })
|
||||
|
||||
expect(
|
||||
await screen.findByText('No incidents recorded for this user')
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('rejects an empty incident without calling the mutation', async () => {
|
||||
const { fetchMock } = renderView()
|
||||
await openDialog()
|
||||
|
||||
submit()
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Please enter a comment or negativity score'
|
||||
)
|
||||
expect(procCount(fetchMock, 'admin.user.addUserIncident')).toBe(0)
|
||||
})
|
||||
|
||||
it('adds an incident with an admin comment', async () => {
|
||||
const { fetchMock } = renderView()
|
||||
await openDialog()
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter details about the incident...'),
|
||||
'Repeated cancellations'
|
||||
)
|
||||
submit()
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
|
||||
userId: 3,
|
||||
adminComment: 'Repeated cancellations',
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Incident added successfully')
|
||||
)
|
||||
})
|
||||
|
||||
it('adds an incident with only a negativity score', async () => {
|
||||
const { fetchMock } = renderView()
|
||||
await openDialog()
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('0'), '7')
|
||||
submit()
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
|
||||
userId: 3,
|
||||
negativityScore: 7,
|
||||
})
|
||||
})
|
||||
|
||||
it('adds an incident with a comment and score including the order id', async () => {
|
||||
const { fetchMock } = renderView({ userId: 3, orderId: 7 })
|
||||
await openDialog()
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter details about the incident...'),
|
||||
'Rude call'
|
||||
)
|
||||
fireEvent.changeText(screen.getByPlaceholderText('0'), '3')
|
||||
submit()
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.user.addUserIncident'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.addUserIncident')).toEqual({
|
||||
userId: 3,
|
||||
orderId: 7,
|
||||
adminComment: 'Rude call',
|
||||
negativityScore: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('refetches the incidents and closes the dialog after adding', async () => {
|
||||
const { fetchMock } = renderView()
|
||||
await screen.findByText('Abusive behaviour')
|
||||
const before = procCount(fetchMock, 'admin.user.getUserIncidents')
|
||||
|
||||
await openDialog()
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter details about the incident...'),
|
||||
'Late arrival'
|
||||
)
|
||||
submit()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.user.getUserIncidents')).toBeGreaterThan(before)
|
||||
)
|
||||
await waitFor(() => expect(screen.queryByText('Add User Incident')).toBeNull())
|
||||
})
|
||||
|
||||
it('shows the error alert when adding fails and keeps the dialog open', async () => {
|
||||
const { fetchMock } = renderView(
|
||||
{ userId: 3, orderId: null },
|
||||
{
|
||||
'admin.user.addUserIncident': () => {
|
||||
throw new Error('nope')
|
||||
},
|
||||
}
|
||||
)
|
||||
await openDialog()
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter details about the incident...'),
|
||||
'Something'
|
||||
)
|
||||
submit()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'nope')
|
||||
)
|
||||
expect(fetchMock).toBeTruthy()
|
||||
expect(screen.getByText('Add User Incident')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,240 +0,0 @@
|
|||
/**
|
||||
* VendorSnippetForm (components/VendorSnippetForm.tsx) — create/edit form for
|
||||
* vendor snippets: snippet-code validation, slot + product selection, and the
|
||||
* create/update mutations.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import VendorSnippetForm from '@/components/VendorSnippetForm'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const DELIVERY_TIME = '2026-12-31T10:00:00.000Z'
|
||||
const SLOT_LABEL = new Date(DELIVERY_TIME).toLocaleString()
|
||||
|
||||
const slotsResponse = {
|
||||
slots: [{ id: 1, deliveryTime: DELIVERY_TIME, freezeTime: '2026-12-30T10:00:00.000Z' }],
|
||||
count: 1,
|
||||
}
|
||||
|
||||
const skusResponse = {
|
||||
skus: [{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' }],
|
||||
}
|
||||
|
||||
const onClose = jest.fn()
|
||||
const onSuccess = jest.fn()
|
||||
|
||||
const renderForm = (snippet?: React.ComponentProps<typeof VendorSnippetForm>['snippet']) =>
|
||||
renderWithProviders(
|
||||
<VendorSnippetForm snippet={snippet} onClose={onClose} onSuccess={onSuccess} />
|
||||
)
|
||||
|
||||
describe('VendorSnippetForm', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
onClose.mockClear()
|
||||
onSuccess.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the create form with an auto-generated snippet code', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
},
|
||||
})
|
||||
renderForm()
|
||||
|
||||
expect(screen.getByText('Create Vendor Snippet')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter snippet code')).toBeVisible()
|
||||
expect(screen.getByText('Create Snippet')).toBeVisible()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByPlaceholderText('Enter snippet code').props.value).toMatch(/^VS_/)
|
||||
)
|
||||
})
|
||||
|
||||
it('validates slot and product selection before submitting', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
},
|
||||
})
|
||||
renderForm()
|
||||
|
||||
fireEvent.press(screen.getByText('Create Snippet'))
|
||||
|
||||
expect(await screen.findByText('Slot selection is required')).toBeVisible()
|
||||
expect(await screen.findByText('At least one product must be selected')).toBeVisible()
|
||||
expect(procCount(api.fetchMock, 'admin.vendorSnippets.create')).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a snippet code with invalid characters', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
},
|
||||
})
|
||||
renderForm()
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter snippet code'),
|
||||
'bad code!'
|
||||
)
|
||||
fireEvent.press(screen.getByText('Create Snippet'))
|
||||
|
||||
expect(
|
||||
await screen.findByText(
|
||||
'Snippet code can only contain letters, numbers, and underscores'
|
||||
)
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('creates a snippet with the selected slot and products', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.vendorSnippets.create': { id: 5 },
|
||||
},
|
||||
})
|
||||
renderForm()
|
||||
|
||||
fireEvent.press(screen.getByText('Choose a delivery slot'))
|
||||
fireEvent.press(await screen.findByText(SLOT_LABEL))
|
||||
|
||||
fireEvent.press(screen.getByText('Select products'))
|
||||
fireEvent.press(await screen.findByText('Chicken 1kg'))
|
||||
fireEvent.press(screen.getByText('Done'))
|
||||
|
||||
fireEvent.press(screen.getByText('Create Snippet'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.vendorSnippets.create'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.vendorSnippets.create')).toEqual(
|
||||
expect.objectContaining({
|
||||
isPermanent: false,
|
||||
slotId: 1,
|
||||
skuIds: [1],
|
||||
})
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Vendor snippet created successfully'
|
||||
)
|
||||
)
|
||||
expect(onSuccess).toHaveBeenCalled()
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates an existing snippet', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.vendorSnippets.update': { id: 3 },
|
||||
},
|
||||
})
|
||||
renderForm({
|
||||
id: 3,
|
||||
snippetCode: 'VS_EXISTING',
|
||||
slotId: 2,
|
||||
isPermanent: false,
|
||||
skuIds: [7],
|
||||
validTill: '2027-01-01T00:00:00.000Z',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
})
|
||||
|
||||
expect(screen.getByText('Edit Vendor Snippet')).toBeVisible()
|
||||
fireEvent.press(screen.getByText('Update Snippet'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.vendorSnippets.update'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.vendorSnippets.update')).toEqual({
|
||||
id: 3,
|
||||
updates: expect.objectContaining({
|
||||
snippetCode: 'VS_EXISTING',
|
||||
slotId: 2,
|
||||
isPermanent: false,
|
||||
skuIds: [7],
|
||||
validTill: '2027-01-01T00:00:00.000Z',
|
||||
}),
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Vendor snippet updated successfully'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('allows a permanent snippet without a slot and hides the slot picker', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
},
|
||||
})
|
||||
renderForm()
|
||||
|
||||
expect(screen.getByText('Choose a delivery slot')).toBeVisible()
|
||||
fireEvent.press(screen.getByText('Is Permanent?'))
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('Choose a delivery slot')).toBeNull())
|
||||
|
||||
fireEvent.press(screen.getByText('Create Snippet'))
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('Slot selection is required')).toBeNull()
|
||||
)
|
||||
})
|
||||
|
||||
it('shows an error alert when the mutation fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.vendorSnippets.update': () => {
|
||||
throw new Error('save failed')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderForm({
|
||||
id: 3,
|
||||
snippetCode: 'VS_EXISTING',
|
||||
slotId: 2,
|
||||
isPermanent: false,
|
||||
skuIds: [7],
|
||||
validTill: null,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
})
|
||||
|
||||
fireEvent.press(screen.getByText('Update Snippet'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String))
|
||||
)
|
||||
})
|
||||
|
||||
it('cancels through the close button', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'user.slots.getSlots': slotsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
},
|
||||
})
|
||||
renderForm()
|
||||
|
||||
fireEvent.press(screen.getByText('✕'))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,185 +0,0 @@
|
|||
/**
|
||||
* staff-auth-context (components/context/staff-auth-context.tsx) — the REAL
|
||||
* provider. tests/setup.ts mocks this module globally, so it is unmocked here.
|
||||
*
|
||||
* It imports the `@/utils/queryClient` singleton (cleared between tests) and
|
||||
* needs expo-router (mocked) plus the trpc/React Query provider stack.
|
||||
*/
|
||||
|
||||
jest.unmock('@/components/context/staff-auth-context')
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { DeviceEventEmitter } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import { MyText, MyTouchableOpacity } from 'common-ui'
|
||||
|
||||
import {
|
||||
StaffAuthProvider,
|
||||
useStaffAuth,
|
||||
} from '@/components/context/staff-auth-context'
|
||||
import { getJWT, saveJWT } from '@/hooks/useJWT'
|
||||
import queryClient from '@/utils/queryClient'
|
||||
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { resetRouterMock, routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
type Auth = ReturnType<typeof useStaffAuth>
|
||||
|
||||
const authSpy = jest.fn<void, [Auth]>()
|
||||
|
||||
function Consumer() {
|
||||
const auth = useStaffAuth()
|
||||
authSpy(auth)
|
||||
|
||||
return (
|
||||
<>
|
||||
<MyTouchableOpacity testID="login" onPress={() => auth.login('shafi', 'secret')}>
|
||||
<MyText>login</MyText>
|
||||
</MyTouchableOpacity>
|
||||
<MyTouchableOpacity testID="logout" onPress={() => auth.logout()}>
|
||||
<MyText>logout</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const lastAuth = (): Auth => authSpy.mock.calls[authSpy.mock.calls.length - 1][0]
|
||||
|
||||
const renderProvider = () =>
|
||||
renderWithProviders(
|
||||
<StaffAuthProvider>
|
||||
<Consumer />
|
||||
</StaffAuthProvider>
|
||||
)
|
||||
|
||||
const trpcErrorResponse = (message: string) => [
|
||||
{ error: { message, code: -32600, data: { code: 'UNAUTHORIZED', httpStatus: 401 } } },
|
||||
]
|
||||
|
||||
describe('staff-auth-context (real provider)', () => {
|
||||
beforeEach(async () => {
|
||||
authSpy.mockClear()
|
||||
queryClient.clear()
|
||||
resetRouterMock()
|
||||
await resetStorage()
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.staffUser.login': { token: 'jwt-abc', staff: { id: 1, name: 'shafi' } },
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('redirects to /login when there is no token', async () => {
|
||||
renderProvider()
|
||||
|
||||
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
|
||||
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
|
||||
expect(lastAuth().isLoggedIn).toBe(false)
|
||||
expect(lastAuth().staff).toBeNull()
|
||||
})
|
||||
|
||||
it('marks the session logged in when a token exists', async () => {
|
||||
await saveJWT('existing-token')
|
||||
|
||||
renderProvider()
|
||||
|
||||
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
|
||||
expect(lastAuth().isLoading).toBe(false)
|
||||
expect(routerMock.replace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('login saves the JWT, sets staff and routes to the dashboard', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.staffUser.login': { token: 'jwt-abc', staff: { id: 7, name: 'shafi' } },
|
||||
},
|
||||
})
|
||||
|
||||
renderProvider()
|
||||
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
|
||||
|
||||
fireEvent.press(screen.getByTestId('login'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(routerMock.replace).toHaveBeenCalledWith('/(drawer)/dashboard')
|
||||
)
|
||||
await waitFor(async () => expect(await getJWT()).toBe('jwt-abc'))
|
||||
|
||||
expect(lastAuth().staff).toEqual({ id: 7, name: 'shafi' })
|
||||
expect(lastAuth().isLoggedIn).toBe(true)
|
||||
expect(lastAuth().loginError).toBeNull()
|
||||
|
||||
expectProcedureCalled(fetchMock, 'admin.staffUser.login', { times: 1 })
|
||||
expect(lastProcedureInput(fetchMock, 'admin.staffUser.login')).toEqual({
|
||||
name: 'shafi',
|
||||
password: 'secret',
|
||||
})
|
||||
})
|
||||
|
||||
it('login sets loginError when the backend rejects', async () => {
|
||||
setupApiMocks()
|
||||
;(global as unknown as { fetch: unknown }).fetch = jest.fn(async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: new Map(),
|
||||
url: '',
|
||||
json: async () => trpcErrorResponse('Invalid credentials'),
|
||||
text: async () => JSON.stringify(trpcErrorResponse('Invalid credentials')),
|
||||
}))
|
||||
|
||||
renderProvider()
|
||||
await waitFor(() => expect(lastAuth().isLoading).toBe(false))
|
||||
|
||||
fireEvent.press(screen.getByTestId('login'))
|
||||
|
||||
await waitFor(() => expect(lastAuth().loginError).toBe('Invalid credentials'))
|
||||
expect(lastAuth().isLoggedIn).toBe(false)
|
||||
expect(routerMock.replace).not.toHaveBeenCalledWith('/(drawer)/dashboard')
|
||||
})
|
||||
|
||||
it('logout deletes the JWT, clears the query cache and routes to /login', async () => {
|
||||
await saveJWT('existing-token')
|
||||
const clearSpy = jest.spyOn(queryClient, 'clear')
|
||||
|
||||
renderProvider()
|
||||
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
|
||||
|
||||
fireEvent.press(screen.getByTestId('logout'))
|
||||
|
||||
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
|
||||
await waitFor(async () => expect(await getJWT()).toBeNull())
|
||||
|
||||
expect(clearSpy).toHaveBeenCalled()
|
||||
expect(lastAuth().isLoggedIn).toBe(false)
|
||||
expect(lastAuth().staff).toBeNull()
|
||||
})
|
||||
|
||||
it('FORCE_LOGOUT_EVENT logs the staff member out', async () => {
|
||||
await saveJWT('existing-token')
|
||||
|
||||
renderProvider()
|
||||
await waitFor(() => expect(lastAuth().isLoggedIn).toBe(true))
|
||||
|
||||
await act(async () => {
|
||||
DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith('/login'))
|
||||
await waitFor(async () => expect(await getJWT()).toBeNull())
|
||||
expect(lastAuth().isLoggedIn).toBe(false)
|
||||
})
|
||||
|
||||
it('useStaffAuth throws when used outside the provider', () => {
|
||||
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
expect(() => renderWithProviders(<Consumer />)).toThrow(
|
||||
'useStaffAuth must be used within a StaffAuthProvider'
|
||||
)
|
||||
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
/**
|
||||
* Provider stack shared by the admin-ui tests.
|
||||
*
|
||||
* Mirrors app/_layout.tsx minus the native wrappers: trpc + React Query +
|
||||
* Refresh. StaffAuthProvider is mocked globally in tests/setup.ts, so screens
|
||||
* that read the session mount without it; real-provider tests render it
|
||||
* explicitly.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render } from '@testing-library/react-native'
|
||||
import { RefreshProvider } from 'common-ui'
|
||||
|
||||
import { trpc, trpcClient } from '@/src/trpc-client'
|
||||
|
||||
export function createQueryClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: 0 } },
|
||||
})
|
||||
}
|
||||
|
||||
export interface ProviderOptions {
|
||||
/** Reuse a specific query client (e.g. to assert refetches). */
|
||||
queryClient?: QueryClient
|
||||
}
|
||||
|
||||
export function Providers({
|
||||
children,
|
||||
queryClient,
|
||||
}: { children?: React.ReactNode } & ProviderOptions) {
|
||||
const client = React.useMemo(
|
||||
() => queryClient ?? createQueryClient(),
|
||||
[queryClient]
|
||||
)
|
||||
|
||||
return (
|
||||
<trpc.Provider client={trpcClient} queryClient={client}>
|
||||
<QueryClientProvider client={client}>
|
||||
<RefreshProvider queryClient={client}>{children}</RefreshProvider>
|
||||
</QueryClientProvider>
|
||||
</trpc.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** Render a screen/component inside the standard provider stack. */
|
||||
export function renderWithProviders(
|
||||
ui: React.ReactElement,
|
||||
options?: ProviderOptions
|
||||
) {
|
||||
return render(<Providers {...options}>{ui}</Providers>)
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
/**
|
||||
* useJWT (hooks/useJWT.ts) — secure-store token persistence.
|
||||
*
|
||||
* StorageService is globally mocked by tests/setup.ts with an in-memory map;
|
||||
* resetStorage() clears the `jwt_token` slot between tests.
|
||||
*/
|
||||
|
||||
import { StorageService } from 'common-ui'
|
||||
|
||||
import { deleteJWT, getJWT, JWT_KEY, saveJWT } from '@/hooks/useJWT'
|
||||
import { resetStorage } from '../mocks/api'
|
||||
|
||||
describe('useJWT', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
})
|
||||
|
||||
it('uses the jwt_token storage key', () => {
|
||||
expect(JWT_KEY).toBe('jwt_token')
|
||||
})
|
||||
|
||||
it('returns null when no token has been stored', async () => {
|
||||
await expect(getJWT()).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('saves a token under JWT_KEY and reads it back', async () => {
|
||||
await saveJWT('token-abc')
|
||||
|
||||
expect(StorageService.setItem).toHaveBeenCalledWith('jwt_token', 'token-abc')
|
||||
await expect(getJWT()).resolves.toBe('token-abc')
|
||||
})
|
||||
|
||||
it('deletes the stored token', async () => {
|
||||
await saveJWT('token-abc')
|
||||
|
||||
await deleteJWT()
|
||||
|
||||
expect(StorageService.removeItem).toHaveBeenCalledWith('jwt_token')
|
||||
await expect(getJWT()).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,231 +0,0 @@
|
|||
/**
|
||||
* useUploadToObjectStorage (hooks/useUploadToObjectStore.ts) — requests
|
||||
* presigned URLs from `common.generateUploadUrls`, then PUTs each image in
|
||||
* parallel and extracts the object key from the presigned URL.
|
||||
*
|
||||
* Fake timers: mutations are driven with act() + waitFor(), never awaited
|
||||
* directly (see tests/screens/login.test.tsx for the pattern).
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { Providers } from '../helpers/render'
|
||||
|
||||
const wrapper = ({ children }: { children?: React.ReactNode }) => (
|
||||
<Providers>{children}</Providers>
|
||||
)
|
||||
|
||||
const presigned = (key: string) =>
|
||||
`https://meatfarmer.s3.amazonaws.com/meatfarmer/${key}`
|
||||
|
||||
const blob = {} as Blob
|
||||
|
||||
const jpeg = { blob, mimeType: 'image/jpeg' }
|
||||
const png = { blob, mimeType: 'image/png' }
|
||||
|
||||
/** Kick off `upload` without awaiting it (fake timers would deadlock). */
|
||||
const startUpload = (
|
||||
result: { current: ReturnType<typeof useUploadToObjectStorage> },
|
||||
input: Parameters<ReturnType<typeof useUploadToObjectStorage>['upload']>[0]
|
||||
) => {
|
||||
let promise: Promise<unknown> = Promise.resolve()
|
||||
act(() => {
|
||||
promise = result.current.upload(input)
|
||||
promise.catch(() => {})
|
||||
})
|
||||
return promise
|
||||
}
|
||||
|
||||
describe('useUploadToObjectStorage', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
})
|
||||
|
||||
it('requests one presigned URL per image and uploads them in parallel', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'common.generateUploadUrls': {
|
||||
uploadUrls: [
|
||||
presigned('product-images/a.jpg'),
|
||||
presigned('product-images/b.png'),
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
|
||||
const promise = startUpload(result, {
|
||||
images: [jpeg, png],
|
||||
contextString: 'product_info',
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.isUploading).toBe(false))
|
||||
|
||||
const uploaded = await promise
|
||||
|
||||
expectProcedureCalled(fetchMock, 'common.generateUploadUrls', { times: 1 })
|
||||
expect(lastProcedureInput(fetchMock, 'common.generateUploadUrls')).toEqual({
|
||||
contextString: 'product_info',
|
||||
mimeTypes: ['image/jpeg', 'image/png'],
|
||||
})
|
||||
|
||||
expect(uploaded).toEqual({
|
||||
keys: ['product-images/a.jpg', 'product-images/b.png'],
|
||||
presignedUrls: [
|
||||
presigned('product-images/a.jpg'),
|
||||
presigned('product-images/b.png'),
|
||||
],
|
||||
})
|
||||
|
||||
const putCalls = fetchMock.mock.calls.filter(
|
||||
([, options]) => (options as { method?: string } | undefined)?.method === 'PUT'
|
||||
)
|
||||
expect(putCalls).toHaveLength(2)
|
||||
expect(result.current.error).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves an empty batch without calling the backend', async () => {
|
||||
const { fetchMock } = setupApiMocks()
|
||||
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
|
||||
|
||||
let resolved: unknown
|
||||
await act(async () => {
|
||||
resolved = await result.current.upload({ images: [], contextString: 'store' })
|
||||
})
|
||||
|
||||
expect(resolved).toEqual({ keys: [], presignedUrls: [] })
|
||||
expect(procCount(fetchMock, 'common.generateUploadUrls')).toBe(0)
|
||||
})
|
||||
|
||||
it('fails when the backend returns a URL count that does not match', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'common.generateUploadUrls': { uploadUrls: [presigned('tags/only.jpg')] },
|
||||
},
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
|
||||
const promise = startUpload(result, {
|
||||
images: [jpeg, png],
|
||||
contextString: 'tags',
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.error?.message).toBe('Expected 2 URLs, got 1')
|
||||
)
|
||||
await expect(promise).rejects.toThrow('Expected 2 URLs, got 1')
|
||||
})
|
||||
|
||||
it('surfaces the failed PUT status and stops uploading', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'common.generateUploadUrls': {
|
||||
uploadUrls: [presigned('store-images/x.jpg')],
|
||||
},
|
||||
},
|
||||
})
|
||||
const trpcFetch = global.fetch
|
||||
|
||||
;(global as unknown as { fetch: unknown }).fetch = jest.fn(
|
||||
async (url: string, options?: { method?: string }) => {
|
||||
if (options?.method === 'PUT') {
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: 'Server Error',
|
||||
headers: new Map(),
|
||||
url: String(url),
|
||||
text: async (): Promise<string> => '<Error><Code>AccessDenied</Code></Error>',
|
||||
json: async () => ({}),
|
||||
}
|
||||
}
|
||||
return trpcFetch(url, options)
|
||||
}
|
||||
)
|
||||
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
|
||||
const promise = startUpload(result, {
|
||||
images: [jpeg],
|
||||
contextString: 'store',
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.error?.message).toBe('Upload 1 failed with status 500')
|
||||
)
|
||||
await expect(promise).rejects.toThrow('Upload 1 failed with status 500')
|
||||
|
||||
expect(result.current.isUploading).toBe(false)
|
||||
expect(result.current.progress).toBeNull()
|
||||
expectProcedureCalled(fetchMock, 'common.generateUploadUrls', { times: 1 })
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('reports progress as each upload settles', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'common.generateUploadUrls': {
|
||||
uploadUrls: [
|
||||
presigned('product-images/a.jpg'),
|
||||
presigned('product-images/b.jpg'),
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
const trpcFetch = global.fetch
|
||||
const resolvers: Array<(value: unknown) => void> = []
|
||||
|
||||
;(global as unknown as { fetch: unknown }).fetch = jest.fn(
|
||||
(url: string, options?: { method?: string }) => {
|
||||
if (options?.method === 'PUT') {
|
||||
return new Promise((resolve) => resolvers.push(resolve))
|
||||
}
|
||||
return trpcFetch(url, options)
|
||||
}
|
||||
)
|
||||
|
||||
const okResponse = {
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: new Map(),
|
||||
url: '',
|
||||
text: async () => '',
|
||||
json: async () => ({}),
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper })
|
||||
const promise = startUpload(result, {
|
||||
images: [jpeg, png],
|
||||
contextString: 'product_info',
|
||||
})
|
||||
|
||||
await waitFor(() => expect(resolvers).toHaveLength(2))
|
||||
expect(result.current.progress).toEqual({ completed: 0, total: 2 })
|
||||
|
||||
act(() => resolvers[0](okResponse))
|
||||
await waitFor(() => expect(result.current.progress).toEqual({ completed: 1, total: 2 }))
|
||||
|
||||
act(() => resolvers[1](okResponse))
|
||||
await waitFor(() => expect(result.current.progress).toBeNull())
|
||||
|
||||
const uploaded = await promise
|
||||
expect(uploaded).toEqual({
|
||||
keys: ['product-images/a.jpg', 'product-images/b.jpg'],
|
||||
presignedUrls: [
|
||||
presigned('product-images/a.jpg'),
|
||||
presigned('product-images/b.jpg'),
|
||||
],
|
||||
})
|
||||
})
|
||||
})
|
||||
6
apps/admin-ui/tests/jest-env.d.ts
vendored
6
apps/admin-ui/tests/jest-env.d.ts
vendored
|
|
@ -1,6 +0,0 @@
|
|||
/// <reference types="jest" />
|
||||
|
||||
// Declares the Jest globals (describe, it, expect, jest, ...) for the tests in
|
||||
// this folder. @types/jest is a devDependency, but the explicit reference means
|
||||
// the globals are declared by a file inside the project rather than relying on
|
||||
// ambient @types auto-inclusion.
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
const path = require('path')
|
||||
|
||||
const appRoot = path.resolve(__dirname, '..')
|
||||
|
||||
/**
|
||||
* Jest project for apps/admin-ui integration tests.
|
||||
*
|
||||
* Mirrors apps/user-ui/tests/jest.config.js. Tests live under tests/ and are
|
||||
* kept out of the app build by living outside the app/ route tree.
|
||||
*/
|
||||
module.exports = {
|
||||
preset: 'jest-expo',
|
||||
rootDir: appRoot,
|
||||
roots: ['<rootDir>/tests'],
|
||||
testMatch: ['<rootDir>/tests/**/*.test.ts', '<rootDir>/tests/**/*.test.tsx'],
|
||||
setupFiles: ['<rootDir>/tests/setup.ts'],
|
||||
clearMocks: true,
|
||||
// The suites are heavy (expo-router + react-query + fake timers) and several
|
||||
// install module-level fakes; running them in parallel workers exhausts
|
||||
// resources and hangs. Serial is ~80s and stable.
|
||||
maxWorkers: 1,
|
||||
forceExit: true,
|
||||
moduleNameMapper: {
|
||||
'^@backend/(.*)$': '<rootDir>/../backend/src/$1',
|
||||
'^@/(.*)$': '<rootDir>/$1',
|
||||
'^shared-types$': '<rootDir>/../shared-types',
|
||||
'^@packages/shared$': '<rootDir>/../../packages/shared',
|
||||
'^@packages/shared/(.*)$': '<rootDir>/../../packages/shared/$1',
|
||||
'^global-shared$': '<rootDir>/../../packages/shared',
|
||||
'^global-shared/(.*)$': '<rootDir>/../../packages/shared/$1',
|
||||
'^common-ui$': '<rootDir>/../../packages/ui',
|
||||
'^common-ui/(.*)$': '<rootDir>/../../packages/ui/$1',
|
||||
},
|
||||
transformIgnorePatterns: [
|
||||
'node_modules/(?!(?:.pnpm/)?(' +
|
||||
[
|
||||
'(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-gesture-handler',
|
||||
'react-native-reanimated',
|
||||
'react-native-safe-area-context',
|
||||
'react-native-screens',
|
||||
'react-native-draggable-flatlist',
|
||||
'react-native-tab-view',
|
||||
'react-native-toast-message',
|
||||
'@trpc/.*',
|
||||
'@tanstack/.*',
|
||||
'twrnc',
|
||||
'zod',
|
||||
'@testing-library/react-native',
|
||||
].join('|') +
|
||||
'))',
|
||||
],
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
/**
|
||||
* queryClient (utils/queryClient.ts) — the app-wide singleton defaults.
|
||||
*
|
||||
* The source only overrides `retry`. React Query therefore supplies the
|
||||
* remaining observable defaults (staleTime resolves to 0, refetchOnWindowFocus
|
||||
* behaves as true). We assert both the configured value and that the other two
|
||||
* options are deliberately left unset.
|
||||
*/
|
||||
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
|
||||
import queryClient from '@/utils/queryClient'
|
||||
|
||||
describe('queryClient', () => {
|
||||
it('is a QueryClient instance', () => {
|
||||
expect(queryClient).toBeInstanceOf(QueryClient)
|
||||
})
|
||||
|
||||
it('retries failed queries 3 times by default', () => {
|
||||
expect(queryClient.getDefaultOptions().queries?.retry).toBe(3)
|
||||
})
|
||||
|
||||
it('retries every query with the configured default', () => {
|
||||
const resolved = queryClient.defaultQueryOptions({ queryKey: ['probe'] })
|
||||
expect(resolved.retry).toBe(3)
|
||||
})
|
||||
|
||||
it('does not override staleTime / refetchOnWindowFocus (library defaults apply)', () => {
|
||||
const queries = queryClient.getDefaultOptions().queries
|
||||
expect(queries?.staleTime).toBeUndefined()
|
||||
expect(queries?.refetchOnWindowFocus).toBeUndefined()
|
||||
|
||||
const resolved = queryClient.defaultQueryOptions({ queryKey: ['probe'] })
|
||||
expect(resolved.staleTime).toBeUndefined()
|
||||
expect(resolved.refetchOnWindowFocus).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
/**
|
||||
* toaster (services/toaster.tsx) — Info/Error/Success helpers funnel into
|
||||
* react-native-toast-message's Toast.show with the right type/position and an
|
||||
* onPress that hides the toast.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import Toast from 'react-native-toast-message'
|
||||
|
||||
import { ErrorToast, InfoToast, SuccessToast } from '@/services/toaster'
|
||||
|
||||
const showMock = Toast.show as jest.Mock
|
||||
const hideMock = Toast.hide as jest.Mock
|
||||
|
||||
const showArg = (index: number) => showMock.mock.calls[index][0]
|
||||
|
||||
describe('toaster', () => {
|
||||
it('InfoToast shows an info toast at the top', () => {
|
||||
InfoToast('heads up')
|
||||
|
||||
expect(showMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'info', text1: 'heads up', position: 'top' })
|
||||
)
|
||||
expect(showArg(0).visibilityTime).toBe(10000)
|
||||
})
|
||||
|
||||
it('ErrorToast shows an error toast at the top', () => {
|
||||
ErrorToast('boom')
|
||||
|
||||
expect(showMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'error', text1: 'boom', position: 'top' })
|
||||
)
|
||||
})
|
||||
|
||||
it('SuccessToast shows a success toast at the top', () => {
|
||||
SuccessToast('done')
|
||||
|
||||
expect(showMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'success', text1: 'done', position: 'top' })
|
||||
)
|
||||
})
|
||||
|
||||
it('hides the toast when pressed', () => {
|
||||
SuccessToast('done')
|
||||
|
||||
showArg(0).onPress()
|
||||
|
||||
expect(hideMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
/**
|
||||
* Network-layer mocks for the admin-ui tests.
|
||||
*
|
||||
* All tRPC traffic goes through `global.fetch` (httpBatchLink). The registry
|
||||
* resolves each batched procedure by name; anything not supplied resolves to
|
||||
* `null`, and tests override with the exact shape they assert against. Tests
|
||||
* that need to prove "nothing was called" use tests/mocks/procedures.ts.
|
||||
*/
|
||||
|
||||
import { StorageService } from 'common-ui/src/services/StorageService'
|
||||
import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual'
|
||||
import { parseTrpcUrl } from './procedures'
|
||||
|
||||
const jsonResponse = (body: unknown) => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: new Map(),
|
||||
url: '',
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
clone: () => jsonResponse(body),
|
||||
})
|
||||
|
||||
export interface ApiMockOptions {
|
||||
/**
|
||||
* Procedure registry: name -> data, or (input) => data. Unlisted procedures
|
||||
* resolve to null.
|
||||
*/
|
||||
procedures?: Record<string, unknown | ((input: unknown) => unknown)>
|
||||
/** The essentialConsts-style consts payload, if a screen reads it. */
|
||||
consts?: unknown
|
||||
}
|
||||
|
||||
export function setupApiMocks(opts: ApiMockOptions = {}) {
|
||||
const resolveProcedure = (name: string, input: unknown): unknown => {
|
||||
const override = opts.procedures?.[name]
|
||||
if (override !== undefined) {
|
||||
return typeof override === 'function'
|
||||
? (override as (value: unknown) => unknown)(input)
|
||||
: override
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const fetchMock = jest.fn(
|
||||
async (url: string, options?: { method?: string; body?: unknown }) => {
|
||||
const target = String(url)
|
||||
const calls = parseTrpcUrl(target, options?.body)
|
||||
|
||||
if (calls.length === 0) {
|
||||
// Presigned S3 uploads PUT straight to a URL.
|
||||
if (options?.method === 'PUT') return jsonResponse({})
|
||||
throw new Error(`[tests] unmocked fetch: ${url}`)
|
||||
}
|
||||
|
||||
const batch = calls.map(({ name, input }) => ({
|
||||
result: { data: resolveProcedure(name, input) },
|
||||
}))
|
||||
return jsonResponse(batch)
|
||||
}
|
||||
)
|
||||
|
||||
;(global as unknown as { fetch: unknown }).fetch = fetchMock
|
||||
|
||||
return { fetchMock }
|
||||
}
|
||||
|
||||
/** Clear the in-memory auth token + cached staff identity + any casual storage. Call from beforeEach. */
|
||||
export async function resetStorage() {
|
||||
await StorageService.clearAll(['jwt_token', 'staff_session'])
|
||||
await StorageServiceCasual.clearAll([])
|
||||
}
|
||||
|
|
@ -1,181 +0,0 @@
|
|||
/**
|
||||
* Module stubs for native / third-party packages that cannot run under jest.
|
||||
* Registered in tests/setup.ts via jest.mock factories.
|
||||
*
|
||||
* Deliberately permissive: tests that assert behaviour spy on the returned
|
||||
* functions or override the module themselves.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { View, Text } from 'react-native'
|
||||
|
||||
/** react-native-draggable-flatlist: render children as a plain list. */
|
||||
export function draggableFlatListMock() {
|
||||
const DraggableFlatList = ({
|
||||
data,
|
||||
renderItem,
|
||||
keyExtractor,
|
||||
ListEmptyComponent,
|
||||
}: {
|
||||
data?: unknown[]
|
||||
renderItem?: (info: { item: unknown; index: number; drag: () => void; isActive: boolean }) => React.ReactNode
|
||||
keyExtractor?: (item: unknown, index: number) => string
|
||||
ListEmptyComponent?: React.ReactNode
|
||||
}) => {
|
||||
if (!data || data.length === 0) {
|
||||
return React.createElement(View, { testID: 'mock-draggable-list' }, ListEmptyComponent ?? null)
|
||||
}
|
||||
return React.createElement(
|
||||
View,
|
||||
{ testID: 'mock-draggable-list' },
|
||||
data.map((item, index) =>
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
{ key: keyExtractor ? keyExtractor(item, index) : index },
|
||||
renderItem?.({ item, index, drag: () => {}, isActive: false })
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
__esModule: true,
|
||||
default: DraggableFlatList,
|
||||
ScaleDecorator: ({ children }: { children?: React.ReactNode }) =>
|
||||
React.createElement(React.Fragment, null, children),
|
||||
}
|
||||
}
|
||||
|
||||
/** react-native-tab-view: render every tab label and the focused scene. */
|
||||
export function tabViewMock() {
|
||||
const TabView = ({
|
||||
navigationState,
|
||||
renderScene,
|
||||
onIndexChange,
|
||||
}: {
|
||||
navigationState: { index: number; routes: { key: string }[] }
|
||||
renderScene: (info: { route: { key: string } }) => React.ReactNode
|
||||
onIndexChange?: (index: number) => void
|
||||
}) => {
|
||||
const route = navigationState.routes[navigationState.index]
|
||||
return React.createElement(
|
||||
View,
|
||||
{ testID: 'mock-tab-view' },
|
||||
navigationState.routes.map((r, index) =>
|
||||
React.createElement(
|
||||
Text,
|
||||
{ key: r.key, testID: `tab-${r.key}`, onPress: () => onIndexChange?.(index) },
|
||||
r.key
|
||||
)
|
||||
),
|
||||
route ? renderScene({ route }) : null
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
__esModule: true,
|
||||
TabView,
|
||||
// SceneMap must return a renderScene function, not the raw map.
|
||||
SceneMap: (scenes: Record<string, React.ComponentType>) => (info: {
|
||||
route: { key: string }
|
||||
}) => {
|
||||
const Scene = scenes[info.route.key]
|
||||
return Scene ? React.createElement(Scene) : null
|
||||
},
|
||||
TabBar: () => null,
|
||||
}
|
||||
}
|
||||
|
||||
/** react-native-toast-message: no-op show/hide. */
|
||||
export function toastMock() {
|
||||
const Toast = {
|
||||
show: jest.fn(),
|
||||
hide: jest.fn(),
|
||||
}
|
||||
return { __esModule: true, default: Toast, ...Toast }
|
||||
}
|
||||
|
||||
/** expo-location: permissions granted, a fixed position. */
|
||||
export function locationMock() {
|
||||
return {
|
||||
__esModule: true,
|
||||
Accuracy: { Lowest: 1, Low: 2, Balanced: 3, High: 4, Highest: 5 },
|
||||
requestForegroundPermissionsAsync: jest.fn(async () => ({ status: 'granted', granted: true })),
|
||||
getForegroundPermissionsAsync: jest.fn(async () => ({ status: 'granted', granted: true })),
|
||||
hasServicesEnabledAsync: jest.fn(async () => true),
|
||||
getCurrentPositionAsync: jest.fn(async () => ({
|
||||
coords: { latitude: 16.75, longitude: 78.0, accuracy: 5 },
|
||||
timestamp: Date.now(),
|
||||
})),
|
||||
reverseGeocodeAsync: jest.fn(async () => [
|
||||
{ street: 'Test Street', city: 'Mahabubnagar', region: 'Telangana', postalCode: '509001' },
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
/** expo-image-picker: one asset by default. */
|
||||
export function imagePickerMock() {
|
||||
const asset = { uri: 'file:///tmp/pick.jpg', fileName: 'pick.jpg', mimeType: 'image/jpeg' }
|
||||
return {
|
||||
__esModule: true,
|
||||
MediaTypeOptions: { Images: 'Images', All: 'All', Videos: 'Videos' },
|
||||
launchImageLibraryAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
launchCameraAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
requestMediaLibraryPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
requestCameraPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
}
|
||||
}
|
||||
|
||||
/** expo-document-picker: one document by default. */
|
||||
export function documentPickerMock() {
|
||||
return {
|
||||
__esModule: true,
|
||||
getDocumentAsync: jest.fn(async () => ({
|
||||
canceled: false,
|
||||
assets: [{ uri: 'file:///tmp/doc.pdf', name: 'doc.pdf', mimeType: 'application/pdf' }],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/** expo-device: a physical device. */
|
||||
export function deviceMock() {
|
||||
return {
|
||||
__esModule: true,
|
||||
isDevice: true,
|
||||
modelName: 'Jest Device',
|
||||
osName: 'Android',
|
||||
osVersion: '14',
|
||||
}
|
||||
}
|
||||
|
||||
/** expo-haptics: no-ops. */
|
||||
export function hapticsMock() {
|
||||
return {
|
||||
__esModule: true,
|
||||
impactAsync: jest.fn(async () => {}),
|
||||
notificationAsync: jest.fn(async () => {}),
|
||||
selectionAsync: jest.fn(async () => {}),
|
||||
ImpactFeedbackStyle: { Light: 'light', Medium: 'medium', Heavy: 'heavy' },
|
||||
}
|
||||
}
|
||||
|
||||
/** expo-linear-gradient: passthrough View. */
|
||||
export function linearGradientMock() {
|
||||
const LinearGradient = ({ children }: { children?: React.ReactNode }) =>
|
||||
React.createElement(View, { testID: 'mock-linear-gradient' }, children)
|
||||
return { __esModule: true, LinearGradient }
|
||||
}
|
||||
|
||||
/** expo-blur: passthrough View. */
|
||||
export function blurMock() {
|
||||
const BlurView = ({ children }: { children?: React.ReactNode }) =>
|
||||
React.createElement(View, { testID: 'mock-blur-view' }, children)
|
||||
return { __esModule: true, BlurView }
|
||||
}
|
||||
|
||||
/** expo-image: passthrough Image. */
|
||||
export function imageMock() {
|
||||
const Image = (props: Record<string, unknown>) =>
|
||||
React.createElement(View, { testID: 'mock-image', ...props })
|
||||
return { __esModule: true, Image, default: Image }
|
||||
}
|
||||
|
|
@ -1,122 +0,0 @@
|
|||
/**
|
||||
* Assert which tRPC procedures a screen called, and with what input.
|
||||
*
|
||||
* Every tRPC call goes through `global.fetch` (httpBatchLink), whose URL is
|
||||
* `/api/trpc/<name>[,<name>...]?batch=1&input=<json>`. The input param is an
|
||||
* object keyed by the batch index: `{ "0": { json: <input> }, ... }`.
|
||||
*
|
||||
* tests/mocks/api.ts installs the fetch stub; pass its returned `fetchMock` to
|
||||
* these helpers.
|
||||
*/
|
||||
|
||||
export interface ProcedureCall {
|
||||
name: string
|
||||
input: unknown
|
||||
}
|
||||
|
||||
export interface FetchMockLike {
|
||||
mock: { calls: unknown[][] }
|
||||
}
|
||||
|
||||
const MARKER = '/api/trpc/'
|
||||
|
||||
const parseInputEnvelope = (raw: string | undefined) => {
|
||||
if (!raw) return {} as Record<string, { json?: unknown }>
|
||||
try {
|
||||
return JSON.parse(raw) as Record<string, { json?: unknown }>
|
||||
} catch {
|
||||
return {} as Record<string, { json?: unknown }>
|
||||
}
|
||||
}
|
||||
|
||||
const unwrapInput = (entry: unknown): unknown => {
|
||||
if (
|
||||
entry != null &&
|
||||
typeof entry === 'object' &&
|
||||
'json' in entry &&
|
||||
'meta' in entry
|
||||
) {
|
||||
return (entry as { json: unknown }).json
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
/** Split a tRPC request URL into one entry per batched procedure. */
|
||||
export function parseTrpcUrl(url: string, body?: unknown): ProcedureCall[] {
|
||||
const target = String(url)
|
||||
const at = target.indexOf(MARKER)
|
||||
if (at === -1) return []
|
||||
|
||||
const rest = target.slice(at + MARKER.length)
|
||||
const queryAt = rest.indexOf('?')
|
||||
const path = queryAt === -1 ? rest : rest.slice(0, queryAt)
|
||||
const query = queryAt === -1 ? '' : rest.slice(queryAt + 1)
|
||||
|
||||
const names = path.split(',').filter(Boolean)
|
||||
|
||||
let inputsByIndex: Record<string, { json?: unknown }> = {}
|
||||
const match = /(?:^|&)input=([^&]*)/.exec(query)
|
||||
if (match) {
|
||||
inputsByIndex = parseInputEnvelope(decodeURIComponent(match[1]))
|
||||
} else if (typeof body === 'string') {
|
||||
inputsByIndex = parseInputEnvelope(body)
|
||||
}
|
||||
|
||||
return names.map((name, index) => ({
|
||||
name,
|
||||
input: unwrapInput(inputsByIndex[String(index)]),
|
||||
}))
|
||||
}
|
||||
|
||||
/** Every procedure call recorded by the fetch mock, in order. */
|
||||
export function calledProcedures(fetchMock: FetchMockLike): ProcedureCall[] {
|
||||
return fetchMock.mock.calls.flatMap(([url, options]) => {
|
||||
const body = (options as { body?: unknown } | undefined)?.body
|
||||
return parseTrpcUrl(String(url), body)
|
||||
})
|
||||
}
|
||||
|
||||
export function procedureCalls(
|
||||
fetchMock: FetchMockLike,
|
||||
name: string
|
||||
): ProcedureCall[] {
|
||||
return calledProcedures(fetchMock).filter((call) => call.name === name)
|
||||
}
|
||||
|
||||
/** Assert a procedure was called (optionally exactly `times`). */
|
||||
export function expectProcedureCalled(
|
||||
fetchMock: FetchMockLike,
|
||||
name: string,
|
||||
options: { times?: number } = {}
|
||||
): ProcedureCall[] {
|
||||
const calls = procedureCalls(fetchMock, name)
|
||||
|
||||
if (options.times != null) {
|
||||
expect(calls).toHaveLength(options.times)
|
||||
} else {
|
||||
expect(calls.length).toBeGreaterThan(0)
|
||||
}
|
||||
|
||||
return calls
|
||||
}
|
||||
|
||||
/** Input of the most recent call to a procedure (undefined if never called). */
|
||||
export function lastProcedureInput(
|
||||
fetchMock: FetchMockLike,
|
||||
name: string
|
||||
): unknown {
|
||||
const calls = procedureCalls(fetchMock, name)
|
||||
return calls.length === 0 ? undefined : calls[calls.length - 1].input
|
||||
}
|
||||
|
||||
export function procedureInput(
|
||||
fetchMock: FetchMockLike,
|
||||
name: string
|
||||
): unknown {
|
||||
return lastProcedureInput(fetchMock, name)
|
||||
}
|
||||
|
||||
/** Number of calls to a procedure. */
|
||||
export function procCount(fetchMock: FetchMockLike, name: string): number {
|
||||
return procedureCalls(fetchMock, name).length
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
/**
|
||||
* Callbacks recorded from the mocked refresh hooks
|
||||
* (common-ui/useMarkDataFetchers, common-ui/useManualRefresh) so a test can
|
||||
* invoke a screen's refresh handler and assert what it refetches.
|
||||
*/
|
||||
|
||||
export const refreshHooks: {
|
||||
markDataFetchers: (() => void) | null
|
||||
manualRefresh: (() => void) | null
|
||||
} = {
|
||||
markDataFetchers: null,
|
||||
manualRefresh: null,
|
||||
}
|
||||
|
||||
export function resetRefreshHooks() {
|
||||
refreshHooks.markDataFetchers = null
|
||||
refreshHooks.manualRefresh = null
|
||||
}
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
/**
|
||||
* Shared spies for the mocked expo-router.
|
||||
*
|
||||
* The mock lives in each test file rather than in tests/setup.ts, so the ones
|
||||
* that want real navigation can use expo-router/testing-library. Any file that
|
||||
* renders a router consumer adds:
|
||||
*
|
||||
* jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
|
||||
export const routerMock = {
|
||||
push: jest.fn(),
|
||||
replace: jest.fn(),
|
||||
back: jest.fn(),
|
||||
navigate: jest.fn(),
|
||||
canGoBack: jest.fn(() => false),
|
||||
dismissTo: jest.fn(),
|
||||
dismissAll: jest.fn(),
|
||||
setParams: jest.fn(),
|
||||
}
|
||||
|
||||
export function resetRouterMock() {
|
||||
routerMock.push.mockClear()
|
||||
routerMock.replace.mockClear()
|
||||
routerMock.back.mockClear()
|
||||
routerMock.navigate.mockClear()
|
||||
routerMock.dismissTo.mockClear()
|
||||
routerMock.dismissAll.mockClear()
|
||||
}
|
||||
|
||||
/** Local search params returned by the mocked router. */
|
||||
export const searchParamsMock: { current: Record<string, unknown> } = {
|
||||
current: {},
|
||||
}
|
||||
|
||||
/** Factory for jest.mock('expo-router', ...). */
|
||||
export function expoRouterMock() {
|
||||
return {
|
||||
useRouter: () => routerMock,
|
||||
router: routerMock,
|
||||
usePathname: () => '/dashboard',
|
||||
useSegments: () => [],
|
||||
useLocalSearchParams: () => searchParamsMock.current,
|
||||
useGlobalSearchParams: () => searchParamsMock.current,
|
||||
useFocusEffect: (callback: () => void | (() => void)) => {
|
||||
const ran = React.useRef(false)
|
||||
React.useEffect(() => {
|
||||
if (ran.current) return
|
||||
ran.current = true
|
||||
return callback()
|
||||
}, [])
|
||||
},
|
||||
Link: ({ children }: { children?: unknown }) => children ?? null,
|
||||
Slot: ({ children }: { children?: unknown }) => children ?? null,
|
||||
// Layout primitives used by route files; render children through and give
|
||||
// Stack/Tabs a no-op .Screen so `<Stack.Screen />` does not crash.
|
||||
Stack: Object.assign(
|
||||
({ children }: { children?: unknown }) => children ?? null,
|
||||
{ Screen: () => null }
|
||||
),
|
||||
Tabs: Object.assign(
|
||||
({ children }: { children?: unknown }) => children ?? null,
|
||||
{ Screen: () => null }
|
||||
),
|
||||
Drawer: ({ children }: { children?: unknown }) => children ?? null,
|
||||
Redirect: () => null,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
/**
|
||||
* Overridable staff-auth mock with spies.
|
||||
*
|
||||
* tests/setup.ts stubs @/components/context/staff-auth-context with this
|
||||
* factory so screens that read the staff session mount. Tests can flip the
|
||||
* state in a beforeEach; reset with resetStaffAuthMock().
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export interface StaffAuthMockState {
|
||||
isLoggedIn: boolean
|
||||
isLoading: boolean
|
||||
staff: unknown
|
||||
/** Region of the signed-in staff member; suites opt in by setting this. */
|
||||
regionId: number | null
|
||||
isLoggingIn: boolean
|
||||
loginError: string | null
|
||||
login: jest.Mock
|
||||
logout: jest.Mock
|
||||
}
|
||||
|
||||
export const staffAuthMock: StaffAuthMockState = {
|
||||
isLoggedIn: true,
|
||||
isLoading: false,
|
||||
staff: { id: 1, name: 'shafi' },
|
||||
regionId: null,
|
||||
isLoggingIn: false,
|
||||
loginError: null,
|
||||
login: jest.fn(async () => {}),
|
||||
logout: jest.fn(),
|
||||
}
|
||||
|
||||
export function resetStaffAuthMock() {
|
||||
staffAuthMock.isLoggedIn = true
|
||||
staffAuthMock.isLoading = false
|
||||
staffAuthMock.staff = { id: 1, name: 'shafi' }
|
||||
staffAuthMock.regionId = null
|
||||
staffAuthMock.isLoggingIn = false
|
||||
staffAuthMock.loginError = null
|
||||
}
|
||||
|
||||
export function staffAuthContextMock() {
|
||||
return {
|
||||
StaffAuthProvider: ({ children }: { children?: ReactNode }) => children ?? null,
|
||||
useStaffAuth: () => ({
|
||||
isLoggedIn: staffAuthMock.isLoggedIn,
|
||||
isLoading: staffAuthMock.isLoading,
|
||||
staff: staffAuthMock.staff,
|
||||
regionId: staffAuthMock.regionId,
|
||||
isLoggingIn: staffAuthMock.isLoggingIn,
|
||||
loginError: staffAuthMock.loginError,
|
||||
login: staffAuthMock.login,
|
||||
logout: staffAuthMock.logout,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,214 +0,0 @@
|
|||
/**
|
||||
* Create banner screen (app/(drawer)/dashboard/dashboard-banners/create.tsx) —
|
||||
* BannerForm wiring, image requirement, upload + createBanner mutation,
|
||||
* validation, cancel and success navigation.
|
||||
*
|
||||
* The common-ui ImageUploader add button lives behind a separate
|
||||
* `@expo/vector-icons` copy, so instead of pressing it we intercept
|
||||
* common-ui's usePickImage hook (test-local module mock) and invoke a pick.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
const mockPickState: { trigger: (() => Promise<void>) | null } = { trigger: null }
|
||||
|
||||
jest.mock('common-ui/src/components/use-pick-image', () => ({
|
||||
__esModule: true,
|
||||
default: ({ setFile }: { setFile: (asset: unknown) => Promise<void> }) => {
|
||||
mockPickState.trigger = () =>
|
||||
setFile({
|
||||
uri: 'file:///tmp/pick.jpg',
|
||||
fileName: 'pick.jpg',
|
||||
mimeType: 'image/jpeg',
|
||||
})
|
||||
return () => {}
|
||||
},
|
||||
}))
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import CreateBanner from '@/app/(drawer)/dashboard/dashboard-banners/create'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
// "Create Banner" appears as both the header title and the submit button.
|
||||
const pressSubmit = () => {
|
||||
const labels = screen.getAllByText('Create Banner')
|
||||
fireEvent.press(labels[labels.length - 1])
|
||||
}
|
||||
|
||||
const blur = (placeholder: string, name: string) => {
|
||||
fireEvent(screen.getByPlaceholderText(placeholder), 'blur', {
|
||||
target: { name },
|
||||
persist: () => {},
|
||||
})
|
||||
}
|
||||
|
||||
const pickImage = async () => {
|
||||
await act(async () => {
|
||||
await mockPickState.trigger?.()
|
||||
})
|
||||
await screen.findByText('Only one image allowed')
|
||||
}
|
||||
|
||||
/** The app GETs the picked file:// asset; the harness fetch only knows tRPC. */
|
||||
const installAssetFetchShim = (fetchMock: jest.Mock) => {
|
||||
;(global as unknown as { fetch: unknown }).fetch = jest.fn((url: string, opts: unknown) => {
|
||||
if (String(url).startsWith('file:')) {
|
||||
return Promise.resolve({ ok: true, blob: async () => ({}) })
|
||||
}
|
||||
return fetchMock(url, opts)
|
||||
})
|
||||
}
|
||||
|
||||
const uploadProcedures = {
|
||||
'common.generateUploadUrls': {
|
||||
uploadUrls: ['https://cdn.example.com/product-images/pic.jpg'],
|
||||
},
|
||||
}
|
||||
|
||||
describe('Create banner', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
searchParamsMock.current = {}
|
||||
mockPickState.trigger = null
|
||||
routerMock.back.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the create form', () => {
|
||||
setupApiMocks()
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
expect(screen.getAllByText('Create Banner').length).toBeGreaterThan(1)
|
||||
expect(screen.getByPlaceholderText('Enter banner name')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter banner description (optional)')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('https://example.com/redirect')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the name validation error on blur', async () => {
|
||||
setupApiMocks()
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
blur('Enter banner name', 'name')
|
||||
|
||||
expect(await screen.findByText('Banner name is required')).toBeVisible()
|
||||
})
|
||||
|
||||
it('rejects a malformed redirect URL', async () => {
|
||||
setupApiMocks()
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('https://example.com/redirect'), 'not-a-url')
|
||||
blur('https://example.com/redirect', 'redirectUrl')
|
||||
|
||||
expect(await screen.findByText('Please enter a valid URL')).toBeVisible()
|
||||
})
|
||||
|
||||
it('does not create a banner without an image', async () => {
|
||||
const { fetchMock } = setupApiMocks()
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
|
||||
pressSubmit()
|
||||
|
||||
await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith('Error', 'Image is required'))
|
||||
expect(procCount(fetchMock, 'admin.banner.createBanner')).toBe(0)
|
||||
})
|
||||
|
||||
it('uploads the image and creates the banner', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
...uploadProcedures,
|
||||
'admin.banner.createBanner': { id: 1, name: 'My Banner' },
|
||||
},
|
||||
})
|
||||
installAssetFetchShim(fetchMock as unknown as jest.Mock)
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
|
||||
await pickImage()
|
||||
pressSubmit()
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.createBanner'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.banner.createBanner')).toMatchObject({
|
||||
name: 'My Banner',
|
||||
imageUrl: 'https://cdn.example.com/product-images/pic.jpg',
|
||||
skuIds: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('alerts and navigates back on successful creation', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
...uploadProcedures,
|
||||
'admin.banner.createBanner': { id: 1 },
|
||||
},
|
||||
})
|
||||
installAssetFetchShim(fetchMock as unknown as jest.Mock)
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
|
||||
await pickImage()
|
||||
pressSubmit()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Banner created successfully',
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
pressLastAlertButton('OK')
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('alerts an error when createBanner fails', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
...uploadProcedures,
|
||||
'admin.banner.createBanner': () => {
|
||||
throw new Error('nope')
|
||||
},
|
||||
},
|
||||
})
|
||||
installAssetFetchShim(fetchMock as unknown as jest.Mock)
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter banner name'), 'My Banner')
|
||||
await pickImage()
|
||||
pressSubmit()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Failed to create banner. Please try again.'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('cancels and navigates back', () => {
|
||||
setupApiMocks()
|
||||
renderWithProviders(<CreateBanner />)
|
||||
|
||||
fireEvent.press(screen.getByText('Cancel'))
|
||||
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,215 +0,0 @@
|
|||
/**
|
||||
* Edit banner screen (app/(drawer)/dashboard/dashboard-banners/edit/[id].tsx) —
|
||||
* getBanner hydration, updateBanner mutation, validation and navigation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import EditBanner from '@/app/(drawer)/dashboard/dashboard-banners/edit/[id]'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const banner = {
|
||||
id: 7,
|
||||
name: 'Banner Seven',
|
||||
imageUrl: 'https://cdn.example.com/seven.jpg',
|
||||
description: 'Seven desc',
|
||||
skuIds: [],
|
||||
redirectUrl: null,
|
||||
serialNum: 1,
|
||||
isActive: true,
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
lastUpdated: '2024-01-01T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('Edit banner', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
searchParamsMock.current = { id: '7' }
|
||||
routerMock.back.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('requests the banner by the route id', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.getBanner'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.banner.getBanner')).toEqual({ id: 7 })
|
||||
})
|
||||
|
||||
it('hydrates the form from the fetched banner', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
expect(await screen.findByDisplayValue('Banner Seven')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Seven desc')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the not-found state when the banner is missing', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanner': null } })
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
expect(await screen.findByText('Banner not found')).toBeVisible()
|
||||
})
|
||||
|
||||
it('updates the banner with the transformed payload', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanner': banner,
|
||||
'admin.banner.updateBanner': { ...banner, name: 'Renamed Banner' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
await screen.findByDisplayValue('Banner Seven')
|
||||
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
|
||||
fireEvent.press(screen.getByText('Update Banner'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.banner.updateBanner')).toMatchObject({
|
||||
id: 7,
|
||||
name: 'Renamed Banner',
|
||||
imageUrl: 'https://cdn.example.com/seven.jpg',
|
||||
description: 'Seven desc',
|
||||
skuIds: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('refreshes the banner list and refetches the mounted banner after a successful update', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanner': banner,
|
||||
'admin.banner.updateBanner': { ...banner, name: 'Renamed Banner' },
|
||||
'admin.banner.getBanners': [banner],
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
await screen.findByDisplayValue('Banner Seven')
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.getBanner'))
|
||||
|
||||
// Baselines: hydration has already pulled getBanner once, while getBanners
|
||||
// is `enabled: false` — nothing fetches it until the screen calls refetch().
|
||||
const getBannerBefore = procCount(fetchMock, 'admin.banner.getBanner')
|
||||
const getBannersBefore = procCount(fetchMock, 'admin.banner.getBanners')
|
||||
expect(getBannerBefore).toBeGreaterThan(0)
|
||||
|
||||
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
|
||||
fireEvent.press(screen.getByText('Update Banner'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
|
||||
|
||||
// `await refetchBanners()` — the explicit pull of the list query.
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(
|
||||
getBannersBefore
|
||||
)
|
||||
)
|
||||
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(0)
|
||||
|
||||
// `utils.admin.banner.getBanner.invalidate()` refetches the mounted query.
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.banner.getBanner')).toBeGreaterThan(
|
||||
getBannerBefore
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('does not update before the banner loads', () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.banner.getBanner': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
expect(procCount(fetchMock, 'admin.banner.updateBanner')).toBe(0)
|
||||
})
|
||||
|
||||
it('alerts when the update fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanner': banner,
|
||||
'admin.banner.updateBanner': () => {
|
||||
throw new Error('nope')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
await screen.findByDisplayValue('Banner Seven')
|
||||
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
|
||||
fireEvent.press(screen.getByText('Update Banner'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Failed to update banner. Please try again.'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('alerts success and navigates back after update', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanner': banner,
|
||||
'admin.banner.updateBanner': { ...banner, name: 'Renamed Banner' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
await screen.findByDisplayValue('Banner Seven')
|
||||
fireEvent.changeText(screen.getByDisplayValue('Banner Seven'), 'Renamed Banner')
|
||||
fireEvent.press(screen.getByText('Update Banner'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Banner updated successfully',
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
|
||||
routerMock.back.mockClear()
|
||||
pressLastAlertButton('OK')
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('BUG: alerts "Banner not found" and navigates back on mount before getBanner resolves', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
await screen.findByDisplayValue('Banner Seven')
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Banner not found')
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels and navigates back', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanner': banner } })
|
||||
renderWithProviders(<EditBanner />)
|
||||
|
||||
await screen.findByDisplayValue('Banner Seven')
|
||||
routerMock.back.mockClear()
|
||||
fireEvent.press(screen.getByText('Cancel'))
|
||||
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,237 +0,0 @@
|
|||
/**
|
||||
* Dashboard banners list (app/(drawer)/dashboard/dashboard-banners/index.tsx) —
|
||||
* banner rows, slot assignment/edit mode, save/empty-slot mutations, delete and
|
||||
* navigation to create/edit.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import DashboardBanners from '@/app/(drawer)/dashboard/dashboard-banners/index'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const bannerOne = {
|
||||
id: 1,
|
||||
name: 'Banner One',
|
||||
imageUrl: 'https://cdn.example.com/one.jpg',
|
||||
description: 'First banner',
|
||||
skuIds: [],
|
||||
redirectUrl: null,
|
||||
serialNum: 1,
|
||||
isActive: true,
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
lastUpdated: '2024-01-01T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const bannerTwo = {
|
||||
...bannerOne,
|
||||
id: 2,
|
||||
name: 'Banner Two',
|
||||
imageUrl: 'https://cdn.example.com/two.jpg',
|
||||
description: null,
|
||||
serialNum: null,
|
||||
isActive: false,
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
const iconByName = (name: string) => {
|
||||
const icons = screen.UNSAFE_getAllByType(MaterialIcons)
|
||||
return icons.find((icon) => icon.props.name === name) as unknown as Parameters<
|
||||
typeof fireEvent.press
|
||||
>[0]
|
||||
}
|
||||
|
||||
describe('Dashboard banners index', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
searchParamsMock.current = {}
|
||||
routerMock.push.mockClear()
|
||||
routerMock.back.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows a loading state while banners are pending', () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [bannerOne] } } })
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
|
||||
expect(screen.getByText('Loading banners...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders banner rows and assigns slotted banners to their slot', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] } },
|
||||
})
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
|
||||
expect(await screen.findByText('First banner')).toBeVisible()
|
||||
expect(screen.getByText('Banner Two')).toBeVisible()
|
||||
// banner one occupies slot 1 (label appears on both the tile and the row)
|
||||
expect(screen.getAllByText('Slot 1').length).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
it('renders the empty state when there are no banners', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [] } } })
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
|
||||
expect(await screen.findByText('No Banners Yet')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the error state when the query fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanners': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
|
||||
expect(await screen.findByText('Error loading banners')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to create from the floating action button', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [bannerOne] } } })
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
await screen.findByText('First banner')
|
||||
|
||||
fireEvent.press(screen.getByLabelText('Add new banner'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/dashboard-banners/create'
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to edit for the pressed banner', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.banner.getBanners': { banners: [bannerOne] } } })
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
await screen.findByText('First banner')
|
||||
|
||||
fireEvent.press(iconByName('edit'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/dashboard-banners/edit/1'
|
||||
)
|
||||
})
|
||||
|
||||
it('saves a new slot assignment through updateBanner', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] },
|
||||
'admin.banner.updateBanner': { ...bannerTwo, serialNum: 2 },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
await screen.findByText('Banner Two')
|
||||
|
||||
const fetchesBeforeSave = procCount(fetchMock, 'admin.banner.getBanners')
|
||||
|
||||
fireEvent.press(screen.getByText('Slot 2'))
|
||||
fireEvent.press(screen.getByText('Banner Two'))
|
||||
fireEvent.press(screen.getByText('Save Changes'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.banner.updateBanner')).toEqual({
|
||||
id: 2,
|
||||
serialNum: 2,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot assignments saved successfully')
|
||||
)
|
||||
// let the post-save refetch settle before the test unmounts
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(fetchesBeforeSave)
|
||||
)
|
||||
})
|
||||
|
||||
it('empties an occupied slot through updateBanner with serialNum null', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] },
|
||||
'admin.banner.updateBanner': { ...bannerOne, serialNum: null },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
await screen.findByText('First banner')
|
||||
|
||||
const fetchesBeforeEmptySlot = procCount(fetchMock, 'admin.banner.getBanners')
|
||||
|
||||
fireEvent.press(screen.getAllByText('Slot 1')[0])
|
||||
fireEvent.press(screen.getByText('Empty Slot'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.updateBanner'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.banner.updateBanner')).toEqual({
|
||||
id: 1,
|
||||
serialNum: null,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot 1 has been emptied')
|
||||
)
|
||||
// let the post-empty-slot refetch settle before the test unmounts
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(
|
||||
fetchesBeforeEmptySlot
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('cancels slot editing and restores assignments', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.banner.getBanners': { banners: [bannerOne, bannerTwo] } },
|
||||
})
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
await screen.findByText('Banner Two')
|
||||
|
||||
fireEvent.press(screen.getByText('Slot 2'))
|
||||
fireEvent.press(screen.getByText('Banner Two'))
|
||||
fireEvent.press(screen.getByText('Cancel'))
|
||||
|
||||
expect(screen.queryByText('Save Changes')).toBeNull()
|
||||
expect(procCount(fetchMock, 'admin.banner.updateBanner')).toBe(0)
|
||||
})
|
||||
|
||||
it('deletes a banner after confirming the alert', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.banner.getBanners': { banners: [bannerOne] },
|
||||
'admin.banner.deleteBanner': { success: true },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<DashboardBanners />)
|
||||
await screen.findByText('First banner')
|
||||
|
||||
fireEvent.press(iconByName('delete'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Delete Banner',
|
||||
'Are you sure you want to delete this banner?',
|
||||
expect.any(Array)
|
||||
)
|
||||
pressLastAlertButton('Delete')
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.banner.deleteBanner'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.banner.deleteBanner')).toEqual({ id: 1 })
|
||||
await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith('Success', 'Banner deleted'))
|
||||
// let the post-delete refetch settle before the test unmounts
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.banner.getBanners')).toBeGreaterThan(1)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,250 +0,0 @@
|
|||
/**
|
||||
* Complaints list (app/(drawer)/dashboard/complaints/index.tsx) — infinite list,
|
||||
* rows, empty/error/loading, resolve mutation and navigation.
|
||||
*
|
||||
* HARNESS BUG WORKAROUND: tests/mocks/native.ts has a stray top-level `return`
|
||||
* (line 89 → "'return' outside of function"), so any module that pulls in
|
||||
* `common-ui` (which eagerly imports expo-image/picker/document-picker) fails to
|
||||
* parse. The harness file is untouched; the three expo modules are re-mocked
|
||||
* locally below with equivalent, self-contained fakes. See the final report.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
jest.mock('expo-image', () => {
|
||||
const React = require('react')
|
||||
const { View } = require('react-native')
|
||||
const Image = (props: Record<string, unknown>) =>
|
||||
React.createElement(View, { testID: 'mock-image', ...props })
|
||||
return { __esModule: true, Image, default: Image }
|
||||
})
|
||||
|
||||
jest.mock('expo-image-picker', () => {
|
||||
const asset = { uri: 'file:///tmp/pick.jpg', fileName: 'pick.jpg', mimeType: 'image/jpeg' }
|
||||
return {
|
||||
__esModule: true,
|
||||
MediaTypeOptions: { Images: 'Images', All: 'All', Videos: 'Videos' },
|
||||
launchImageLibraryAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
launchCameraAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
requestMediaLibraryPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
requestCameraPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('expo-document-picker', () => ({
|
||||
__esModule: true,
|
||||
getDocumentAsync: jest.fn(async () => ({
|
||||
canceled: false,
|
||||
assets: [{ uri: 'file:///tmp/doc.pdf', name: 'doc.pdf', mimeType: 'application/pdf' }],
|
||||
})),
|
||||
}))
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, FlatList } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import Complaints from '@/app/(drawer)/dashboard/complaints/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { resetRefreshHooks } from '../mocks/refresh'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const pendingComplaint = {
|
||||
id: 5,
|
||||
text: 'Missing item in order',
|
||||
userId: 3,
|
||||
userName: 'Alice',
|
||||
userMobile: '9999999999',
|
||||
orderId: 7,
|
||||
status: 'pending',
|
||||
createdAt: '2026-01-01T10:00:00.000Z',
|
||||
images: ['https://assets.test/c/1.png'],
|
||||
response: null,
|
||||
}
|
||||
|
||||
const resolvedComplaint = {
|
||||
...pendingComplaint,
|
||||
id: 6,
|
||||
text: 'Late delivery',
|
||||
status: 'resolved',
|
||||
response: 'We have refunded the amount',
|
||||
images: [],
|
||||
}
|
||||
|
||||
const page = (complaints: unknown[], nextCursor?: number) => ({ complaints, nextCursor })
|
||||
|
||||
describe('Complaints list', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
resetRefreshHooks()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows a loading state while the list query is pending', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.complaint.getAll': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
expect(screen.getByText('Loading complaints...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders each complaint with status, reply and linked user/order', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.complaint.getAll': page([pendingComplaint, resolvedComplaint]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
|
||||
expect(screen.getByText('Complaint #6')).toBeVisible()
|
||||
expect(screen.getByText('Missing item in order')).toBeVisible()
|
||||
expect(screen.getByText('Pending')).toBeVisible()
|
||||
expect(screen.getByText('Resolved')).toBeVisible()
|
||||
expect(screen.getByText('We have refunded the amount')).toBeVisible()
|
||||
expect(screen.getAllByText('Alice').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('Order #7').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('only offers Resolve on pending complaints', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.complaint.getAll': page([pendingComplaint, resolvedComplaint]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
|
||||
expect(screen.getAllByText('Resolve Complaint')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no complaints', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.complaint.getAll': page([]) } })
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No complaints')).toBeVisible())
|
||||
expect(screen.getByText('All complaints will appear here')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state and refetches on Retry', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.complaint.getAll': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Error')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.complaint.getAll')
|
||||
fireEvent.press(screen.getByText('Retry'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.complaint.getAll')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('resolves a complaint with the admin response and refetches', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.complaint.getAll': page([pendingComplaint]),
|
||||
'admin.complaint.resolve': { message: 'Complaint resolved successfully' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
|
||||
const before = procCount(api.fetchMock, 'admin.complaint.getAll')
|
||||
|
||||
fireEvent.press(screen.getByText('Resolve Complaint'))
|
||||
fireEvent.changeText(
|
||||
await screen.findByPlaceholderText('Add a comment...'),
|
||||
'Refund issued'
|
||||
)
|
||||
fireEvent.press(screen.getByText('Resolve'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.complaint.resolve'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.complaint.resolve')).toEqual({
|
||||
id: '5',
|
||||
response: 'Refund issued',
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Complaint marked as resolved')
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.complaint.getAll')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('sends an empty response when the admin confirms without a note', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.complaint.getAll': page([pendingComplaint]),
|
||||
'admin.complaint.resolve': { message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Resolve Complaint'))
|
||||
fireEvent.press(await screen.findByText('Resolve'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.complaint.resolve'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.complaint.resolve')).toEqual({
|
||||
id: '5',
|
||||
response: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('navigates to the user and the order from a complaint row', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.complaint.getAll': page([pendingComplaint]) },
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Alice'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/3')
|
||||
|
||||
fireEvent.press(screen.getByText('Order #7'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/order-details/7'
|
||||
)
|
||||
})
|
||||
|
||||
it('fetches the next page when the list end is reached', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.complaint.getAll': (input: { cursor?: number }) =>
|
||||
input?.cursor
|
||||
? page([{ ...pendingComplaint, id: 9, text: 'Second page' }])
|
||||
: page([pendingComplaint], 100),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Complaints />)
|
||||
|
||||
await screen.findByText('Complaint #5')
|
||||
const list = screen.UNSAFE_getByType(FlatList as never)
|
||||
act(() => list.props.onEndReached())
|
||||
|
||||
expect(await screen.findByText('Second page')).toBeVisible()
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.complaint.getAll')).toMatchObject({
|
||||
limit: 20,
|
||||
cursor: 100,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -1,199 +0,0 @@
|
|||
/**
|
||||
* Create coupon screen (app/(drawer)/dashboard/coupons/create.tsx) — CouponForm
|
||||
* wiring, payload shaping (targetUsers->targetUser, flat->maxValue) and the
|
||||
* create / createReservedCoupon mutations.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import CreateCoupon from '@/app/(drawer)/dashboard/coupons/create'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { createQueryClient, renderWithProviders } from '../helpers/render'
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
const fillPercentageCoupon = (code = 'save10', percent = '10') => {
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), code)
|
||||
fireEvent.press(screen.getByText('Percentage'))
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., 10'), percent)
|
||||
}
|
||||
|
||||
describe('Create coupon', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
searchParamsMock.current = {}
|
||||
routerMock.back.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the coupon form', () => {
|
||||
setupApiMocks()
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
expect(screen.getByText('Coupon Codes')).toBeVisible()
|
||||
expect(screen.getByText('Discount Type *')).toBeVisible()
|
||||
expect(screen.getByText('Create Coupon')).toBeVisible()
|
||||
})
|
||||
|
||||
it('does not submit when the form is invalid', async () => {
|
||||
const { fetchMock } = setupApiMocks()
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Code 1')).toBeVisible())
|
||||
expect(procCount(fetchMock, 'admin.coupon.create')).toBe(0)
|
||||
expect(procCount(fetchMock, 'admin.coupon.createReservedCoupon')).toBe(0)
|
||||
})
|
||||
|
||||
it('uppercases the coupon code as it is typed', () => {
|
||||
setupApiMocks()
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'save10')
|
||||
|
||||
expect(screen.getByDisplayValue('SAVE10')).toBeVisible()
|
||||
})
|
||||
|
||||
it('creates a percentage coupon with the expected payload', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.coupon.create': [{ id: 1, couponCode: 'SAVE10' }] },
|
||||
})
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
fillPercentageCoupon()
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.create'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.coupon.create')).toMatchObject({
|
||||
couponCodes: ['SAVE10'],
|
||||
discountPercent: 10,
|
||||
isUserBased: false,
|
||||
isApplyForAll: false,
|
||||
exclusiveApply: false,
|
||||
isFirstOrderOnly: false,
|
||||
})
|
||||
expect(procCount(fetchMock, 'admin.coupon.createReservedCoupon')).toBe(0)
|
||||
})
|
||||
|
||||
it('invalidates both coupon list queries by path after a create', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.coupon.create': [{ id: 1, couponCode: 'SAVE10' }] },
|
||||
})
|
||||
// The list queries behind this form are not mounted here, so a fetch-count
|
||||
// assertion cannot see the refresh. Spy on the injected query client
|
||||
// instead; jest.spyOn keeps calling through, so invalidation still happens.
|
||||
const client = createQueryClient()
|
||||
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
|
||||
renderWithProviders(<CreateCoupon />, { queryClient: client })
|
||||
|
||||
fillPercentageCoupon()
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
|
||||
|
||||
// tRPC keys are [pathArray, ...]; assert the ARRAY path was used, so a
|
||||
// differently-filtered list (any search term) still matches the refresh.
|
||||
const paths = invalidateSpy.mock.calls.map((call) => {
|
||||
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
|
||||
return Array.isArray(key) ? key[0] : null
|
||||
})
|
||||
expect(paths).toContainEqual(['admin', 'coupon', 'getAll'])
|
||||
expect(paths).toContainEqual(['admin', 'coupon', 'getReservedCoupons'])
|
||||
})
|
||||
|
||||
it('creates a flat-discount coupon and mirrors it into maxValue', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.coupon.create': [{ id: 1 }] },
|
||||
})
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., SECRET10'), 'flat50')
|
||||
fireEvent.press(screen.getByText('Flat Amount'))
|
||||
fireEvent.changeText(screen.getByPlaceholderText('e.g., 50'), '50')
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.create'))
|
||||
const input = lastProcedureInput(fetchMock, 'admin.coupon.create') as Record<string, unknown>
|
||||
expect(input).toMatchObject({ couponCodes: ['FLAT50'], flatDiscount: 50, maxValue: 50 })
|
||||
expect(input.discountPercent).toBeUndefined()
|
||||
})
|
||||
|
||||
it('creates a reserved coupon when the checkbox is set', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.coupon.createReservedCoupon': [{ id: 1 }] },
|
||||
})
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
fillPercentageCoupon('secret20', '20')
|
||||
fireEvent.press(screen.getByRole('checkbox'))
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.coupon.createReservedCoupon')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.coupon.createReservedCoupon')).toMatchObject({
|
||||
couponCodes: ['SECRET20'],
|
||||
discountPercent: 20,
|
||||
})
|
||||
expect(procCount(fetchMock, 'admin.coupon.create')).toBe(0)
|
||||
})
|
||||
|
||||
it('alerts success and navigates back when the form is confirmed', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.coupon.create': [{ id: 1 }] },
|
||||
})
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
fillPercentageCoupon()
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'1 coupon created successfully',
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
|
||||
pressLastAlertButton('OK')
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('alerts the mutation error message', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.create': () => {
|
||||
throw new Error('Coupon code already exists: SAVE10')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<CreateCoupon />)
|
||||
|
||||
fillPercentageCoupon()
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Coupon code already exists: SAVE10'
|
||||
)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,217 +0,0 @@
|
|||
/**
|
||||
* Edit coupon screen (app/(drawer)/dashboard/coupons/edit/[id].tsx) — hydrates
|
||||
* CouponForm from getById and dispatches the update mutation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import EditCoupon from '@/app/(drawer)/dashboard/coupons/edit/[id]'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { createQueryClient, renderWithProviders } from '../helpers/render'
|
||||
|
||||
const coupon = {
|
||||
id: 5,
|
||||
couponCode: 'EDIT10',
|
||||
isUserBased: false,
|
||||
discountPercent: '10',
|
||||
flatDiscount: null,
|
||||
minOrder: '100',
|
||||
skuIds: [],
|
||||
maxValue: '50',
|
||||
isApplyForAll: true,
|
||||
validTill: '2099-01-01T00:00:00.000Z',
|
||||
maxLimitForUser: 2,
|
||||
exclusiveApply: false,
|
||||
isFirstOrderOnly: false,
|
||||
isInvalidated: false,
|
||||
createdBy: 1,
|
||||
targetUser: { id: 3, name: 'shafi', mobile: '9999999999' },
|
||||
applicableUsers: [],
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('Edit coupon', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
searchParamsMock.current = { id: '5' }
|
||||
routerMock.back.mockClear()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows loading while getById is pending', () => {
|
||||
setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('requests the coupon by the route id', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.getById'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.coupon.getById')).toEqual({ id: 5 })
|
||||
})
|
||||
|
||||
it('prefills the form from the fetched coupon', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
expect(await screen.findByDisplayValue('EDIT10')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('10')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('100')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows a not-found state when the coupon does not exist', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.coupon.getById': null } })
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
expect(await screen.findByText('Coupon not found')).toBeVisible()
|
||||
})
|
||||
|
||||
it('dispatches update with the transformed payload', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getById': coupon,
|
||||
'admin.coupon.update': { ...coupon },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
await screen.findByDisplayValue('EDIT10')
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.update'))
|
||||
const input = lastProcedureInput(fetchMock, 'admin.coupon.update') as {
|
||||
id: number
|
||||
updates: Record<string, unknown>
|
||||
}
|
||||
expect(input.id).toBe(5)
|
||||
expect(input.updates).toMatchObject({
|
||||
couponCodes: ['EDIT10'],
|
||||
discountPercent: 10,
|
||||
minOrder: 100,
|
||||
maxValue: 50,
|
||||
isApplyForAll: true,
|
||||
isUserBased: false,
|
||||
targetUser: 3,
|
||||
isReservedCoupon: false,
|
||||
})
|
||||
expect(input.updates.targetUsers).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not call update before the coupon loads', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getById': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
expect(procCount(fetchMock, 'admin.coupon.update')).toBe(0)
|
||||
})
|
||||
|
||||
it('alerts the update error message', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getById': coupon,
|
||||
'admin.coupon.update': () => {
|
||||
throw new Error('Cannot have both discountPercent and flatDiscount')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
await screen.findByDisplayValue('EDIT10')
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Cannot have both discountPercent and flatDiscount'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('alerts success and navigates back after update', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getById': coupon,
|
||||
'admin.coupon.update': { ...coupon },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditCoupon />)
|
||||
|
||||
await screen.findByDisplayValue('EDIT10')
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Coupon updated successfully',
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
|
||||
pressLastAlertButton('OK')
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refetches the mounted coupon and invalidates both coupon lists by path after update', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getById': coupon,
|
||||
'admin.coupon.update': { ...coupon },
|
||||
},
|
||||
})
|
||||
|
||||
const client = createQueryClient()
|
||||
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
|
||||
renderWithProviders(<EditCoupon />, { queryClient: client })
|
||||
|
||||
await screen.findByDisplayValue('EDIT10')
|
||||
|
||||
// These suites share a module-singleton tRPC client, so baseline the count
|
||||
// right before the interaction and assert a delta, never an absolute number.
|
||||
const before = procCount(fetchMock, 'admin.coupon.getById')
|
||||
fireEvent.press(screen.getByText('Create Coupon'))
|
||||
|
||||
// (a) the mounted getById query really refetches.
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.coupon.getById')).toBeGreaterThan(before)
|
||||
)
|
||||
|
||||
// (b) the two list invalidations used the ARRAY path, not a dotted string.
|
||||
const invalidatedPaths = () =>
|
||||
invalidateSpy.mock.calls.map((call) => {
|
||||
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
|
||||
return Array.isArray(key) ? key[0] : null
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(invalidatedPaths()).toContainEqual(['admin', 'coupon', 'getAll'])
|
||||
)
|
||||
expect(invalidatedPaths()).toContainEqual([
|
||||
'admin',
|
||||
'coupon',
|
||||
'getReservedCoupons',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
|
@ -1,289 +0,0 @@
|
|||
/**
|
||||
* Coupons list screen (app/(drawer)/dashboard/coupons/index.tsx) — the two
|
||||
* TabView tabs (General / Reserved), infinite pagination, search, delete and
|
||||
* navigation to create/edit.
|
||||
*
|
||||
* HARNESS BUG WORKAROUND: tests/mocks/native.ts `tabViewMock` is internally
|
||||
* inconsistent — its `SceneMap` returns the scenes object while `TabView`
|
||||
* invokes `renderScene({ route })` as a function, so rendering this screen
|
||||
* throws `TypeError: renderScene is not a function`. Its tab press also
|
||||
* hardcodes `onIndexChange(0)`. We override the module locally with a corrected
|
||||
* copy (the harness file itself is untouched). See the final report.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
jest.mock('react-native-tab-view', () => {
|
||||
const React = require('react')
|
||||
const { View, Text } = require('react-native')
|
||||
|
||||
const TabView = ({
|
||||
navigationState,
|
||||
renderScene,
|
||||
onIndexChange,
|
||||
}: {
|
||||
navigationState: { index: number; routes: { key: string }[] }
|
||||
renderScene: (info: { route: { key: string } }) => React.ReactNode
|
||||
onIndexChange?: (index: number) => void
|
||||
}) => {
|
||||
const route = navigationState.routes[navigationState.index]
|
||||
return React.createElement(
|
||||
View,
|
||||
{ testID: 'mock-tab-view' },
|
||||
navigationState.routes.map((r, i) =>
|
||||
React.createElement(
|
||||
Text,
|
||||
{ key: r.key, testID: `tab-${r.key}`, onPress: () => onIndexChange?.(i) },
|
||||
r.key
|
||||
)
|
||||
),
|
||||
route ? renderScene({ route }) : null
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
__esModule: true,
|
||||
TabView,
|
||||
SceneMap: (scenes: Record<string, React.ComponentType>) => ({ route }: { route: { key: string } }) => {
|
||||
const Scene = scenes[route.key]
|
||||
return React.createElement(Scene)
|
||||
},
|
||||
TabBar: () => null,
|
||||
}
|
||||
})
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, FlatList } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import Coupons from '@/app/(drawer)/dashboard/coupons/index'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import { lastProcedureInput, expectProcedureCalled, procCount } from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { searchParamsMock, routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const activeCoupon = {
|
||||
id: 1,
|
||||
couponCode: 'SAVE10',
|
||||
isUserBased: false,
|
||||
discountPercent: '10',
|
||||
flatDiscount: null,
|
||||
minOrder: null,
|
||||
skuIds: null,
|
||||
maxValue: null,
|
||||
isApplyForAll: true,
|
||||
validTill: '2099-01-01T00:00:00.000Z',
|
||||
maxLimitForUser: null,
|
||||
exclusiveApply: false,
|
||||
isFirstOrderOnly: false,
|
||||
isInvalidated: false,
|
||||
createdBy: 1,
|
||||
applicableUsers: [],
|
||||
}
|
||||
|
||||
const expiredCoupon = {
|
||||
...activeCoupon,
|
||||
id: 2,
|
||||
couponCode: 'OLDCODE',
|
||||
flatDiscount: '50',
|
||||
discountPercent: null,
|
||||
validTill: '2000-01-01T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const reservedCoupon = {
|
||||
id: 9,
|
||||
secretCode: 'SECRET9',
|
||||
couponCode: 'SECRET9',
|
||||
discountPercent: '20',
|
||||
flatDiscount: null,
|
||||
minOrder: null,
|
||||
maxValue: null,
|
||||
validTill: '2099-01-01T00:00:00.000Z',
|
||||
isRedeemed: false,
|
||||
redeemedUser: null,
|
||||
redeemedAt: null,
|
||||
creator: { id: 1, name: 'shafi' },
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
const button = buttons.find((b) => b.text === label)
|
||||
act(() => button?.onPress?.())
|
||||
}
|
||||
|
||||
describe('Coupons index', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
searchParamsMock.current = {}
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
routerMock.push.mockClear()
|
||||
})
|
||||
|
||||
it('shows a loading state while the list query is pending', () => {
|
||||
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } })
|
||||
renderWithProviders(<Coupons />)
|
||||
|
||||
expect(screen.getByText('Loading Coupons...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders coupon rows from the getAll infinite query', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon, expiredCoupon] } },
|
||||
})
|
||||
renderWithProviders(<Coupons />)
|
||||
|
||||
expect(await screen.findByText('SAVE10')).toBeVisible()
|
||||
expect(screen.getByText('OLDCODE')).toBeVisible()
|
||||
expect(screen.getByText('Discount: 10% off')).toBeVisible()
|
||||
expect(screen.getByText('Discount: ₹50 off')).toBeVisible()
|
||||
expect(screen.getAllByText('Expired').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('renders the empty state when there are no coupons', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [] } } })
|
||||
renderWithProviders(<Coupons />)
|
||||
|
||||
expect(await screen.findByText('No Coupons Found')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the error state and retries on press', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getAll': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Coupons />)
|
||||
|
||||
expect(await screen.findByText('Failed to load coupons')).toBeVisible()
|
||||
const before = procCount(fetchMock, 'admin.coupon.getAll')
|
||||
|
||||
fireEvent.press(screen.getByText('Retry'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.coupon.getAll')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('fetches the next page when the list end is reached', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getAll': (input: any) =>
|
||||
input?.cursor
|
||||
? { coupons: [{ ...activeCoupon, id: 3, couponCode: 'PAGE2' }] }
|
||||
: { coupons: [activeCoupon], nextCursor: 100 },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Coupons />)
|
||||
|
||||
await screen.findByText('SAVE10')
|
||||
|
||||
const list = screen.UNSAFE_getByType(FlatList as any)
|
||||
act(() => list.props.onEndReached())
|
||||
|
||||
expect(await screen.findByText('PAGE2')).toBeVisible()
|
||||
expect(lastProcedureInput(fetchMock, 'admin.coupon.getAll')).toMatchObject({
|
||||
limit: 20,
|
||||
cursor: 100,
|
||||
})
|
||||
})
|
||||
|
||||
it('sends the search term to getAll', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } },
|
||||
})
|
||||
renderWithProviders(<Coupons />)
|
||||
|
||||
await screen.findByText('SAVE10')
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Search coupons...'), 'SAVE')
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.coupon.getAll')).toMatchObject({
|
||||
limit: 20,
|
||||
search: 'SAVE',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to the create screen from the floating action button', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } })
|
||||
renderWithProviders(<Coupons />)
|
||||
await screen.findByText('SAVE10')
|
||||
|
||||
fireEvent.press(screen.getByTestId('mock-linear-gradient'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/create')
|
||||
})
|
||||
|
||||
it('navigates to the edit screen for the pressed coupon', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } })
|
||||
renderWithProviders(<Coupons />)
|
||||
await screen.findByText('SAVE10')
|
||||
|
||||
fireEvent.press(screen.getByText('Edit'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/edit/1')
|
||||
})
|
||||
|
||||
it('deletes a coupon after confirming the alert', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getAll': { coupons: [activeCoupon] },
|
||||
'admin.coupon.delete': { message: 'Coupon invalidated successfully' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Coupons />)
|
||||
await screen.findByText('SAVE10')
|
||||
|
||||
fireEvent.press(screen.getByText('Delete'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Delete Coupon',
|
||||
'Are you sure you want to delete this coupon?',
|
||||
expect.any(Array)
|
||||
)
|
||||
|
||||
pressLastAlertButton('Delete')
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.delete'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.coupon.delete')).toEqual({ id: 1 })
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Coupon deleted successfully')
|
||||
)
|
||||
})
|
||||
|
||||
it('switches to the Reserved tab and lists reserved coupons', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getAll': { coupons: [activeCoupon] },
|
||||
'admin.coupon.getReservedCoupons': { coupons: [reservedCoupon] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Coupons />)
|
||||
await screen.findByText('SAVE10')
|
||||
|
||||
fireEvent.press(screen.getByTestId('tab-reserved'))
|
||||
|
||||
expect(await screen.findByText('SECRET9')).toBeVisible()
|
||||
expect(screen.getByTestId('tab-reserved')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the reserved empty state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.coupon.getAll': { coupons: [activeCoupon] },
|
||||
'admin.coupon.getReservedCoupons': { coupons: [] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Coupons />)
|
||||
|
||||
fireEvent.press(screen.getByTestId('tab-reserved'))
|
||||
|
||||
expect(await screen.findByText('No Reserved Coupons Found')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,220 +0,0 @@
|
|||
/**
|
||||
* All items order editor
|
||||
* (app/(drawer)/dashboard/customize-app/all-items-order.tsx) — sorts the
|
||||
* catalogue by the `allItemsOrder` constant, supports drag reordering and saves
|
||||
* the full ordered id list back to the constant.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import AllItemsOrder from '@/app/(drawer)/dashboard/customize-app/all-items-order'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { createQueryClient, renderWithProviders } from '../helpers/render'
|
||||
|
||||
const productsResponse = {
|
||||
products: [
|
||||
{ id: 1, name: 'Chicken', images: ['chicken.jpg'], isOutOfStock: false },
|
||||
{ id: 2, name: 'Mutton', images: ['mutton.jpg'], isOutOfStock: true },
|
||||
{ id: 3, name: 'Fish', images: [], isOutOfStock: false },
|
||||
],
|
||||
count: 3,
|
||||
}
|
||||
|
||||
describe('All items order editor', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while constants load', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => new Promise(() => {}),
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
expect(screen.getByText('Loading order...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state when constants fail', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
|
||||
})
|
||||
|
||||
it('sorts products by the constant and appends the rest', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [2, 1] }],
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Mutton')).toBeVisible())
|
||||
|
||||
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
expect(list.props.data.map((p: { id: number }) => p.id)).toEqual([2, 1, 3])
|
||||
expect(screen.getByText(/3 items/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('accepts a comma-separated order string', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: '3' }],
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Fish')).toBeVisible())
|
||||
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
expect(list.props.data.map((p: { id: number }) => p.id)).toEqual([3, 1, 2])
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no products', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [] }],
|
||||
'common.product.getAllProductsSummary': { products: [], count: 0 },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No products available')).toBeVisible())
|
||||
})
|
||||
|
||||
it('disables Save until the order changes, then saves the full list', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }],
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] },
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
expect(procCount(api.fetchMock, 'admin.region.updateRegionConstants')).toBe(0)
|
||||
|
||||
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[2], list.props.data[0], list.props.data[1]] })
|
||||
})
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({
|
||||
constants: [{ key: 'allItemsOrder', value: [3, 1, 2] }],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'All items order updated successfully!'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches the constants after saving', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }],
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] },
|
||||
},
|
||||
})
|
||||
const client = createQueryClient()
|
||||
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
|
||||
const result = renderWithProviders(<AllItemsOrder />, { queryClient: client })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
const before = procCount(api.fetchMock, 'admin.region.getRegionConstants')
|
||||
// Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's
|
||||
// request can land in this test's fetchMock.
|
||||
expect(before).toBeGreaterThan(0)
|
||||
|
||||
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[2], list.props.data[0], list.props.data[1]] })
|
||||
})
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.region.getRegionConstants')).toBeGreaterThan(before)
|
||||
)
|
||||
// The refetch is driven by the path-based invalidation, not by updateConstants itself.
|
||||
// Asserting the ARRAY path is the point: the old dotted string matched no query at all.
|
||||
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
|
||||
expect(
|
||||
invalidateSpy.mock.calls
|
||||
.map((call) => (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey)
|
||||
.map((key) => (Array.isArray(key) ? key[0] : null))
|
||||
).toContainEqual(['admin', 'const', 'getConstants'])
|
||||
// Same client, same cache: the array path matches the live query, the dotted form matches none.
|
||||
expect(
|
||||
client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length
|
||||
).toBeGreaterThan(0)
|
||||
expect(
|
||||
client.getQueryCache().findAll({ queryKey: ['admin.region.getRegionConstants'] })
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shows the saving label while the update is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }],
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'admin.region.updateRegionConstants': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0], list.props.data[2]] })
|
||||
})
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
|
||||
})
|
||||
|
||||
it('goes back from the header and the error state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AllItemsOrder />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Go Back'))
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,171 +0,0 @@
|
|||
/**
|
||||
* Customize App hub (app/(drawer)/dashboard/customize-app/index.tsx) — renders
|
||||
* the visible constants, links to the popular-items / all-items-order editors,
|
||||
* and saves only the constants that changed.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import CustomizeApp from '@/app/(drawer)/dashboard/customize-app/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const constants = [
|
||||
{ key: 'deliveryCharge', value: 10 },
|
||||
{ key: 'supportMobile', value: '9999999999' },
|
||||
{ key: 'isFlashDeliveryEnabled', value: false },
|
||||
{ key: 'popularItems', value: [1, 2] },
|
||||
{ key: 'allItemsOrder', value: [3] },
|
||||
]
|
||||
|
||||
const renderHub = () =>
|
||||
renderWithProviders(<CustomizeApp />)
|
||||
|
||||
describe('Customize App hub', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while constants load', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.const.getConstants': () => new Promise(() => {}) },
|
||||
})
|
||||
renderHub()
|
||||
|
||||
expect(screen.getByText('Loading constants...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the failed state when constants are missing', async () => {
|
||||
renderHub()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
|
||||
})
|
||||
|
||||
it('renders the visible constants and section links', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.const.getConstants': constants },
|
||||
})
|
||||
renderHub()
|
||||
|
||||
expect(await screen.findByText('Customize App Constants')).toBeVisible()
|
||||
expect(screen.getByText('Delivery Charge')).toBeVisible()
|
||||
expect(screen.getByText('Support Mobile')).toBeVisible()
|
||||
expect(screen.getByText('Enable Flash Delivery')).toBeVisible()
|
||||
expect(screen.getByText('Manage Popular Items (2 items)')).toBeVisible()
|
||||
expect(screen.getByText('Manage All Visible Items (1 items)')).toBeVisible()
|
||||
expect(screen.getByText('Save Changes')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to the popular items editor', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.const.getConstants': constants },
|
||||
})
|
||||
renderHub()
|
||||
|
||||
fireEvent.press(await screen.findByText('Manage Popular Items (2 items)'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/customize-app/popular-items'
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to the all items order editor', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.const.getConstants': constants },
|
||||
})
|
||||
renderHub()
|
||||
|
||||
fireEvent.press(await screen.findByText('Manage All Visible Items (1 items)'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/customize-app/all-items-order'
|
||||
)
|
||||
})
|
||||
|
||||
it('alerts when saving without changes and skips the mutation', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'admin.const.getConstants': constants },
|
||||
})
|
||||
renderHub()
|
||||
|
||||
fireEvent.press(await screen.findByText('Save Changes'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('No Changes', 'No constants were modified.')
|
||||
)
|
||||
expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0)
|
||||
})
|
||||
|
||||
it('saves only the changed constant', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.const.getConstants': constants,
|
||||
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['deliveryCharge'] },
|
||||
},
|
||||
})
|
||||
renderHub()
|
||||
|
||||
await screen.findByText('Delivery Charge')
|
||||
fireEvent.changeText(screen.getAllByPlaceholderText('Enter number')[0], '25')
|
||||
fireEvent.press(screen.getByText('Save Changes'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
|
||||
constants: [{ key: 'deliveryCharge', value: 25 }],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Updated 1 constants successfully.'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('toggles a boolean constant and saves it', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.const.getConstants': constants,
|
||||
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['isFlashDeliveryEnabled'] },
|
||||
},
|
||||
})
|
||||
renderHub()
|
||||
|
||||
await screen.findByText('Enable Flash Delivery')
|
||||
expect(screen.getByText('Disabled')).toBeVisible()
|
||||
fireEvent.press(screen.getByRole('checkbox'))
|
||||
await waitFor(() => expect(screen.getByText('Enabled')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Save Changes'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
|
||||
constants: [{ key: 'isFlashDeliveryEnabled', value: true }],
|
||||
})
|
||||
})
|
||||
|
||||
it('shows the updating label while the mutation is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.const.getConstants': constants,
|
||||
'admin.const.updateConstants': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
renderHub()
|
||||
|
||||
await screen.findByText('Delivery Charge')
|
||||
fireEvent.changeText(screen.getAllByPlaceholderText('Enter number')[0], '25')
|
||||
fireEvent.press(screen.getByText('Save Changes'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Updating...')).toBeVisible())
|
||||
})
|
||||
})
|
||||
|
|
@ -1,298 +0,0 @@
|
|||
/**
|
||||
* Popular items editor
|
||||
* (app/(drawer)/dashboard/customize-app/popular-items.tsx) — resolves the
|
||||
* `popularItems` constant against the product catalogue, supports removing /
|
||||
* adding items and saves the ordered product ids back to the constant.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
|
||||
import PopularItems from '@/app/(drawer)/dashboard/customize-app/popular-items'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { createQueryClient, renderWithProviders } from '../helpers/render'
|
||||
|
||||
const product = (id: number, name: string, price: number) => ({
|
||||
id,
|
||||
name,
|
||||
price,
|
||||
marketPrice: null,
|
||||
images: [`${name}.jpg`],
|
||||
storeId: null,
|
||||
nextDeliveryDate: null,
|
||||
isOutOfStock: false,
|
||||
})
|
||||
|
||||
const productsResponse = {
|
||||
products: [product(1, 'Chicken', 100), product(2, 'Mutton', 200), product(3, 'Fish', 50)],
|
||||
count: 3,
|
||||
}
|
||||
|
||||
// SKU ids intentionally match product ids so the selector's ids resolve against
|
||||
// the product catalogue (see the reported popular-items add-flow bug).
|
||||
const skusResponse = {
|
||||
skus: [
|
||||
{ id: 3, productId: 3, productName: 'Fish', label: 'Fish 1kg' },
|
||||
],
|
||||
}
|
||||
|
||||
const constants = [{ key: 'popularItems', value: [1, 2] }]
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
const pressIcon = (result: ReturnType<typeof renderWithProviders>, name: string, index = 0) => {
|
||||
const icons = result.UNSAFE_getAllByType(MaterialIcons).filter((n) => n.props.name === name)
|
||||
fireEvent.press(icons[index])
|
||||
}
|
||||
|
||||
describe('Popular items editor', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while constants load', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => new Promise(() => {}),
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PopularItems />)
|
||||
|
||||
expect(screen.getByText('Loading constants...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state when constants fail', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PopularItems />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
|
||||
})
|
||||
|
||||
it('renders the popular items resolved from the constant', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': constants,
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PopularItems />)
|
||||
|
||||
expect(await screen.findByText('Chicken')).toBeVisible()
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
expect(screen.getByText('₹100')).toBeVisible()
|
||||
expect(screen.queryByText('Fish')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows the empty state when nothing is configured', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'popularItems', value: [] }],
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PopularItems />)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('No popular items configured')).toBeVisible()
|
||||
)
|
||||
})
|
||||
|
||||
it('removes a product and saves the remaining ids', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': constants,
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<PopularItems />)
|
||||
|
||||
await screen.findByText('Chicken')
|
||||
pressIcon(result, 'delete', 0)
|
||||
pressLastAlertButton('Remove')
|
||||
await waitFor(() => expect(screen.queryByText('Chicken')).toBeNull())
|
||||
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({
|
||||
constants: [{ key: 'popularItems', value: [2] }],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Popular items updated successfully!'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('saves a reordered list', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': constants,
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<PopularItems />)
|
||||
|
||||
await screen.findByText('Chicken')
|
||||
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
|
||||
})
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({
|
||||
constants: [{ key: 'popularItems', value: [2, 1] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('refetches the constants after saving', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': constants,
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
||||
},
|
||||
})
|
||||
const client = createQueryClient()
|
||||
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
|
||||
const result = renderWithProviders(<PopularItems />, { queryClient: client })
|
||||
|
||||
await screen.findByText('Chicken')
|
||||
const before = procCount(api.fetchMock, 'admin.region.getRegionConstants')
|
||||
// Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's
|
||||
// request can land in this test's fetchMock.
|
||||
expect(before).toBeGreaterThan(0)
|
||||
|
||||
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
|
||||
})
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.region.getRegionConstants')).toBeGreaterThan(before)
|
||||
)
|
||||
// The refetch is driven by the path-based invalidation, not by updateConstants itself.
|
||||
// Asserting the ARRAY path is the point: the old dotted string matched no query at all.
|
||||
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
|
||||
expect(
|
||||
invalidateSpy.mock.calls
|
||||
.map((call) => (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey)
|
||||
.map((key) => (Array.isArray(key) ? key[0] : null))
|
||||
).toContainEqual(['admin', 'const', 'getConstants'])
|
||||
// Same client, same cache: the array path matches the live query, the dotted form matches none.
|
||||
expect(
|
||||
client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length
|
||||
).toBeGreaterThan(0)
|
||||
expect(
|
||||
client.getQueryCache().findAll({ queryKey: ['admin.region.getRegionConstants'] })
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not save while nothing changed', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': constants,
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PopularItems />)
|
||||
|
||||
await screen.findByText('Chicken')
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
expect(procCount(api.fetchMock, 'admin.region.updateRegionConstants')).toBe(0)
|
||||
})
|
||||
|
||||
it('adds a product through the add dialog and saves it', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': constants,
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<PopularItems />)
|
||||
|
||||
await screen.findByText('Chicken')
|
||||
pressIcon(result, 'add')
|
||||
expect(await screen.findByText('Add Popular Items')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('Choose products...'))
|
||||
fireEvent.press(await screen.findByTestId('undefined-option-3'))
|
||||
fireEvent.press(screen.getByText('Done'))
|
||||
fireEvent.press(await screen.findByText('Add 1 Product'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Fish')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({
|
||||
constants: [{ key: 'popularItems', value: [1, 2, 3] }],
|
||||
})
|
||||
})
|
||||
|
||||
it('shows the saving label while the update is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': constants,
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
'admin.region.updateRegionConstants': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<PopularItems />)
|
||||
|
||||
await screen.findByText('Chicken')
|
||||
pressIcon(result, 'delete', 0)
|
||||
pressLastAlertButton('Remove')
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
|
||||
})
|
||||
|
||||
it('goes back from the header and the error state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
'common.product.getAllProductsSummary': productsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PopularItems />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Go Back'))
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,116 +0,0 @@
|
|||
/**
|
||||
* Dashboard hub (app/(drawer)/dashboard/index.tsx) — quick actions, the
|
||||
* complaints badge from getEssentials, and navigation (incl. the navigation
|
||||
* target set for the manage-orders flow).
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Text } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import Dashboard from '@/app/(drawer)/dashboard/index'
|
||||
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { expectProcedureCalled } from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const TargetProbe = () => {
|
||||
const { navigationTarget } = useNavigationTarget()
|
||||
return <Text testID="target-probe">{navigationTarget ?? 'none'}</Text>
|
||||
}
|
||||
|
||||
describe('Dashboard hub', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getEssentials': { unresolvedComplaints: 3 } },
|
||||
})
|
||||
})
|
||||
|
||||
it('renders the quick actions and grouped menu items', async () => {
|
||||
renderWithProviders(<Dashboard />)
|
||||
|
||||
expect(screen.getByText('Quick Actions')).toBeVisible()
|
||||
expect(screen.getByText('Delivery Slots')).toBeVisible()
|
||||
expect(screen.getByText('Add Product')).toBeVisible()
|
||||
expect(screen.getByText('Complaints')).toBeVisible()
|
||||
expect(screen.getByText('Orders')).toBeVisible()
|
||||
expect(screen.getByText('Manage Orders')).toBeVisible()
|
||||
expect(screen.getByText('Delivery Sequences')).toBeVisible()
|
||||
expect(screen.getByText('Products & Inventory')).toBeVisible()
|
||||
expect(screen.getByText('Prices Overview')).toBeVisible()
|
||||
expect(screen.getByText('Product Groupings')).toBeVisible()
|
||||
expect(screen.getByText('Settings & Configuration')).toBeVisible()
|
||||
// Both the category header and its menu tile say "User Management".
|
||||
expect(screen.getAllByText('User Management').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('shows the unresolved-complaints badge from getEssentials', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.user.getEssentials': { unresolvedComplaints: 3 } },
|
||||
})
|
||||
renderWithProviders(<Dashboard />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('3')).toBeVisible())
|
||||
expectProcedureCalled(fetchMock, 'admin.user.getEssentials')
|
||||
})
|
||||
|
||||
it('navigates to manage orders and sets the nested navigation target', () => {
|
||||
renderWithProviders(
|
||||
<>
|
||||
<Dashboard />
|
||||
<TargetProbe />
|
||||
</>
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Manage Orders'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
|
||||
expect(screen.getByTestId('target-probe')).toHaveTextContent(
|
||||
'/(drawer)/dashboard/manage-orders/orders'
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to delivery sequences with its nested navigation target', () => {
|
||||
renderWithProviders(
|
||||
<>
|
||||
<Dashboard />
|
||||
<TargetProbe />
|
||||
</>
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Delivery Sequences'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
|
||||
expect(screen.getByTestId('target-probe')).toHaveTextContent(
|
||||
'/(drawer)/dashboard/manage-orders/delivery-sequences'
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates from the quick-action tiles by testID', () => {
|
||||
renderWithProviders(<Dashboard />)
|
||||
|
||||
fireEvent.press(screen.getByTestId('delivery-slots-menu-item'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots')
|
||||
|
||||
fireEvent.press(screen.getByTestId('add-product-menu-item'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/add')
|
||||
})
|
||||
|
||||
it('navigates to prices overview', () => {
|
||||
renderWithProviders(<Dashboard />)
|
||||
|
||||
fireEvent.press(screen.getByText('Prices Overview'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/prices-overview'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,387 +0,0 @@
|
|||
/**
|
||||
* Delivery sequences
|
||||
* (app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx) — slot
|
||||
* picker, unassigned/all-users filtering, assigning & unassigning orders,
|
||||
* packaged/delivered toggles, notes, cancel and order intents.
|
||||
*
|
||||
* NOTE: the "save sequence" FAB only appears after a drag (`hasSequenceChanged`).
|
||||
* The mocked draggable list never fires onDragEnd on its own, but the prop is
|
||||
* still on the rendered element and can be invoked through
|
||||
* UNSAFE_getByType(...).props.onDragEnd({ data }) inside act(), which is how the
|
||||
* reorder-save path (`handleSaveSequence`) is covered below. Assignment changes
|
||||
* persist via updateDeliverySequence directly.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, Linking } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import dayjs from 'dayjs'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import Entypo from '@expo/vector-icons/Entypo'
|
||||
import Ionicons from '@expo/vector-icons/Ionicons'
|
||||
|
||||
import DeliverySequences from '@/app/(drawer)/dashboard/manage-orders/delivery-sequences'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const SLOTS = [
|
||||
{ id: 3, deliveryTime: '2026-01-01T09:00:00.000Z' },
|
||||
{ id: 4, deliveryTime: '2026-01-02T09:00:00.000Z' },
|
||||
]
|
||||
const LABEL_3 = dayjs(SLOTS[0].deliveryTime).format('ddd DD MMM, h:mm a')
|
||||
const LABEL_4 = dayjs(SLOTS[1].deliveryTime).format('ddd DD MMM, h:mm a')
|
||||
|
||||
const slotOrder = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 21,
|
||||
readableId: 21,
|
||||
customerName: 'Bob',
|
||||
address: '12 Main St, Phone: 9876543210',
|
||||
addressId: 5,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
totalAmount: 300,
|
||||
items: [],
|
||||
deliveryTime: null,
|
||||
status: 'pending',
|
||||
isPackaged: false,
|
||||
isDelivered: false,
|
||||
slotId: 3,
|
||||
adminNotes: 'fragile',
|
||||
userNotes: null,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const defaultProcedures = (overrides: Record<string, unknown> = {}) => ({
|
||||
'admin.slots.getAll': { slots: SLOTS, count: 2 },
|
||||
'admin.order.getSlotOrders': { success: true, data: [slotOrder()] },
|
||||
'admin.slots.getDeliverySequence': { deliverySequence: {} },
|
||||
'admin.staffUser.getStaff': { staff: [{ id: 7, name: 'Ravi' }, { id: 8, name: 'Sita' }] },
|
||||
'admin.slots.updateDeliverySequence': { slot: { id: 3, deliverySequence: {} }, message: 'ok' },
|
||||
'admin.order.updatePackaged': { success: true, userId: 1 },
|
||||
'admin.order.updateDelivered': { success: true, userId: 1 },
|
||||
'admin.order.updateNotes': { id: 21 },
|
||||
'admin.order.cancelOrder': { success: true, message: 'cancelled' },
|
||||
'admin.order.updateAddressCoords': { success: true },
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderScreen = (overrides: Record<string, unknown> = {}) => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: defaultProcedures(overrides) })
|
||||
// `view` is returned so tests can reach props of the mocked DraggableFlatList
|
||||
// (its `onDragEnd` prop is not fired by the mock component itself).
|
||||
const view = renderWithProviders(<DeliverySequences />)
|
||||
return { fetchMock, view }
|
||||
}
|
||||
|
||||
const openOrderMenu = async () => {
|
||||
const dots = screen.UNSAFE_getAllByType(Entypo)[0]
|
||||
fireEvent.press(dots)
|
||||
await screen.findByText('Select an action to perform')
|
||||
}
|
||||
|
||||
const openUserDropdown = async () => {
|
||||
fireEvent.press(await screen.findByText('Unassigned'))
|
||||
await screen.findByText('All Users')
|
||||
}
|
||||
|
||||
const toggleMenuResponder = async (name: 'square-outline' | 'checkbox') => {
|
||||
const icon = screen.UNSAFE_getAllByType(Ionicons).find((node) => node.props.name === name)!
|
||||
fireEvent(icon, 'responderEnd', { stopPropagation: jest.fn() })
|
||||
}
|
||||
|
||||
const openAssignDropdown = async () => {
|
||||
const icon = screen
|
||||
.UNSAFE_getAllByType(MaterialIcons)
|
||||
.find((node) => node.props.name === 'person-add')!
|
||||
fireEvent.press(icon)
|
||||
await screen.findByText('Assign To')
|
||||
}
|
||||
|
||||
describe('Delivery sequences', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
resetRefreshHooks()
|
||||
searchParamsMock.current = { slotId: '3' }
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
jest.spyOn(Linking, 'openURL').mockResolvedValue(true)
|
||||
})
|
||||
|
||||
it('shows a loading message while slots load', () => {
|
||||
renderScreen()
|
||||
|
||||
expect(screen.getByText('Loading slots...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('reports when there are no slots', async () => {
|
||||
renderScreen({ 'admin.slots.getAll': { slots: [], count: 0 } })
|
||||
|
||||
expect(await screen.findByText('No slots available')).toBeVisible()
|
||||
})
|
||||
|
||||
it('auto-selects the first slot and prompts when no slot is given', async () => {
|
||||
searchParamsMock.current = {}
|
||||
renderScreen()
|
||||
|
||||
expect(
|
||||
await screen.findByText('No slot selected. Please select a slot to view delivery sequence.')
|
||||
).toBeVisible()
|
||||
await waitFor(() =>
|
||||
expect(routerMock.replace).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=3'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('queries slot orders and sequence with the route slot id', async () => {
|
||||
const { fetchMock } = renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.getSlotOrders')).toEqual({ slotId: '3' })
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.getDeliverySequence')).toEqual({ id: '3' })
|
||||
})
|
||||
|
||||
it('renders the order card details', async () => {
|
||||
renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
expect(screen.getByText('₹300')).toBeVisible()
|
||||
expect(screen.getByText('fragile')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders an empty state when there are no orders', async () => {
|
||||
renderScreen({ 'admin.order.getSlotOrders': { success: true, data: [] } })
|
||||
|
||||
expect(await screen.findByText('No orders found for this slot')).toBeVisible()
|
||||
})
|
||||
|
||||
it('filters to a user with no sequence and reports empty', async () => {
|
||||
renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
await openUserDropdown()
|
||||
fireEvent.press(screen.getByText('Ravi'))
|
||||
|
||||
expect(await screen.findByText('No orders found for this slot')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows assignment info in the All Users view', async () => {
|
||||
renderScreen({ 'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21] } } })
|
||||
|
||||
await openUserDropdown()
|
||||
fireEvent.press(screen.getByText('All Users'))
|
||||
|
||||
expect(await screen.findByText('Assigned to')).toBeVisible()
|
||||
expect(screen.getByText('Ravi')).toBeVisible()
|
||||
expect(screen.getByText('#21')).toBeVisible()
|
||||
})
|
||||
|
||||
it('assigns selected orders to a user', async () => {
|
||||
const { fetchMock } = renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
fireEvent.press(screen.getAllByRole('checkbox')[0])
|
||||
await openAssignDropdown()
|
||||
fireEvent.press(screen.getByText('Ravi'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.updateDeliverySequence')).toEqual({
|
||||
id: 3,
|
||||
deliverySequence: { '7': [21] },
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('unassigns selected orders from all users', async () => {
|
||||
const { fetchMock } = renderScreen({
|
||||
'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21] } },
|
||||
})
|
||||
|
||||
await openUserDropdown()
|
||||
fireEvent.press(screen.getByText('All Users'))
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getAllByRole('checkbox')[0])
|
||||
await openAssignDropdown()
|
||||
fireEvent.press(screen.getByText('None'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.updateDeliverySequence')).toEqual({
|
||||
id: 3,
|
||||
deliverySequence: { '7': [] },
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('marks an order packaged from the options menu', async () => {
|
||||
const { fetchMock } = renderScreen({
|
||||
'admin.order.getSlotOrders': { success: true, data: [slotOrder({ isDelivered: true })] },
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
const beforeOrders = procCount(fetchMock, 'admin.order.getSlotOrders')
|
||||
const beforeSequence = procCount(fetchMock, 'admin.slots.getDeliverySequence')
|
||||
await openOrderMenu()
|
||||
await toggleMenuResponder('square-outline')
|
||||
|
||||
await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updatePackaged')).toEqual({
|
||||
orderId: '21',
|
||||
isPackaged: true,
|
||||
}))
|
||||
|
||||
// onSuccess refetches both the slot orders and the delivery sequence.
|
||||
await waitFor(() => {
|
||||
expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(beforeOrders)
|
||||
expect(procCount(fetchMock, 'admin.slots.getDeliverySequence')).toBeGreaterThan(beforeSequence)
|
||||
})
|
||||
})
|
||||
|
||||
it('marks an order delivered from the options menu', async () => {
|
||||
const { fetchMock } = renderScreen({
|
||||
'admin.order.getSlotOrders': { success: true, data: [slotOrder({ isPackaged: true })] },
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
await openOrderMenu()
|
||||
await toggleMenuResponder('square-outline')
|
||||
|
||||
await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updateDelivered')).toEqual({
|
||||
orderId: '21',
|
||||
isDelivered: true,
|
||||
}))
|
||||
})
|
||||
|
||||
it('saves admin notes from the options menu', async () => {
|
||||
const { fetchMock } = renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
await openOrderMenu()
|
||||
fireEvent.press(screen.getByText('Admin Notes'))
|
||||
|
||||
fireEvent.changeText(
|
||||
await screen.findByPlaceholderText('Enter notes for this order...'),
|
||||
'fragile item'
|
||||
)
|
||||
fireEvent.press(screen.getByText('Save Notes'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.updateNotes')).toEqual({
|
||||
orderId: 21,
|
||||
adminNotes: 'fragile item',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the cancel dialog from the options menu', async () => {
|
||||
renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
await openOrderMenu()
|
||||
fireEvent.press(screen.getByText('Cancel Order'))
|
||||
|
||||
expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to order details from View Details', async () => {
|
||||
renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
await openOrderMenu()
|
||||
fireEvent.press(screen.getByText('View Details'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/order-details/21'
|
||||
)
|
||||
})
|
||||
|
||||
it('switches slots through the slot picker', async () => {
|
||||
renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText(LABEL_3)).toBeVisible())
|
||||
fireEvent.press(screen.getByText(LABEL_3))
|
||||
fireEvent.press(await screen.findByText(LABEL_4))
|
||||
|
||||
expect(routerMock.replace).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=4'
|
||||
)
|
||||
})
|
||||
|
||||
it('opens a Google Maps link for orders with coordinates', async () => {
|
||||
renderScreen({
|
||||
'admin.order.getSlotOrders': {
|
||||
success: true,
|
||||
data: [slotOrder({ latitude: 16.75, longitude: 78.0 })],
|
||||
},
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
const mapIcon = screen
|
||||
.UNSAFE_getAllByType(MaterialIcons)
|
||||
.find((node) => node.props.name === 'map')!
|
||||
fireEvent.press(mapIcon)
|
||||
|
||||
expect(Linking.openURL).toHaveBeenCalledWith('https://www.google.com/maps?q=16.75,78')
|
||||
})
|
||||
|
||||
it('goes back from the header', async () => {
|
||||
renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
fireEvent.press(screen.getByLabelText('Go back'))
|
||||
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refetches orders and sequence after saving a reordered sequence', async () => {
|
||||
const { fetchMock, view } = renderScreen({
|
||||
'admin.order.getSlotOrders': {
|
||||
success: true,
|
||||
data: [slotOrder({ id: 21, readableId: 21 }), slotOrder({ id: 22, readableId: 22 })],
|
||||
},
|
||||
'admin.slots.getDeliverySequence': { deliverySequence: { '7': [21, 22] } },
|
||||
})
|
||||
|
||||
// A real user must be selected: handleDragEnd/handleSaveSequence no-op for
|
||||
// the Unassigned (-1) view.
|
||||
await openUserDropdown()
|
||||
fireEvent.press(screen.getByText('Ravi'))
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
|
||||
const beforeOrders = procCount(fetchMock, 'admin.order.getSlotOrders')
|
||||
const beforeSequence = procCount(fetchMock, 'admin.slots.getDeliverySequence')
|
||||
|
||||
// The mocked list renders its data but never drags by itself.
|
||||
const list = view.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
|
||||
})
|
||||
|
||||
fireEvent.press(await screen.findByLabelText('Save sequence'))
|
||||
|
||||
// handleSaveSequence's onSuccess refetches both the slot orders and the
|
||||
// delivery sequence.
|
||||
await waitFor(() => {
|
||||
expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(beforeOrders)
|
||||
expect(procCount(fetchMock, 'admin.slots.getDeliverySequence')).toBeGreaterThan(beforeSequence)
|
||||
})
|
||||
})
|
||||
|
||||
it('refetches on mark-data-fetchers', async () => {
|
||||
const { fetchMock } = renderScreen()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#21')).toBeVisible())
|
||||
const before = procCount(fetchMock, 'admin.order.getSlotOrders')
|
||||
|
||||
refreshHooks.markDataFetchers?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.order.getSlotOrders')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,191 +0,0 @@
|
|||
/**
|
||||
* Drawer layout (app/(drawer)/_layout.tsx) — auth gate, the custom drawer
|
||||
* content (staff name, nav items, logout) and the header buttons.
|
||||
*
|
||||
* expo-router/drawer and @react-navigation/drawer are stubbed so the custom
|
||||
* drawer content and the screenOptions header callbacks are reachable.
|
||||
*/
|
||||
|
||||
const mockRedirects: string[] = []
|
||||
|
||||
jest.mock('expo-router', () => {
|
||||
const React = require('react')
|
||||
const { Text } = require('react-native')
|
||||
const base = require('../mocks/router').expoRouterMock()
|
||||
return {
|
||||
...base,
|
||||
Redirect: ({ href }: { href: string }) => {
|
||||
mockRedirects.push(href)
|
||||
return React.createElement(Text, { testID: 'redirect' }, String(href))
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const mockNavigation = {
|
||||
getState: () => ({ routes: [], index: 0 }),
|
||||
openDrawer: jest.fn(),
|
||||
}
|
||||
|
||||
jest.mock('expo-router/drawer', () => {
|
||||
const React = require('react')
|
||||
const { View } = require('react-native')
|
||||
const Drawer = ({
|
||||
drawerContent: DrawerContent,
|
||||
screenOptions,
|
||||
children,
|
||||
}: {
|
||||
drawerContent?: React.ComponentType
|
||||
screenOptions?: (args: { navigation: unknown }) => Record<string, any>
|
||||
children?: React.ReactNode
|
||||
}) => {
|
||||
const options =
|
||||
typeof screenOptions === 'function'
|
||||
? screenOptions({ navigation: mockNavigation })
|
||||
: {}
|
||||
return React.createElement(
|
||||
View,
|
||||
null,
|
||||
options.headerLeft ? options.headerLeft() : null,
|
||||
options.headerRight ? options.headerRight() : null,
|
||||
DrawerContent ? React.createElement(DrawerContent) : null,
|
||||
children
|
||||
)
|
||||
}
|
||||
Drawer.Screen = () => null
|
||||
return { Drawer }
|
||||
})
|
||||
|
||||
jest.mock('@react-navigation/drawer', () => {
|
||||
const React = require('react')
|
||||
const { View, TouchableOpacity, Text } = require('react-native')
|
||||
return {
|
||||
DrawerContentScrollView: ({ children }: { children?: React.ReactNode }) =>
|
||||
React.createElement(View, null, children),
|
||||
DrawerItem: ({
|
||||
label,
|
||||
onPress,
|
||||
}: {
|
||||
label: string
|
||||
onPress?: () => void
|
||||
}) =>
|
||||
React.createElement(
|
||||
TouchableOpacity,
|
||||
{ onPress, accessibilityLabel: label },
|
||||
React.createElement(Text, null, label)
|
||||
),
|
||||
}
|
||||
})
|
||||
|
||||
import React from 'react'
|
||||
import { ActivityIndicator, DeviceEventEmitter } from 'react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
|
||||
|
||||
import Layout from '@/app/(drawer)/_layout'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { resetStaffAuthMock, staffAuthMock } from '../mocks/staff-auth'
|
||||
import { resetRouterMock, routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const iconByName = (name: string) =>
|
||||
screen.UNSAFE_getAllByType(MaterialIcons).find((i) => i.props.name === name) as
|
||||
| Parameters<typeof fireEvent.press>[0]
|
||||
| undefined
|
||||
|
||||
describe('Drawer layout', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
staffAuthMock.regionId = 1
|
||||
mockRedirects.length = 0
|
||||
mockNavigation.openDrawer.mockClear()
|
||||
resetRouterMock()
|
||||
await resetStorage()
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.staffUser.me': {
|
||||
id: 1,
|
||||
name: 'shafi',
|
||||
regionId: 1,
|
||||
regionName: 'Hyderabad',
|
||||
},
|
||||
},
|
||||
})
|
||||
jest.spyOn(DeviceEventEmitter, 'emit')
|
||||
})
|
||||
|
||||
it('shows a spinner while the session is loading', () => {
|
||||
staffAuthMock.isLoading = true
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
expect(screen.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
|
||||
expect(screen.queryByText('Logout')).toBeNull()
|
||||
})
|
||||
|
||||
it('redirects to login when logged out', () => {
|
||||
staffAuthMock.isLoggedIn = false
|
||||
staffAuthMock.isLoading = false
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
expect(screen.getByTestId('redirect')).toHaveTextContent('/login')
|
||||
expect(mockRedirects).toEqual(['/login'])
|
||||
})
|
||||
|
||||
it('renders the staff name, region and navigation items', async () => {
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
expect(screen.getByText('shafi')).toBeVisible()
|
||||
await waitFor(() => expect(screen.getByText('Hyderabad')).toBeVisible())
|
||||
expect(screen.getByText('Dashboard')).toBeVisible()
|
||||
expect(screen.getByText('Products')).toBeVisible()
|
||||
expect(screen.getByText('Prices Overview')).toBeVisible()
|
||||
expect(screen.getByText('Product Groupings')).toBeVisible()
|
||||
expect(screen.getByText('Manage Orders')).toBeVisible()
|
||||
expect(screen.getByText('User Management')).toBeVisible()
|
||||
expect(screen.getByText('Send Notifications')).toBeVisible()
|
||||
expect(screen.getByText('Logout')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates from a drawer item', () => {
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
fireEvent.press(screen.getByText('Prices Overview'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/prices-overview'
|
||||
)
|
||||
})
|
||||
|
||||
it('dismisses to the dashboard from the Dashboard item', () => {
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
fireEvent.press(screen.getByText('Dashboard'))
|
||||
|
||||
expect(routerMock.dismissTo).toHaveBeenCalledWith('/(drawer)/dashboard')
|
||||
})
|
||||
|
||||
it('logs out from the Logout item', () => {
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
fireEvent.press(screen.getByText('Logout'))
|
||||
|
||||
expect(staffAuthMock.logout).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('emits the refresh event from the header refresh button', () => {
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
fireEvent.press(iconByName('refresh')!)
|
||||
|
||||
expect(DeviceEventEmitter.emit).toHaveBeenCalledWith(REFRESH_EVENT)
|
||||
})
|
||||
|
||||
it('opens the drawer from the header menu button when there is no back stack', () => {
|
||||
renderWithProviders(<Layout />)
|
||||
|
||||
fireEvent.press(iconByName('menu')!)
|
||||
|
||||
expect(mockNavigation.openDrawer).toHaveBeenCalledTimes(1)
|
||||
expect(routerMock.back).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
/**
|
||||
* Root entry (app/index.tsx) — loading spinner while auth resolves, then a
|
||||
* Redirect to the dashboard or to /login depending on the staff session.
|
||||
*/
|
||||
|
||||
const mockRedirects: string[] = []
|
||||
|
||||
jest.mock('expo-router', () => {
|
||||
const React = require('react')
|
||||
const { Text } = require('react-native')
|
||||
const base = require('../mocks/router').expoRouterMock()
|
||||
return {
|
||||
...base,
|
||||
Redirect: ({ href }: { href: string }) => {
|
||||
mockRedirects.push(href)
|
||||
return React.createElement(Text, { testID: 'redirect' }, String(href))
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
import React from 'react'
|
||||
import { ActivityIndicator } from 'react-native'
|
||||
import { screen } from '@testing-library/react-native'
|
||||
|
||||
import Index from '@/app/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { resetStaffAuthMock, staffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
describe('Root index redirect', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
mockRedirects.length = 0
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
})
|
||||
|
||||
it('shows a spinner while the session is loading', () => {
|
||||
staffAuthMock.isLoading = true
|
||||
renderWithProviders(<Index />)
|
||||
|
||||
expect(screen.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
|
||||
expect(screen.queryByTestId('redirect')).toBeNull()
|
||||
})
|
||||
|
||||
it('redirects to the dashboard when logged in', () => {
|
||||
staffAuthMock.isLoggedIn = true
|
||||
staffAuthMock.isLoading = false
|
||||
renderWithProviders(<Index />)
|
||||
|
||||
expect(screen.getByTestId('redirect')).toHaveTextContent(
|
||||
'/(drawer)/dashboard'
|
||||
)
|
||||
expect(mockRedirects).toEqual(['/(drawer)/dashboard'])
|
||||
})
|
||||
|
||||
it('redirects to login when logged out', () => {
|
||||
staffAuthMock.isLoggedIn = false
|
||||
staffAuthMock.isLoading = false
|
||||
renderWithProviders(<Index />)
|
||||
|
||||
expect(screen.getByTestId('redirect')).toHaveTextContent('/login')
|
||||
expect(mockRedirects).toEqual(['/login'])
|
||||
})
|
||||
})
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
/**
|
||||
* Admin login screen (app/login.tsx) — validation and the staff-auth login call.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import LoginScreen from '@/app/login'
|
||||
import { setupApiMocks } from '../mocks/api'
|
||||
import { resetStaffAuthMock, staffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
describe('Admin login', () => {
|
||||
beforeEach(() => {
|
||||
resetStaffAuthMock()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the login form', () => {
|
||||
renderWithProviders(<LoginScreen />)
|
||||
|
||||
expect(screen.getByText('Admin Login')).toBeVisible()
|
||||
expect(screen.getByTestId('login-name-input')).toBeVisible()
|
||||
expect(screen.getByTestId('login-password-input')).toBeVisible()
|
||||
expect(screen.getByTestId('login-button')).toBeVisible()
|
||||
})
|
||||
|
||||
it('rejects an empty name or password without calling login', () => {
|
||||
renderWithProviders(<LoginScreen />)
|
||||
|
||||
fireEvent.press(screen.getByTestId('login-button'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter both name and password')
|
||||
expect(staffAuthMock.login).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('trims the credentials and calls login', async () => {
|
||||
renderWithProviders(<LoginScreen />)
|
||||
|
||||
fireEvent.changeText(screen.getByTestId('login-name-input'), ' shafi ')
|
||||
fireEvent.changeText(screen.getByTestId('login-password-input'), 'secret')
|
||||
fireEvent.press(screen.getByTestId('login-button'))
|
||||
|
||||
await waitFor(() => expect(staffAuthMock.login).toHaveBeenCalledWith('shafi', 'secret'))
|
||||
})
|
||||
|
||||
it('shows the login error from the context', () => {
|
||||
staffAuthMock.loginError = 'Invalid credentials'
|
||||
renderWithProviders(<LoginScreen />)
|
||||
|
||||
expect(screen.getByText('Invalid credentials')).toBeVisible()
|
||||
})
|
||||
|
||||
it('disables the button while logging in', () => {
|
||||
staffAuthMock.isLoggingIn = true
|
||||
renderWithProviders(<LoginScreen />)
|
||||
|
||||
expect(screen.getByText('Logging in...')).toBeVisible()
|
||||
expect(screen.getByTestId('login-button')).toBeDisabled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
/**
|
||||
* Manage Orders hub (app/(drawer)/dashboard/manage-orders/index.tsx) — slot
|
||||
* picker plus navigation into Orders / Delivery Sequences.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
import ManageOrders from '@/app/(drawer)/dashboard/manage-orders'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { procCount } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const SLOT = { id: 3, deliveryTime: '2026-01-01T10:00:00.000Z' }
|
||||
const SLOT_LABEL = dayjs(SLOT.deliveryTime).format('ddd DD MMM, h:mm a')
|
||||
|
||||
const slotsResult = { slots: [SLOT], count: 1 }
|
||||
|
||||
describe('Manage Orders hub', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
resetRefreshHooks()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures: { 'admin.slots.getAll': slotsResult } })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the slot picker and both menu tiles', async () => {
|
||||
renderWithProviders(<ManageOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Delivery Sequences')).toBeVisible())
|
||||
expect(screen.getByText('Orders')).toBeVisible()
|
||||
expect(screen.getByText('Select Slot')).toBeVisible()
|
||||
})
|
||||
|
||||
it('loads the slot options into the dropdown', async () => {
|
||||
renderWithProviders(<ManageOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Select Slot'))
|
||||
|
||||
expect(await screen.findByText('⚡ Flash Deliveries')).toBeVisible()
|
||||
expect(await screen.findByText(SLOT_LABEL)).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to Orders without a filter when no slot is selected', async () => {
|
||||
renderWithProviders(<ManageOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Orders')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Orders'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/orders'
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to Orders with filter=flash after picking flash deliveries', async () => {
|
||||
renderWithProviders(<ManageOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Select Slot'))
|
||||
fireEvent.press(await screen.findByText('⚡ Flash Deliveries'))
|
||||
|
||||
fireEvent.press(screen.getByText('Orders'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/orders?filter=flash'
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to Delivery Sequences for the selected slot', async () => {
|
||||
renderWithProviders(<ManageOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Select Slot'))
|
||||
fireEvent.press(await screen.findByText(SLOT_LABEL))
|
||||
|
||||
fireEvent.press(screen.getByText('Delivery Sequences'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=3'
|
||||
)
|
||||
})
|
||||
|
||||
it('warns that flash deliveries have no delivery sequences', async () => {
|
||||
renderWithProviders(<ManageOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Select Slot')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Select Slot'))
|
||||
fireEvent.press(await screen.findByText('⚡ Flash Deliveries'))
|
||||
|
||||
fireEvent.press(screen.getByText('Delivery Sequences'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Flash Deliveries',
|
||||
'Flash deliveries do not have delivery sequences. Use the Orders menu to manage flash deliveries.'
|
||||
)
|
||||
expect(routerMock.push).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refetches slots when mark-data-fetchers fires', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.slots.getAll': slotsResult },
|
||||
})
|
||||
|
||||
renderWithProviders(<ManageOrders />)
|
||||
await waitFor(() => expect(screen.getByText('Orders')).toBeVisible())
|
||||
|
||||
expect(typeof refreshHooks.markDataFetchers).toBe('function')
|
||||
act(() => {
|
||||
refreshHooks.markDataFetchers?.()
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.slots.getAll')).toBeGreaterThanOrEqual(2)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,337 +0,0 @@
|
|||
/**
|
||||
* Orders list (app/(drawer)/dashboard/manage-orders/orders/index.tsx) — rows,
|
||||
* loading/empty/error, delivered toggle, item packaging, admin notes, filters,
|
||||
* pagination and navigation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, FlatList } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import Entypo from '@expo/vector-icons/Entypo'
|
||||
|
||||
import Orders from '@/app/(drawer)/dashboard/manage-orders/orders'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const makeOrder = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 11,
|
||||
orderId: '11',
|
||||
readableId: 11,
|
||||
customerName: 'Alice',
|
||||
customerMobile: '9999999999',
|
||||
address: '12 Main St, City, State - 500001, Phone: 9876543210',
|
||||
addressId: 3,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
totalAmount: 500,
|
||||
deliveryCharge: 20,
|
||||
items: [
|
||||
{
|
||||
id: 101,
|
||||
name: 'Chicken',
|
||||
quantity: 2,
|
||||
price: 100,
|
||||
amount: 200,
|
||||
unit: 'kg',
|
||||
skuName: 'Chicken',
|
||||
features: [],
|
||||
productSize: 1,
|
||||
isPackaged: false,
|
||||
isPackageVerified: false,
|
||||
},
|
||||
],
|
||||
createdAt: '2026-01-01T10:00:00.000Z',
|
||||
deliveryTime: null,
|
||||
status: 'pending',
|
||||
isPackaged: false,
|
||||
isDelivered: false,
|
||||
isFlashDelivery: false,
|
||||
userNotes: null,
|
||||
adminNotes: 'call before delivery',
|
||||
userNegativityScore: 0,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const mutateProcedures = {
|
||||
'admin.order.updateDelivered': { success: true, userId: 1 },
|
||||
'admin.order.updatePackaged': { success: true, userId: 1 },
|
||||
'admin.order.updateOrderItemPackaging': { success: true, updated: true },
|
||||
'admin.order.updateNotes': { id: 11 },
|
||||
'admin.order.cancelOrder': { success: true, message: 'cancelled' },
|
||||
}
|
||||
|
||||
const renderOrders = (procedures: Record<string, unknown> = {}) => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': { slots: [], count: 0 },
|
||||
'admin.order.getAll': { orders: [makeOrder()], nextCursor: null },
|
||||
...procedures,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Orders />)
|
||||
return { fetchMock }
|
||||
}
|
||||
|
||||
// Checkboxes render in tree order: row [Packaged, Delivered] then the filter
|
||||
// dialog rows [Packaged, Not Packaged, Delivered, Not Delivered, Cancelled,
|
||||
// Not Cancelled, ⚡ 1 Hr, Regular].
|
||||
const checkboxAt = (index: number) => screen.getAllByRole('checkbox')[index]
|
||||
|
||||
const openFilter = () => {
|
||||
const icon = screen
|
||||
.UNSAFE_getAllByType(MaterialIcons)
|
||||
.find((node) => node.props.name === 'filter-list')!
|
||||
fireEvent.press(icon)
|
||||
}
|
||||
|
||||
const FILTER_INDEX = {
|
||||
packaged: 2,
|
||||
notPackaged: 3,
|
||||
delivered: 4,
|
||||
notDelivered: 5,
|
||||
cancelled: 6,
|
||||
notCancelled: 7,
|
||||
flash: 8,
|
||||
regular: 9,
|
||||
} as const
|
||||
|
||||
describe('Orders list', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = {}
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows a loading indicator while the list is pending', () => {
|
||||
renderOrders()
|
||||
|
||||
expect(screen.getByText('Loading orders...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders a populated row', async () => {
|
||||
renderOrders()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
expect(screen.getByText('#11')).toBeVisible()
|
||||
expect(screen.getByText('1 item')).toBeVisible()
|
||||
expect(screen.getByText('₹500')).toBeVisible()
|
||||
expect(screen.getByText('₹20')).toBeVisible()
|
||||
expect(screen.getByText('Admin Notes')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders an empty list when there are no orders', async () => {
|
||||
renderOrders({ 'admin.order.getAll': { orders: [], nextCursor: null } })
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('Loading orders...')).toBeNull())
|
||||
expect(screen.queryByText('Alice')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders flash and cancelled order badges', async () => {
|
||||
renderOrders({
|
||||
'admin.order.getAll': {
|
||||
orders: [
|
||||
makeOrder({ isFlashDelivery: true, status: 'cancelled', readableId: 42, id: 42, orderId: '42' }),
|
||||
],
|
||||
nextCursor: null,
|
||||
},
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('FLASH')).toBeVisible())
|
||||
expect(screen.getByText('CANCELLED')).toBeVisible()
|
||||
})
|
||||
|
||||
it('marks an order delivered from the row checkbox', async () => {
|
||||
const { fetchMock } = renderOrders(mutateProcedures)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
fireEvent.press(checkboxAt(1))
|
||||
|
||||
await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.order.updateDelivered')).toEqual({
|
||||
orderId: '11',
|
||||
isDelivered: true,
|
||||
}))
|
||||
})
|
||||
|
||||
it('does not toggle packaged from the (inert) inline row checkbox', async () => {
|
||||
const { fetchMock } = renderOrders(mutateProcedures)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
fireEvent.press(checkboxAt(0))
|
||||
|
||||
expect(procCount(fetchMock, 'admin.order.updatePackaged')).toBe(0)
|
||||
})
|
||||
|
||||
it('updates per-item packaging from the items dialog', async () => {
|
||||
const { fetchMock } = renderOrders(mutateProcedures)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('1 item'))
|
||||
fireEvent.press(checkboxAt(2))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
|
||||
orderItemId: 101,
|
||||
isPackaged: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('applies the packaged filter to the query input', async () => {
|
||||
const { fetchMock } = renderOrders(mutateProcedures)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
openFilter()
|
||||
fireEvent.press(checkboxAt(FILTER_INDEX.packaged))
|
||||
|
||||
await waitFor(() => {
|
||||
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
|
||||
expect(input.packagedFilter).toBe('packaged')
|
||||
})
|
||||
})
|
||||
|
||||
it('applies the delivered and cancellation filters', async () => {
|
||||
const { fetchMock } = renderOrders(mutateProcedures)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
openFilter()
|
||||
fireEvent.press(checkboxAt(FILTER_INDEX.delivered))
|
||||
|
||||
await waitFor(() => {
|
||||
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
|
||||
expect(input.deliveredFilter).toBe('delivered')
|
||||
})
|
||||
})
|
||||
|
||||
it('applies the flash delivery type filter', async () => {
|
||||
const { fetchMock } = renderOrders(mutateProcedures)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
openFilter()
|
||||
fireEvent.press(checkboxAt(FILTER_INDEX.flash))
|
||||
|
||||
await waitFor(() => {
|
||||
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
|
||||
expect(input.flashDeliveryFilter).toBe('flash')
|
||||
})
|
||||
})
|
||||
|
||||
it('saves admin notes through the notes dialog', async () => {
|
||||
const { fetchMock } = renderOrders(mutateProcedures)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Admin Notes'))
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter admin notes...'),
|
||||
'leave at gate'
|
||||
)
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.updateNotes')).toEqual({
|
||||
orderId: 11,
|
||||
adminNotes: 'leave at gate',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the user notes dialog', async () => {
|
||||
renderOrders({
|
||||
'admin.order.getAll': {
|
||||
orders: [makeOrder({ userNotes: 'ring the bell' })],
|
||||
nextCursor: null,
|
||||
},
|
||||
})
|
||||
await waitFor(() => expect(screen.getByText('User Notes')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('User Notes'))
|
||||
|
||||
expect(await screen.findByText('ring the bell')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to order details when a row is pressed', async () => {
|
||||
renderOrders()
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Alice'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/order-details/11'
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the options menu and navigates via View Details', async () => {
|
||||
renderOrders()
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
const dots = screen.UNSAFE_getAllByType(Entypo)[0]
|
||||
fireEvent.press(dots)
|
||||
|
||||
expect(await screen.findByText('Select an action to perform')).toBeVisible()
|
||||
fireEvent.press(screen.getByText('View Details'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/order-details/11'
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the cancel dialog from the options menu', async () => {
|
||||
renderOrders()
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.UNSAFE_getAllByType(Entypo)[0])
|
||||
fireEvent.press(await screen.findByText('Cancel Order'))
|
||||
|
||||
expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('loads the next page when the list end is reached', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': { slots: [], count: 0 },
|
||||
'admin.order.getAll': (input: unknown) => {
|
||||
const cursor = (input as { cursor?: number } | undefined)?.cursor
|
||||
if (cursor) {
|
||||
return {
|
||||
orders: [makeOrder({ id: 5, orderId: '5', readableId: 5, customerName: 'Fish Order' })],
|
||||
nextCursor: null,
|
||||
}
|
||||
}
|
||||
return { orders: [makeOrder()], nextCursor: 5 }
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
renderWithProviders(<Orders />)
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeVisible())
|
||||
|
||||
fireEvent(screen.UNSAFE_getByType(FlatList), 'endReached')
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Fish Order')).toBeVisible())
|
||||
const input = lastProcedureInput(fetchMock, 'admin.order.getAll') as Record<string, unknown>
|
||||
expect(input.cursor).toBe(5)
|
||||
})
|
||||
|
||||
it('falls back to an empty list when the query fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': { slots: [], count: 0 },
|
||||
'admin.order.getAll': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
renderWithProviders(<Orders />)
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('Loading orders...')).toBeNull())
|
||||
expect(screen.queryByText('Alice')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,235 +0,0 @@
|
|||
/**
|
||||
* Order details (app/(drawer)/dashboard/manage-orders/order-details/[id].tsx) —
|
||||
* detail rendering, packaging toggles, delivery-charge removal, cancellation
|
||||
* and navigation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import OrderDetails from '@/app/(drawer)/dashboard/manage-orders/order-details/[id]'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const makeDetails = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 11,
|
||||
readableId: 11,
|
||||
userId: 5,
|
||||
customerName: 'Alice',
|
||||
customerEmail: 'alice@example.com',
|
||||
customerMobile: '9999999999',
|
||||
address: {
|
||||
name: 'Alice',
|
||||
line1: '12 Main St',
|
||||
line2: null,
|
||||
city: 'City',
|
||||
state: 'State',
|
||||
phone: '9876543210',
|
||||
},
|
||||
slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null },
|
||||
totalAmount: 500,
|
||||
deliveryCharge: 20,
|
||||
adminNotes: 'handle with care',
|
||||
userNotes: null,
|
||||
createdAt: '2026-01-01T10:00:00.000Z',
|
||||
status: 'pending',
|
||||
isPackaged: false,
|
||||
isDelivered: false,
|
||||
items: [
|
||||
{
|
||||
id: 101,
|
||||
name: 'Chicken',
|
||||
amount: 200,
|
||||
isPackaged: false,
|
||||
isPackageVerified: false,
|
||||
quantity: '2',
|
||||
price: '100',
|
||||
productSize: 1,
|
||||
unit: 'kg',
|
||||
},
|
||||
],
|
||||
cancelReason: null,
|
||||
cancellationReviewed: false,
|
||||
couponData: null,
|
||||
couponCode: null,
|
||||
couponDescription: null,
|
||||
discountAmount: 0,
|
||||
orderStatus: null,
|
||||
isFlashDelivery: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const procedures = (overrides: Record<string, unknown> = {}) => ({
|
||||
'admin.order.getOrderDetails': makeDetails(),
|
||||
'admin.order.updateOrderItemPackaging': { success: true, updated: true },
|
||||
'admin.order.removeDeliveryCharge': { message: 'removed' },
|
||||
'admin.order.cancelOrder': { success: true, message: 'cancelled' },
|
||||
'admin.user.getUserIncidents': { incidents: [] },
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderDetails = (overrides: Record<string, unknown> = {}) => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: procedures(overrides) })
|
||||
renderWithProviders(<OrderDetails />)
|
||||
return { fetchMock }
|
||||
}
|
||||
|
||||
describe('Order details', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = { id: '11' }
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows a loading message while the order is pending', () => {
|
||||
renderDetails()
|
||||
|
||||
expect(screen.getByText('Loading order details...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('queries the order with the route id', async () => {
|
||||
const { fetchMock } = renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#11')).toBeVisible())
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.getOrderDetails')).toEqual({ orderId: 11 })
|
||||
})
|
||||
|
||||
it('renders the order, customer, items and totals', async () => {
|
||||
renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#11')).toBeVisible())
|
||||
expect(screen.getByText('Alice')).toBeVisible()
|
||||
expect(screen.getByText('9999999999')).toBeVisible()
|
||||
expect(screen.getByText('Chicken')).toBeVisible()
|
||||
expect(screen.getByText('Subtotal (1 items)')).toBeVisible()
|
||||
expect(screen.getByText('handle with care')).toBeVisible()
|
||||
expect(screen.getByText('Manage Orders')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders an error state with a back action when the order is missing', async () => {
|
||||
renderDetails({ 'admin.order.getOrderDetails': null })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Oops!')).toBeVisible())
|
||||
expect(screen.getByText('Failed to load order details')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('Go Back'))
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('toggles item packaged state', async () => {
|
||||
const { fetchMock } = renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
fireEvent.press(screen.getAllByText('Packaged').pop()!)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
|
||||
orderItemId: 101,
|
||||
isPackaged: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('toggles item verified state', async () => {
|
||||
const { fetchMock } = renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Pkg Verified'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.updateOrderItemPackaging')).toEqual({
|
||||
orderItemId: 101,
|
||||
isPackageVerified: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('removes the delivery charge after confirmation', async () => {
|
||||
const { fetchMock } = renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Remove')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Remove'))
|
||||
|
||||
const call = (Alert.alert as jest.Mock).mock.calls.find((c) => c[0] === 'Remove Delivery Cost')
|
||||
expect(call).toBeTruthy()
|
||||
const buttons = call![2] as { text: string; onPress?: () => void }[]
|
||||
|
||||
await act(async () => {
|
||||
buttons.find((b) => b.text === 'Remove')!.onPress?.()
|
||||
})
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.order.removeDeliveryCharge'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.removeDeliveryCharge')).toEqual({ orderId: 11 })
|
||||
})
|
||||
|
||||
it('opens the cancel order dialog', async () => {
|
||||
renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Cancel Order')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Cancel Order'))
|
||||
|
||||
expect(await screen.findByPlaceholderText('Enter reason for cancellation...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the cancellation reason and hides the cancel button when cancelled', async () => {
|
||||
renderDetails({
|
||||
'admin.order.getOrderDetails': makeDetails({
|
||||
status: 'cancelled',
|
||||
cancelReason: 'Customer requested',
|
||||
}),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Cancellation Reason')).toBeVisible())
|
||||
expect(screen.getByText('Customer requested')).toBeVisible()
|
||||
expect(screen.queryByText('Cancel Order')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders the flash delivery notice', async () => {
|
||||
renderDetails({
|
||||
'admin.order.getOrderDetails': makeDetails({ isFlashDelivery: true }),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('1 Hr Delivery Order')).toBeVisible())
|
||||
expect(screen.getByText(/high-priority flash delivery order/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the applied coupon block', async () => {
|
||||
renderDetails({
|
||||
'admin.order.getOrderDetails': makeDetails({
|
||||
couponCode: 'SAVE50',
|
||||
couponDescription: 'Flat ₹50 off',
|
||||
discountAmount: 50,
|
||||
}),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Coupon Applied')).toBeVisible())
|
||||
expect(screen.getByText('SAVE50')).toBeVisible()
|
||||
expect(screen.getAllByText('-₹50').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('navigates to user management from customer details', async () => {
|
||||
renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Customer Details')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Customer Details'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
|
||||
})
|
||||
|
||||
it('navigates back to Manage Orders from the bottom bar', async () => {
|
||||
renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Manage Orders')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Manage Orders'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
|
||||
})
|
||||
})
|
||||
|
|
@ -1,317 +0,0 @@
|
|||
/**
|
||||
* Prices overview (app/(drawer)/dashboard/prices-overview/index.tsx) — SKU
|
||||
* price grid, store filter, edit-dialog validation, flash toggle, the
|
||||
* updateProductPrices mutation and navigation to rebalance orders.
|
||||
*
|
||||
* NOTE: the screen collects SKUs and sends `skuId: sku.id`. The field was renamed from the misleading
|
||||
* `productId` (product ids and SKU ids overlap, so passing a product id silently repriced another
|
||||
* product's SKU); the backend now takes `skuId` and reports only rows it actually wrote.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { Entypo } from '@expo/vector-icons'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import PricesOverview from '@/app/(drawer)/dashboard/prices-overview/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const chickenSku = {
|
||||
id: 11,
|
||||
productId: 1,
|
||||
name: 'Chicken 1kg',
|
||||
displayName: '1 kg pack',
|
||||
price: '100',
|
||||
marketPrice: '120',
|
||||
flashPrice: '90',
|
||||
isFlashAvailable: false,
|
||||
images: ['https://cdn.freshyo.in/chicken.jpg'],
|
||||
features: [{ featureValue: '1kg' }],
|
||||
}
|
||||
|
||||
const muttonSku = {
|
||||
id: 22,
|
||||
productId: 2,
|
||||
name: 'Mutton 1kg',
|
||||
displayName: '1 kg pack',
|
||||
price: '200',
|
||||
marketPrice: null,
|
||||
flashPrice: null,
|
||||
isFlashAvailable: false,
|
||||
images: [],
|
||||
features: [],
|
||||
}
|
||||
|
||||
const product = (id: number, name: string, storeId: number, skus: unknown[]) => ({
|
||||
id,
|
||||
name,
|
||||
shortDescription: null,
|
||||
longDescription: null,
|
||||
storeId,
|
||||
incrementStep: 1,
|
||||
productType: 'item',
|
||||
store: null,
|
||||
skus,
|
||||
})
|
||||
|
||||
const productsResponse = {
|
||||
products: [
|
||||
product(1, 'Chicken', 1, [chickenSku]),
|
||||
product(2, 'Mutton', 2, [muttonSku]),
|
||||
],
|
||||
count: 2,
|
||||
}
|
||||
|
||||
const storesResponse = {
|
||||
stores: [
|
||||
{ id: 1, name: 'Main Store' },
|
||||
{ id: 2, name: 'Other Store' },
|
||||
],
|
||||
count: 2,
|
||||
}
|
||||
|
||||
const baseProcedures = {
|
||||
'admin.product.getProducts': productsResponse,
|
||||
'admin.store.getStores': storesResponse,
|
||||
'admin.product.updateProductPrices': {
|
||||
message: 'Updated prices for 1 product(s)',
|
||||
updatedCount: 1,
|
||||
},
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
buttons.find((b) => b.text === label)?.onPress?.()
|
||||
}
|
||||
|
||||
const editIcon = () =>
|
||||
screen.UNSAFE_getAllByType(MaterialIcons).find((i) => i.props.name === 'edit') as
|
||||
| Parameters<typeof fireEvent.press>[0]
|
||||
| undefined
|
||||
|
||||
const openEditDialog = () => {
|
||||
fireEvent.press(editIcon()!)
|
||||
}
|
||||
|
||||
describe('Prices overview', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
routerMock.push.mockClear()
|
||||
setupApiMocks({ procedures: baseProcedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows a loading state while products or stores are pending', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProducts': () => new Promise(() => {}),
|
||||
'admin.store.getStores': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PricesOverview />)
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the SKU price grid', async () => {
|
||||
renderWithProviders(<PricesOverview />)
|
||||
|
||||
expect(await screen.findByText('Chicken')).toBeVisible()
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
expect(screen.getByText('₹100')).toBeVisible()
|
||||
expect(screen.getByText('₹120')).toBeVisible()
|
||||
expect(screen.getByText('₹90')).toBeVisible()
|
||||
expect(screen.getByText('1kg')).toBeVisible()
|
||||
// Mutton has no market/flash price.
|
||||
expect(screen.getAllByText('N/A')).toHaveLength(2)
|
||||
expect(screen.getByText('Save (0)')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders without rows when there are no products', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
...baseProcedures,
|
||||
'admin.product.getProducts': { products: [], count: 0 },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PricesOverview />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Save (0)')).toBeVisible())
|
||||
expect(screen.queryByText('Chicken')).toBeNull()
|
||||
})
|
||||
|
||||
it('filters SKUs by store', async () => {
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
fireEvent.press(screen.getByText('Main Store, Other Store'))
|
||||
fireEvent.press(await screen.findByText('Main Store'))
|
||||
fireEvent.press(screen.getByText('Done'))
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('Chicken')).toBeNull())
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
})
|
||||
|
||||
it('rejects an invalid price in the edit dialog', async () => {
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
openEditDialog()
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '0')
|
||||
fireEvent.press(screen.getByText('Update Price'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter a valid price')
|
||||
expect(screen.getByText('Save (0)')).toBeVisible()
|
||||
})
|
||||
|
||||
it('rejects an invalid market price in the edit dialog', async () => {
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
openEditDialog()
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter market price'), '0')
|
||||
fireEvent.press(screen.getByText('Update Price'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Please enter a valid market price'
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an invalid flash price in the edit dialog', async () => {
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
openEditDialog()
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter flash price'), '0')
|
||||
fireEvent.press(screen.getByText('Update Price'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
'Please enter a valid flash price'
|
||||
)
|
||||
})
|
||||
|
||||
it('saves an edited price through updateProductPrices', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: baseProcedures })
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
openEditDialog()
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
|
||||
fireEvent.press(screen.getByText('Update Price'))
|
||||
expect(screen.getByText('Save (1)')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('Save (1)'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.product.updateProductPrices')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.product.updateProductPrices')).toEqual({
|
||||
updates: [{ skuId: 11, price: 150 }],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Prices updated successfully')
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.product.getProducts')).toBeGreaterThan(1)
|
||||
)
|
||||
})
|
||||
|
||||
it('saves the flash-availability toggle through updateProductPrices', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: baseProcedures })
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
fireEvent.press(screen.getAllByRole('checkbox')[0])
|
||||
expect(screen.getByText('Save (1)')).toBeVisible()
|
||||
fireEvent.press(screen.getByText('Save (1)'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.product.updateProductPrices')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.product.updateProductPrices')).toEqual({
|
||||
updates: [{ skuId: 11, isFlashAvailable: true }],
|
||||
})
|
||||
})
|
||||
|
||||
it('shows an error alert when the update fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
...baseProcedures,
|
||||
'admin.product.updateProductPrices': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
openEditDialog()
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
|
||||
fireEvent.press(screen.getByText('Update Price'))
|
||||
fireEvent.press(screen.getByText('Save (1)'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Error',
|
||||
expect.stringContaining('Failed to update prices')
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('does not submit while no change was made', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: baseProcedures })
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
fireEvent.press(screen.getByText('Save (0)'))
|
||||
|
||||
expect(procCount(fetchMock, 'admin.product.updateProductPrices')).toBe(0)
|
||||
})
|
||||
|
||||
it('navigates to rebalance orders from the options menu', async () => {
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
const dots = screen.UNSAFE_getAllByType(Entypo)[0]
|
||||
fireEvent.press(dots)
|
||||
fireEvent.press(await screen.findByText('Re-Balance Orders'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/rebalance-orders'
|
||||
)
|
||||
})
|
||||
|
||||
it('acknowledges the success alert', async () => {
|
||||
renderWithProviders(<PricesOverview />)
|
||||
await screen.findByText('Chicken')
|
||||
|
||||
openEditDialog()
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter price'), '150')
|
||||
fireEvent.press(screen.getByText('Update Price'))
|
||||
fireEvent.press(screen.getByText('Save (1)'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Prices updated successfully')
|
||||
)
|
||||
pressLastAlertButton('OK')
|
||||
expect(routerMock.push).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
/**
|
||||
* Create product group (app/(drawer)/dashboard/product-groupings/create.tsx) —
|
||||
* renders ProductGroupForm in create mode and wires onClose/onSuccess to
|
||||
* router.back().
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import CreateProductGroup from '@/app/(drawer)/dashboard/product-groupings/create'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { expectProcedureCalled, procCount } from '../mocks/procedures'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const procedures = {
|
||||
'common.product.getAllProductsSummary': { products: [] },
|
||||
'common.product.getAllSkusSummary': {
|
||||
skus: [{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' }],
|
||||
},
|
||||
'admin.product.createGroup': {
|
||||
group: { id: 1, groupName: 'Meat', description: null, createdAt: '2024-01-01' },
|
||||
message: 'Group created successfully',
|
||||
},
|
||||
}
|
||||
|
||||
describe('Create product group', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the create form', () => {
|
||||
renderWithProviders(<CreateProductGroup />)
|
||||
|
||||
expect(screen.getByText('Create Product Group')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter group name')).toBeVisible()
|
||||
expect(screen.getByText('Save')).toBeVisible()
|
||||
})
|
||||
|
||||
it('does not create a group when the name is empty', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
renderWithProviders(<CreateProductGroup />)
|
||||
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
expect(await screen.findByText('Group name is required')).toBeVisible()
|
||||
expect(procCount(fetchMock, 'admin.product.createGroup')).toBe(0)
|
||||
})
|
||||
|
||||
it('creates the group then navigates back', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
renderWithProviders(<CreateProductGroup />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter group name'), 'Meat')
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.createGroup'))
|
||||
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('navigates back when cancelled', () => {
|
||||
renderWithProviders(<CreateProductGroup />)
|
||||
|
||||
fireEvent.press(screen.getByText('Cancel'))
|
||||
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,98 +0,0 @@
|
|||
/**
|
||||
* Edit product group (app/(drawer)/dashboard/product-groupings/edit/[id].tsx) —
|
||||
* loads getGroups, finds the group by the route id, and wires the form to
|
||||
* updateGroup() + router.back().
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import EditProductGroup from '@/app/(drawer)/dashboard/product-groupings/edit/[id]'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
} from '../mocks/procedures'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const group = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 5,
|
||||
groupName: 'Beef Box',
|
||||
description: 'Bundle',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
products: [{ id: 10 }, { id: 11 }],
|
||||
productCount: 2,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const procedures = (groups: unknown[]) => ({
|
||||
'admin.product.getGroups': { groups },
|
||||
'common.product.getAllProductsSummary': { products: [] },
|
||||
'common.product.getAllSkusSummary': {
|
||||
skus: [
|
||||
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
|
||||
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
|
||||
],
|
||||
},
|
||||
'admin.product.updateGroup': {
|
||||
group: { id: 5, groupName: 'Beef Combo', description: 'Bundle', createdAt: '2024-01-01' },
|
||||
message: 'Group updated successfully',
|
||||
},
|
||||
})
|
||||
|
||||
describe('Edit product group', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = { id: '5' }
|
||||
setupApiMocks({ procedures: procedures([group()]) })
|
||||
jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while groups are pending', () => {
|
||||
searchParamsMock.current = { id: '5' }
|
||||
setupApiMocks({
|
||||
procedures: { ...procedures([group()]), 'admin.product.getGroups': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<EditProductGroup />)
|
||||
|
||||
expect(screen.getByText('Loading group...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows a not-found state when the id does not match a group', async () => {
|
||||
searchParamsMock.current = { id: '99' }
|
||||
setupApiMocks({ procedures: procedures([group()]) })
|
||||
renderWithProviders(<EditProductGroup />)
|
||||
|
||||
expect(await screen.findByText('Group not found')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the edit form seeded with the group', async () => {
|
||||
renderWithProviders(<EditProductGroup />)
|
||||
|
||||
expect(await screen.findByText('Edit Product Group')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Beef Box')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Bundle')).toBeVisible()
|
||||
})
|
||||
|
||||
it('updates the group and navigates back', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: procedures([group()]) })
|
||||
renderWithProviders(<EditProductGroup />)
|
||||
await screen.findByDisplayValue('Beef Box')
|
||||
|
||||
fireEvent.changeText(screen.getByDisplayValue('Beef Box'), 'Beef Combo')
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.product.updateGroup'))
|
||||
expect(lastProcedureInput(fetchMock, 'admin.product.updateGroup')).toEqual({
|
||||
id: 5,
|
||||
group_name: 'Beef Combo',
|
||||
description: 'Bundle',
|
||||
product_ids: [10, 11],
|
||||
})
|
||||
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
|
||||
})
|
||||
})
|
||||
|
|
@ -1,201 +0,0 @@
|
|||
/**
|
||||
* Product groupings list (app/(drawer)/dashboard/product-groupings/index.tsx) —
|
||||
* group rows, empty/loading/error states, create/edit navigation, delete via
|
||||
* the confirm alert and the manual-refresh hooks.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import dayjs from 'dayjs'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import ProductGroupings from '@/app/(drawer)/dashboard/product-groupings/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const group = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 1,
|
||||
groupName: 'Meat Box',
|
||||
description: 'Protein bundle',
|
||||
createdAt: '2024-05-01T00:00:00.000Z',
|
||||
products: [{ id: 10 }, { id: 11 }],
|
||||
productCount: 2,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const groupsResponse = (groups: unknown[]) => ({ groups })
|
||||
|
||||
const iconByName = (name: string) =>
|
||||
screen.UNSAFE_getAllByType(MaterialIcons).find((i) => i.props.name === name) as
|
||||
| Parameters<typeof fireEvent.press>[0]
|
||||
| undefined
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('Product groupings list', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
resetRefreshHooks()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures: { 'admin.product.getGroups': groupsResponse([group()]) } })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getGroups': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
|
||||
expect(screen.getByText('Loading product groups...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state when the query fails', async () => {
|
||||
const { fetchMock } = setupApiMocks()
|
||||
fetchMock.mockRejectedValue(new Error('network down'))
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
|
||||
expect(await screen.findByText('Error loading groups')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the empty state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getGroups': groupsResponse([]) },
|
||||
})
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
|
||||
expect(await screen.findByText('No Groups Yet')).toBeVisible()
|
||||
expect(
|
||||
screen.getByText('Start by creating your first product group using the button below.')
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders a group row with description, product count and date', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getGroups': groupsResponse([
|
||||
group(),
|
||||
group({ id: 2, groupName: 'Fish Box', description: null, productCount: 1 }),
|
||||
]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
|
||||
expect(await screen.findByText('Meat Box')).toBeVisible()
|
||||
expect(screen.getByText('Protein bundle')).toBeVisible()
|
||||
expect(screen.getByText('2 Products')).toBeVisible()
|
||||
expect(screen.getByText('Fish Box')).toBeVisible()
|
||||
expect(screen.getByText('1 Products')).toBeVisible()
|
||||
expect(
|
||||
screen.getAllByText(dayjs('2024-05-01T00:00:00.000Z').format('MMM DD, YYYY'))
|
||||
).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('navigates to create from the floating action button', async () => {
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
await screen.findByText('Meat Box')
|
||||
|
||||
fireEvent.press(iconByName('add')!)
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/product-groupings/create'
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to edit for the pressed group', async () => {
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
await screen.findByText('Meat Box')
|
||||
|
||||
fireEvent.press(iconByName('edit')!)
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/product-groupings/edit/1'
|
||||
)
|
||||
})
|
||||
|
||||
it('deletes a group after confirming the alert and refetches', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getGroups': groupsResponse([group()]),
|
||||
'admin.product.deleteGroup': { message: 'Group deleted successfully' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
await screen.findByText('Meat Box')
|
||||
|
||||
fireEvent.press(iconByName('delete')!)
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Delete Group',
|
||||
'Are you sure you want to delete this group?',
|
||||
expect.any(Array)
|
||||
)
|
||||
pressLastAlertButton('Delete')
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.product.deleteGroup')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.product.deleteGroup')).toEqual({
|
||||
id: 1,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.product.getGroups')).toBeGreaterThan(1)
|
||||
)
|
||||
})
|
||||
|
||||
it('does not delete when the alert is cancelled', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getGroups': groupsResponse([group()]),
|
||||
'admin.product.deleteGroup': { message: 'Group deleted successfully' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
await screen.findByText('Meat Box')
|
||||
|
||||
fireEvent.press(iconByName('delete')!)
|
||||
pressLastAlertButton('Cancel')
|
||||
|
||||
expect(procCount(fetchMock, 'admin.product.deleteGroup')).toBe(0)
|
||||
})
|
||||
|
||||
it('refetches through the manual-refresh and mark-data-fetchers hooks', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.product.getGroups': groupsResponse([group()]) },
|
||||
})
|
||||
renderWithProviders(<ProductGroupings />)
|
||||
await screen.findByText('Meat Box')
|
||||
|
||||
const before = procCount(fetchMock, 'admin.product.getGroups')
|
||||
expect(refreshHooks.manualRefresh).toBeTruthy()
|
||||
refreshHooks.manualRefresh?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.product.getGroups')).toBeGreaterThan(before)
|
||||
)
|
||||
|
||||
const afterManual = procCount(fetchMock, 'admin.product.getGroups')
|
||||
expect(refreshHooks.markDataFetchers).toBeTruthy()
|
||||
refreshHooks.markDataFetchers?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.product.getGroups')).toBeGreaterThan(afterManual)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,125 +0,0 @@
|
|||
/**
|
||||
* Add product tag (app/(drawer)/dashboard/product-tags/add.tsx) — creates a tag
|
||||
* (with optional image upload) then navigates back on success.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import AddTag from '@/app/(drawer)/dashboard/product-tags/add'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const storesResponse = {
|
||||
stores: [{ id: 1, name: 'Main Store' }],
|
||||
count: 1,
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('Add product tag', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the create form', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': { skus: [] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AddTag />)
|
||||
|
||||
expect(screen.getByText('Create Tag')).toBeVisible()
|
||||
})
|
||||
|
||||
it('creates the tag with the entered values', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': { skus: [] },
|
||||
'admin.product.createProductTag': {
|
||||
tag: { id: 3, tagName: 'Featured' },
|
||||
message: 'Tag created successfully',
|
||||
},
|
||||
'admin.product.getProductTags': { tags: [], message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AddTag />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter tag name'), 'Featured')
|
||||
fireEvent.press(screen.getByText('Create Tag'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'admin.product.createProductTag')
|
||||
)
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.createProductTag')).toMatchObject({
|
||||
tagName: 'Featured',
|
||||
isDashboardTag: false,
|
||||
relatedStores: [],
|
||||
productIds: [],
|
||||
uploadUrls: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('navigates back after the success alert is acknowledged', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': { skus: [] },
|
||||
'admin.product.createProductTag': {
|
||||
tag: { id: 3, tagName: 'Featured' },
|
||||
message: 'Tag created successfully',
|
||||
},
|
||||
'admin.product.getProductTags': { tags: [], message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AddTag />)
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter tag name'), 'Featured')
|
||||
fireEvent.press(screen.getByText('Create Tag'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Tag created successfully',
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
pressLastAlertButton('OK')
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not create the tag when the name is empty', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': { skus: [] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<AddTag />)
|
||||
|
||||
fireEvent.press(screen.getByText('Create Tag'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.createProductTag')).toBe(0)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,226 +0,0 @@
|
|||
/**
|
||||
* Edit product tag (app/(drawer)/dashboard/product-tags/edit/index.tsx) —
|
||||
* loads the tag by route param, seeds TagForm, and updates it.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import EditTag from '@/app/(drawer)/dashboard/product-tags/edit/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const tag = {
|
||||
id: 7,
|
||||
tagName: 'Bestsellers',
|
||||
tagDescription: 'Top picks',
|
||||
imageUrl: null,
|
||||
isDashboardTag: true,
|
||||
relatedStores: [1],
|
||||
sortOrder: [11, 10],
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
products: [
|
||||
{ productId: 10, tagId: 7, assignedAt: '2024-01-01T00:00:00.000Z', product: {} },
|
||||
{ productId: 11, tagId: 7, assignedAt: '2024-01-01T00:00:00.000Z', product: {} },
|
||||
],
|
||||
productIds: [10, 11],
|
||||
}
|
||||
|
||||
const storesResponse = { stores: [{ id: 1, name: 'Main Store' }], count: 1 }
|
||||
const skusResponse = {
|
||||
skus: [
|
||||
{ id: 1, productId: 10, productName: 'Chicken', label: 'Chicken 1kg' },
|
||||
{ id: 2, productId: 11, productName: 'Mutton', label: 'Mutton 1kg' },
|
||||
],
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('Edit product tag', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
searchParamsMock.current = { tagId: '7' }
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while the tag is fetched', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
expect(screen.getByText('Loading tag...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows "Tag not found" when the query errors', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': () => {
|
||||
throw new Error('404')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Tag not found')).toBeVisible())
|
||||
})
|
||||
|
||||
it('seeds the form from the fetched tag', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': { tag, message: 'ok' },
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
|
||||
expect(screen.getByDisplayValue('Top picks')).toBeVisible()
|
||||
expect(screen.getByText('Update Tag')).toBeVisible()
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductTagById')).toEqual({ id: 7 })
|
||||
})
|
||||
|
||||
it('orders the seeded products by sortOrder', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': { tag, message: 'ok' },
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
// sortOrder [11, 10] puts Mutton (product 11) before Chicken (product 10).
|
||||
await waitFor(() => expect(screen.getByText('Mutton 1kg')).toBeVisible())
|
||||
expect(screen.getByText('Chicken 1kg')).toBeVisible()
|
||||
})
|
||||
|
||||
it('updates the tag with the expected payload', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': { tag, message: 'ok' },
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
|
||||
'admin.product.getProductTags': { tags: [], message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Update Tag'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.updateProductTag'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.updateProductTag')).toMatchObject({
|
||||
id: 7,
|
||||
tagName: 'Bestsellers',
|
||||
isDashboardTag: true,
|
||||
relatedStores: [1],
|
||||
productIds: [11, 10],
|
||||
})
|
||||
})
|
||||
|
||||
it('navigates back after the success alert is acknowledged', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': { tag, message: 'ok' },
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
|
||||
'admin.product.getProductTags': { tags: [], message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Update Tag'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Tag updated successfully',
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
pressLastAlertButton('OK')
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refetches the tag list after a successful update', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': { tag, message: 'ok' },
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
|
||||
'admin.product.getProductTags': { tags: [], message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProductTags')
|
||||
fireEvent.press(screen.getByText('Update Tag'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches the tag by id after a successful update', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': { tag, message: 'ok' },
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.product.updateProductTag': { tag: { id: 7 }, message: 'Tag updated successfully' },
|
||||
'admin.product.getProductTags': { tags: [], message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProductTagById')
|
||||
expect(before).toBeGreaterThan(0)
|
||||
fireEvent.press(screen.getByText('Update Tag'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductTagById')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the updating label while the mutation is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTagById': { tag, message: 'ok' },
|
||||
'admin.store.getStores': storesResponse,
|
||||
'common.product.getAllSkusSummary': skusResponse,
|
||||
'admin.product.updateProductTag': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditTag />)
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Bestsellers')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Update Tag'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Updating...')).toBeVisible())
|
||||
})
|
||||
})
|
||||
|
|
@ -1,141 +0,0 @@
|
|||
/**
|
||||
* Product tags list (app/(drawer)/dashboard/product-tags/index.tsx) — list,
|
||||
* dashboard-tag badge, empty/error states, navigation and delete via TagMenu.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import ProductTags from '@/app/(drawer)/dashboard/product-tags/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { procCount } from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const tag = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 1,
|
||||
tagName: 'Bestsellers',
|
||||
tagDescription: 'Top picks',
|
||||
imageUrl: null,
|
||||
isDashboardTag: true,
|
||||
relatedStores: [],
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const tagsResponse = (tags: unknown[]) => ({ tags, message: 'ok' })
|
||||
|
||||
describe('Product tags list', () => {
|
||||
beforeEach(async () => {
|
||||
resetRefreshHooks()
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while the query is pending', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProductTags': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<ProductTags />)
|
||||
|
||||
expect(screen.getByText('Loading tags...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the tags with the dashboard badge', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTags': tagsResponse([
|
||||
tag(),
|
||||
tag({ id: 2, tagName: 'New', tagDescription: null, isDashboardTag: false }),
|
||||
]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductTags />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
|
||||
expect(screen.getByText('New')).toBeVisible()
|
||||
expect(screen.getByText('Top picks')).toBeVisible()
|
||||
expect(screen.getByText('Dashboard Tag')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the empty state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProductTags': tagsResponse([]) },
|
||||
})
|
||||
renderWithProviders(<ProductTags />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No tags yet')).toBeVisible())
|
||||
})
|
||||
|
||||
it('shows the error state and retries', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductTags': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductTags />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Error')).toBeVisible())
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProductTags')
|
||||
fireEvent.press(screen.getByText('Retry'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to add and order screens', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProductTags': tagsResponse([tag()]) },
|
||||
})
|
||||
renderWithProviders(<ProductTags />)
|
||||
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Add New Tag'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/add')
|
||||
|
||||
fireEvent.press(screen.getByText('Tag Orders'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/order')
|
||||
})
|
||||
|
||||
it('renders a TagMenu per row that opens the tag options', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProductTags': tagsResponse([tag()]) },
|
||||
})
|
||||
const { UNSAFE_getAllByType } = renderWithProviders(<ProductTags />)
|
||||
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
|
||||
|
||||
const TouchableOpacity = require('react-native').TouchableOpacity
|
||||
// One trigger per rendered tag row.
|
||||
expect(UNSAFE_getAllByType(TouchableOpacity).length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('refetches through the manual-refresh and mark-data-fetchers hooks', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'admin.product.getProductTags': tagsResponse([tag()]) },
|
||||
})
|
||||
renderWithProviders(<ProductTags />)
|
||||
await waitFor(() => expect(screen.getByText('Bestsellers')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProductTags')
|
||||
expect(refreshHooks.manualRefresh).toBeTruthy()
|
||||
refreshHooks.manualRefresh?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(before)
|
||||
)
|
||||
|
||||
const afterManual = procCount(api.fetchMock, 'admin.product.getProductTags')
|
||||
expect(refreshHooks.markDataFetchers).toBeTruthy()
|
||||
refreshHooks.markDataFetchers?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductTags')).toBeGreaterThan(afterManual)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,231 +0,0 @@
|
|||
/**
|
||||
* Tag orders (app/(drawer)/dashboard/product-tags/order.tsx) — orders tags by
|
||||
* the `tagsOrder` constant, supports save via updateConstants and shows
|
||||
* loading/empty/error states.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import TagOrders from '@/app/(drawer)/dashboard/product-tags/order'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { createQueryClient, renderWithProviders } from '../helpers/render'
|
||||
|
||||
const tagsResponse = {
|
||||
tags: [
|
||||
{ id: 1, tagName: 'Chicken Tag', tagDescription: null, imageUrl: null, isDashboardTag: false, relatedStores: [], createdAt: '2024-01-01T00:00:00.000Z' },
|
||||
{ id: 2, tagName: 'Mutton Tag', tagDescription: null, imageUrl: null, isDashboardTag: false, relatedStores: [], createdAt: '2024-01-01T00:00:00.000Z' },
|
||||
],
|
||||
message: 'ok',
|
||||
}
|
||||
|
||||
describe('Tag orders', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while constants load', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => new Promise(() => {}),
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<TagOrders />)
|
||||
|
||||
expect(screen.getByText('Loading order...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state when the constants query fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<TagOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
|
||||
})
|
||||
|
||||
it('orders the tags by the tagsOrder constant', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [2, 1] }],
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<TagOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Mutton Tag')).toBeVisible())
|
||||
|
||||
const list = result.UNSAFE_getByType(
|
||||
require('react-native-draggable-flatlist').default
|
||||
)
|
||||
expect(list.props.data.map((t: { id: number }) => t.id)).toEqual([2, 1])
|
||||
expect(screen.getByText(/2 items/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('appends tags missing from the order and accepts comma lists', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: '2' }],
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<TagOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Mutton Tag')).toBeVisible())
|
||||
const list = result.UNSAFE_getByType(
|
||||
require('react-native-draggable-flatlist').default
|
||||
)
|
||||
expect(list.props.data.map((t: { id: number }) => t.id)).toEqual([2, 1])
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no tags', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [] }],
|
||||
'admin.product.getProductTags': { tags: [], message: 'ok' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<TagOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No tags available')).toBeVisible())
|
||||
})
|
||||
|
||||
it('disables Save until the order changes, then saves', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [1, 2] }],
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] },
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<TagOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken Tag')).toBeVisible())
|
||||
|
||||
// Save is disabled before any drag.
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
expect(procCount(api.fetchMock, 'admin.region.updateRegionConstants')).toBe(0)
|
||||
|
||||
// Reorder and save.
|
||||
const list = result.UNSAFE_getByType(
|
||||
require('react-native-draggable-flatlist').default
|
||||
)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
|
||||
})
|
||||
await waitFor(() => expect(screen.getByText('Save')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({
|
||||
constants: [{ key: 'tagsOrder', value: [2, 1] }],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Tag order updated successfully!')
|
||||
)
|
||||
expect(routerMock.back).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refetches the constants after saving', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [1, 2] }],
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['tagsOrder'] },
|
||||
},
|
||||
})
|
||||
const client = createQueryClient()
|
||||
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
|
||||
const result = renderWithProviders(<TagOrders />, { queryClient: client })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken Tag')).toBeVisible())
|
||||
const before = procCount(api.fetchMock, 'admin.region.getRegionConstants')
|
||||
// Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's
|
||||
// request can land in this test's fetchMock.
|
||||
expect(before).toBeGreaterThan(0)
|
||||
|
||||
const list = result.UNSAFE_getByType(
|
||||
require('react-native-draggable-flatlist').default
|
||||
)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
|
||||
})
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.region.getRegionConstants')).toBeGreaterThan(before)
|
||||
)
|
||||
// The refetch is driven by the path-based invalidation, not by updateConstants itself.
|
||||
// Asserting the ARRAY path is the point: the old dotted string matched no query at all.
|
||||
await waitFor(() => expect(invalidateSpy).toHaveBeenCalled())
|
||||
expect(
|
||||
invalidateSpy.mock.calls
|
||||
.map((call) => (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey)
|
||||
.map((key) => (Array.isArray(key) ? key[0] : null))
|
||||
).toContainEqual(['admin', 'const', 'getConstants'])
|
||||
// Same client, same cache: the array path matches the live query, the dotted form matches none.
|
||||
expect(
|
||||
client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length
|
||||
).toBeGreaterThan(0)
|
||||
expect(
|
||||
client.getQueryCache().findAll({ queryKey: ['admin.region.getRegionConstants'] })
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shows the saving label while the update is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': [{ key: 'tagsOrder', value: [1, 2] }],
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
'admin.region.updateRegionConstants': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<TagOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken Tag')).toBeVisible())
|
||||
const list = result.UNSAFE_getByType(
|
||||
require('react-native-draggable-flatlist').default
|
||||
)
|
||||
act(() => {
|
||||
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
|
||||
})
|
||||
|
||||
fireEvent.press(screen.getByText('Save'))
|
||||
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
|
||||
})
|
||||
|
||||
it('goes back from the header and the error state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.region.getRegionConstants': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
'admin.product.getProductTags': tagsResponse,
|
||||
},
|
||||
})
|
||||
renderWithProviders(<TagOrders />)
|
||||
await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Go Back'))
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
/**
|
||||
* Add product (app/(drawer)/dashboard/products/add.tsx) — create-mode screen.
|
||||
*
|
||||
* KNOWN APP BUG (src/components/ProductForm.tsx:80): `variantSignature` calls
|
||||
* `a.featureValue.trim()` unguarded. The create form starts every variant with
|
||||
* an empty `quantity` value, so any keystroke / variant add makes Yup throw
|
||||
* `TypeError: Cannot read properties of undefined (reading 'trim')`,
|
||||
* `validateForm()` never resolves, and the form cannot be submitted. This
|
||||
* screen therefore can only be asserted for render/loading; the submit payload
|
||||
* is covered against ProductForm with valid seeded values (see
|
||||
* tests/components/product-form.test.tsx). See the final report.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen } from '@testing-library/react-native'
|
||||
|
||||
import AddProduct from '@/app/(drawer)/dashboard/products/add'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { procCount } from '../mocks/procedures'
|
||||
import { searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
describe('Add product', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders the create form with a single seeded variant', () => {
|
||||
renderWithProviders(<AddProduct />)
|
||||
|
||||
expect(screen.getByText('Create Product')).toBeVisible()
|
||||
expect(screen.getByTestId('product-name-input')).toBeVisible()
|
||||
expect(screen.getByTestId('variant-0-price')).toBeVisible()
|
||||
expect(screen.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
|
||||
expect(screen.queryByTestId('variant-1-price')).toBeNull()
|
||||
})
|
||||
|
||||
it('starts the form empty', () => {
|
||||
renderWithProviders(<AddProduct />)
|
||||
|
||||
expect(screen.getByTestId('product-name-input').props.value).toBe('')
|
||||
expect(screen.getByTestId('variant-0-price').props.value).toBe('')
|
||||
expect(screen.getByTestId('variant-0-attr-0-value').props.value).toBe('')
|
||||
})
|
||||
|
||||
it('does not call createProduct on mount', () => {
|
||||
const api = setupApiMocks()
|
||||
renderWithProviders(<AddProduct />)
|
||||
|
||||
expect(procCount(api.fetchMock, 'admin.product.createProduct')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,273 +0,0 @@
|
|||
/**
|
||||
* Product detail (app/(drawer)/dashboard/products/detail/[id].tsx) — product
|
||||
* fetch, variants/deals/reviews render, empty reviews, edit/back navigation and
|
||||
* the respondToReview flow.
|
||||
*
|
||||
* HARNESS GAP: tests/mocks/router.ts `expoRouterMock()` (admin-ui) does not
|
||||
* expose a `Stack`/`Tabs` primitive, but this screen renders
|
||||
* `<Stack.Screen options={{ headerShown: false }} />`. Without a stub the render
|
||||
* hangs indefinitely. We spread the harness mock and add a `Stack.Screen`
|
||||
* no-op locally (the harness file itself is untouched). See the final report.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => {
|
||||
const base = require('../mocks/router').expoRouterMock()
|
||||
return {
|
||||
...base,
|
||||
Stack: Object.assign(() => null, { Screen: () => null }),
|
||||
}
|
||||
})
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import ProductDetail from '@/app/(drawer)/dashboard/products/detail/[id]'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const product = {
|
||||
id: 5,
|
||||
name: 'Chicken Breast',
|
||||
shortDescription: 'Boneless',
|
||||
longDescription: 'Farm fresh boneless breast',
|
||||
incrementStep: 1,
|
||||
skus: [
|
||||
{
|
||||
id: 51,
|
||||
price: '215',
|
||||
marketPrice: '220',
|
||||
flashPrice: '199',
|
||||
isFlashAvailable: true,
|
||||
isOutOfStock: false,
|
||||
images: ['https://assets.test/p/1.png'],
|
||||
features: [{ id: 1, featureName: 'quantity', featureValue: '0.5 kg' }],
|
||||
},
|
||||
],
|
||||
deals: [
|
||||
{ quantity: 3, price: 600, validTill: '2099-01-01T00:00:00.000Z' },
|
||||
],
|
||||
}
|
||||
|
||||
const review = {
|
||||
id: 91,
|
||||
userName: 'Asha',
|
||||
ratings: 5,
|
||||
reviewBody: 'Great meat',
|
||||
imageUrls: [],
|
||||
signedImageUrls: [],
|
||||
adminResponse: null,
|
||||
adminResponseImages: [],
|
||||
signedAdminImageUrls: [],
|
||||
}
|
||||
|
||||
const reviewsResponse = (reviews: unknown[]) => ({ reviews, hasMore: false })
|
||||
|
||||
describe('Product detail', () => {
|
||||
beforeEach(async () => {
|
||||
resetRefreshHooks()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = { id: '5' }
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while the product is fetched', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProductById': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows Product Not Found when the query errors', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': () => {
|
||||
throw new Error('404')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Product Not Found')).toBeVisible())
|
||||
})
|
||||
|
||||
it('renders the product, variants, deals and reviews', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.getProductReviews': reviewsResponse([review]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken Breast')).toBeVisible())
|
||||
expect(screen.getByText('Boneless')).toBeVisible()
|
||||
expect(screen.getByText('1 Variant')).toBeVisible()
|
||||
expect(screen.getByText('₹215')).toBeVisible()
|
||||
expect(screen.getByText('₹220')).toBeVisible()
|
||||
expect(screen.getByText('0.5 kg')).toBeVisible()
|
||||
expect(screen.getByText('Special Deals')).toBeVisible()
|
||||
expect(screen.getByText('Buy 3')).toBeVisible()
|
||||
expect(screen.getByText('Great meat')).toBeVisible()
|
||||
expect(screen.getByText('Asha')).toBeVisible()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductById')).toEqual({ id: 5 })
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductReviews')).toMatchObject({
|
||||
productId: 5,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the no-reviews state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.getProductReviews': reviewsResponse([]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No reviews yet')).toBeVisible())
|
||||
})
|
||||
|
||||
it('shows an existing admin response', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.getProductReviews': reviewsResponse([
|
||||
{ ...review, adminResponse: 'Thanks for the feedback!' },
|
||||
]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Admin Response')).toBeVisible())
|
||||
expect(screen.getByText('Thanks for the feedback!')).toBeVisible()
|
||||
expect(screen.queryByText('Reply')).toBeNull()
|
||||
})
|
||||
|
||||
it('navigates to edit and back', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.getProductReviews': reviewsResponse([]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
await waitFor(() => expect(screen.getByText('Chicken Breast')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Edit'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=5')
|
||||
})
|
||||
|
||||
it('goes back from the error state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': () => {
|
||||
throw new Error('404')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
await waitFor(() => expect(screen.getByText('Product Not Found')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Go Back'))
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the reply dialog and submits a review response', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.getProductReviews': reviewsResponse([review]),
|
||||
'admin.product.respondToReview': { success: true, review: { id: 91 } },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
await waitFor(() => expect(screen.getByText('Great meat')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('Reply'))
|
||||
|
||||
// The reply form opens inside a bottom dialog; its placeholder identifies it.
|
||||
const input = await screen.findByPlaceholderText('Write your response here...')
|
||||
fireEvent.changeText(input, 'Thank you!')
|
||||
act(() => {
|
||||
fireEvent.press(screen.getByText('Submit Response'))
|
||||
})
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.respondToReview'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.respondToReview')).toMatchObject({
|
||||
reviewId: 91,
|
||||
adminResponse: 'Thank you!',
|
||||
adminResponseImages: [],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Response submitted')
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches the reviews after a review response is submitted', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.getProductReviews': reviewsResponse([review]),
|
||||
'admin.product.respondToReview': { success: true, review: { id: 91 } },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
|
||||
// The mounted reviews query (fed by `reviewsResponse([review])`) has loaded.
|
||||
await waitFor(() => expect(screen.getByText('Great meat')).toBeVisible())
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProductReviews')
|
||||
|
||||
fireEvent.press(screen.getByText('Reply'))
|
||||
const input = await screen.findByPlaceholderText('Write your response here...')
|
||||
fireEvent.changeText(input, 'Thank you!')
|
||||
|
||||
// Opening the dialog and typing do not refetch the reviews, so any increase
|
||||
// below can only come from the submit handler invalidating the query.
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductReviews')).toBe(before)
|
||||
|
||||
act(() => {
|
||||
fireEvent.press(screen.getByText('Submit Response'))
|
||||
})
|
||||
|
||||
// Submitting invalidates admin.product.getProductReviews, which refetches
|
||||
// the mounted reviews query this screen renders.
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductReviews')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches the product through useMarkDataFetchers', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.getProductReviews': reviewsResponse([]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<ProductDetail />)
|
||||
await waitFor(() => expect(screen.getByText('Chicken Breast')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProductById')
|
||||
expect(refreshHooks.markDataFetchers).toBeTruthy()
|
||||
refreshHooks.markDataFetchers?.()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductById')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,216 +0,0 @@
|
|||
/**
|
||||
* Edit product (app/(drawer)/dashboard/products/edit.tsx) — loads a product by
|
||||
* route id, seeds ProductForm, loads/refetches, validation and the
|
||||
* updateProduct payload.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import EditProduct from '@/app/(drawer)/dashboard/products/edit'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { searchParamsMock } from '../mocks/router'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const product = {
|
||||
id: 7,
|
||||
name: 'Chicken',
|
||||
shortDescription: 'Fresh',
|
||||
longDescription: 'Very fresh',
|
||||
storeId: 1,
|
||||
productType: 'item',
|
||||
incrementStep: 1,
|
||||
skus: [
|
||||
{
|
||||
id: 71,
|
||||
name: null,
|
||||
price: '250',
|
||||
marketPrice: '300',
|
||||
flashPrice: null,
|
||||
isFlashAvailable: false,
|
||||
isOffer: false,
|
||||
isComboOnly: false,
|
||||
isDeleted: false,
|
||||
isSuspended: false,
|
||||
images: ['https://assets.test/p/1.png'],
|
||||
imageKeys: ['product-images/1.png'],
|
||||
features: [{ id: 1, featureName: 'quantity', featureValue: '1 kg' }],
|
||||
comboItems: [],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const updateResponse = { product: { id: 7 }, message: 'Product updated successfully' }
|
||||
const listResponse = { products: [], count: 0 }
|
||||
|
||||
describe('Edit product', () => {
|
||||
beforeEach(async () => {
|
||||
resetRefreshHooks()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = { id: '7' }
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while the product is fetched', () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
expect(screen.getByText('Loading product...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows "Product not found" when the query resolves without a product', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProductById': { product: null } },
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Product not found')).toBeVisible())
|
||||
})
|
||||
|
||||
it('seeds the form from the fetched product', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
|
||||
expect(screen.getByTestId('variant-0-price').props.value).toBe('250')
|
||||
expect(screen.getByTestId('variant-0-attr-0-value').props.value).toBe('1 kg')
|
||||
expect(screen.getByText('Save Changes')).toBeVisible()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductById')).toEqual({ id: 7 })
|
||||
)
|
||||
})
|
||||
|
||||
it('routes the product id from the URL params', async () => {
|
||||
searchParamsMock.current = { id: '42' }
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product: { ...product, id: 42 } },
|
||||
'common.getStoresSummary': { stores: [] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.getProductById')).toEqual({ id: 42 })
|
||||
)
|
||||
})
|
||||
|
||||
it('updates the product with the expected payload', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.updateProduct': updateResponse,
|
||||
'admin.product.getProducts': listResponse,
|
||||
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
|
||||
fireEvent.press(screen.getByTestId('create-product-button'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.updateProduct'))
|
||||
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.updateProduct')).toMatchObject({
|
||||
id: 7,
|
||||
name: 'Chicken',
|
||||
storeId: 1,
|
||||
productType: 'item',
|
||||
skus: [
|
||||
expect.objectContaining({
|
||||
id: 71,
|
||||
price: 250,
|
||||
marketPrice: 300,
|
||||
features: [{ featureName: 'quantity', featureValue: '1 kg' }],
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Product updated successfully!')
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches the product and list after a successful update', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.updateProduct': updateResponse,
|
||||
'admin.product.getProducts': listResponse,
|
||||
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
|
||||
|
||||
const productBefore = procCount(api.fetchMock, 'admin.product.getProductById')
|
||||
const listBefore = procCount(api.fetchMock, 'admin.product.getProducts')
|
||||
|
||||
fireEvent.press(screen.getByTestId('create-product-button'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.product.updateProduct'))
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductById')).toBeGreaterThan(productBefore)
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProducts')).toBeGreaterThan(listBefore)
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches through useManualRefresh', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProductById')
|
||||
expect(refreshHooks.manualRefresh).toBeTruthy()
|
||||
refreshHooks.manualRefresh?.()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProductById')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the saving label while the update is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProductById': { product },
|
||||
'admin.product.updateProduct': () => new Promise(() => {}),
|
||||
'common.getStoresSummary': { stores: [{ id: 1, name: 'Main Store' }] },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<EditProduct />)
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('product-name-input').props.value).toBe('Chicken'))
|
||||
fireEvent.press(screen.getByTestId('create-product-button'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible())
|
||||
})
|
||||
})
|
||||
|
|
@ -1,252 +0,0 @@
|
|||
/**
|
||||
* Products list (app/(drawer)/dashboard/products/index.tsx) — list, search,
|
||||
* stock filters, stock toggle, empty/error states and navigation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import Toast from 'react-native-toast-message'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import Products from '@/app/(drawer)/dashboard/products/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const chicken = {
|
||||
id: 1,
|
||||
name: 'Chicken',
|
||||
shortDescription: 'Fresh farm chicken',
|
||||
skus: [
|
||||
{
|
||||
id: 11,
|
||||
price: '200',
|
||||
images: ['https://assets.test/p/1.png'],
|
||||
isOutOfStock: false,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const mutton = {
|
||||
id: 2,
|
||||
name: 'Mutton',
|
||||
shortDescription: 'Tender goat meat',
|
||||
skus: [
|
||||
{
|
||||
id: 22,
|
||||
price: '500',
|
||||
images: [],
|
||||
isOutOfStock: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const listResponse = (products: unknown[]) => ({ products, count: products.length })
|
||||
|
||||
describe('Products list', () => {
|
||||
beforeEach(async () => {
|
||||
resetRefreshHooks()
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('renders each product with its variant count and stock state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProducts': listResponse([chicken, mutton]) },
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
expect(screen.getAllByText('1 Variants')).toHaveLength(2)
|
||||
// Stock labels: chicken shows In, mutton shows Out (plus the toggle button
|
||||
// label "Out" on the in-stock chicken row).
|
||||
expect(screen.getByText('In')).toBeVisible()
|
||||
expect(screen.getAllByText('Out').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('shows the loading state while the query is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProducts': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
expect(screen.getByText('Loading products...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no products', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProducts': listResponse([]) },
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No products found')).toBeVisible())
|
||||
expect(screen.getByText('Start by adding your first product')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state and refetches on Retry', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProducts': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Error loading products')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProducts')
|
||||
fireEvent.press(screen.getByText('Retry'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProducts')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('filters products by search term', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProducts': listResponse([chicken, mutton]) },
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Search products...'), 'mutton')
|
||||
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
expect(screen.queryByText('Chicken')).toBeNull()
|
||||
})
|
||||
|
||||
it('filters by stock and clears the filters from the empty state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProducts': listResponse([chicken, mutton]) },
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
expect(screen.getByText('All (2)')).toBeVisible()
|
||||
expect(screen.getByText('In Stock (1)')).toBeVisible()
|
||||
expect(screen.getByText('Out of Stock (1)')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('In Stock (1)'))
|
||||
expect(screen.getByText('Chicken')).toBeVisible()
|
||||
expect(screen.queryByText('Mutton')).toBeNull()
|
||||
|
||||
fireEvent.press(screen.getByText('Out of Stock (1)'))
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
expect(screen.queryByText('Chicken')).toBeNull()
|
||||
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Search products...'), 'nothing')
|
||||
expect(screen.getByText('No products match your filters')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('Clear Filters'))
|
||||
expect(screen.getByText('Chicken')).toBeVisible()
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to add, edit and detail', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.product.getProducts': listResponse([chicken, mutton]) },
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByTestId('add-product-button'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/add')
|
||||
|
||||
fireEvent.press(screen.getAllByText('View')[0])
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/detail/1')
|
||||
|
||||
fireEvent.press(screen.getAllByText('Edit')[0])
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=1')
|
||||
})
|
||||
|
||||
it('toggles an in-stock product out of stock and refetches', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProducts': listResponse([mutton]),
|
||||
'admin.product.toggleOutOfStock': {
|
||||
productId: 2,
|
||||
isOutOfStock: false,
|
||||
message: 'Product marked as in stock',
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
// mutton is out of stock, so its toggle button offers "Stock".
|
||||
await waitFor(() => expect(screen.getByText('Mutton')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProducts')
|
||||
fireEvent.press(screen.getByText('Stock'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(api.fetchMock, 'admin.product.toggleOutOfStock')
|
||||
)
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.product.toggleOutOfStock')).toEqual({
|
||||
id: 2,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProducts')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the success toast after toggling stock', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.product.getProducts': listResponse([mutton]),
|
||||
'admin.product.toggleOutOfStock': {
|
||||
productId: 2,
|
||||
isOutOfStock: false,
|
||||
message: 'Product marked as in stock',
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Mutton')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Stock'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Toast.show).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ text1: 'Product marked as in stock' })
|
||||
)
|
||||
)
|
||||
expect(expectProcedureCalled(api.fetchMock, 'admin.product.toggleOutOfStock')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('refetches through the manual-refresh and mark-data-fetchers hooks', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'admin.product.getProducts': listResponse([chicken]) },
|
||||
})
|
||||
renderWithProviders(<Products />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.product.getProducts')
|
||||
|
||||
expect(refreshHooks.manualRefresh).toBeTruthy()
|
||||
refreshHooks.manualRefresh?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProducts')).toBeGreaterThan(before)
|
||||
)
|
||||
|
||||
const afterManual = procCount(api.fetchMock, 'admin.product.getProducts')
|
||||
expect(refreshHooks.markDataFetchers).toBeTruthy()
|
||||
refreshHooks.markDataFetchers?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.product.getProducts')).toBeGreaterThan(afterManual)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,188 +0,0 @@
|
|||
/**
|
||||
* Rebalance orders (app/(drawer)/dashboard/rebalance-orders/index.tsx) —
|
||||
* upcoming-slot list, past-slot filtering, selection, the rebalanceSlots
|
||||
* mutation and the +N-more product dialog.
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import RebalanceOrders from '@/app/(drawer)/dashboard/rebalance-orders/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const futureSlot = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 1,
|
||||
deliveryTime: '2099-01-01T10:00:00.000Z',
|
||||
freezeTime: '2099-01-01T09:00:00.000Z',
|
||||
isActive: true,
|
||||
products: [
|
||||
{ id: 10, name: 'Chicken' },
|
||||
{ id: 11, name: 'Mutton' },
|
||||
{ id: 12, name: 'Fish' },
|
||||
],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const slotsResult = (slots: unknown[]) => ({ slots, count: slots.length })
|
||||
|
||||
describe('Rebalance orders', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while slots are pending', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.slots.getAll': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
|
||||
expect(screen.getByText('Loading slots...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders an upcoming slot row with products and status', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.slots.getAll': slotsResult([futureSlot()]) },
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Slot #1')).toBeVisible())
|
||||
expect(screen.getByText('Active')).toBeVisible()
|
||||
// Only the first two product names are shown.
|
||||
expect(screen.getByText('Chicken, Mutton')).toBeVisible()
|
||||
expect(screen.getByText('+1 more')).toBeVisible()
|
||||
})
|
||||
|
||||
it('marks an inactive slot as Inactive', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': slotsResult([futureSlot({ isActive: false })]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Inactive')).toBeVisible())
|
||||
})
|
||||
|
||||
it('hides slots whose delivery time has already passed', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': slotsResult([
|
||||
futureSlot({ id: 1, deliveryTime: '2099-01-01T10:00:00.000Z' }),
|
||||
futureSlot({ id: 2, deliveryTime: '2000-01-01T10:00:00.000Z' }),
|
||||
]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Slot #1')).toBeVisible())
|
||||
expect(screen.queryByText('Slot #2')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no upcoming slots', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': slotsResult([
|
||||
futureSlot({ deliveryTime: '2000-01-01T10:00:00.000Z' }),
|
||||
]),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
|
||||
expect(
|
||||
await screen.findByText('No upcoming slots available for rebalancing.')
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
it('does not rebalance while nothing is selected', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: { 'admin.slots.getAll': slotsResult([futureSlot()]) },
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
await screen.findByText('Slot #1')
|
||||
|
||||
fireEvent.press(screen.getByTestId('mock-linear-gradient'))
|
||||
|
||||
expect(procCount(fetchMock, 'admin.order.rebalanceSlots')).toBe(0)
|
||||
})
|
||||
|
||||
it('rebalances the selected slots through rebalanceSlots', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': slotsResult([futureSlot(), futureSlot({ id: 2 })]),
|
||||
'admin.order.rebalanceSlots': {
|
||||
message: 'Rebalanced',
|
||||
updatedSlotIds: [1],
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
await screen.findByText('Slot #1')
|
||||
|
||||
fireEvent.press(screen.getByText('Slot #1'))
|
||||
fireEvent.press(screen.getByText('Slot #2'))
|
||||
fireEvent.press(screen.getByTestId('mock-linear-gradient'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Rebalancing...',
|
||||
'Please wait while we rebalance the selected slots.',
|
||||
[{ text: 'OK' }]
|
||||
)
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.order.rebalanceSlots')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.order.rebalanceSlots')).toEqual({
|
||||
slotIds: [1, 2],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Rebalance Complete',
|
||||
'Slots have been rebalanced.'
|
||||
)
|
||||
)
|
||||
// onSuccess refetches the slot list.
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.slots.getAll')).toBeGreaterThan(1)
|
||||
)
|
||||
})
|
||||
|
||||
it('toggles a slot back off when pressed twice', async () => {
|
||||
const { fetchMock } = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getAll': slotsResult([futureSlot()]),
|
||||
'admin.order.rebalanceSlots': { message: 'Rebalanced' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
await screen.findByText('Slot #1')
|
||||
|
||||
fireEvent.press(screen.getByText('Slot #1'))
|
||||
fireEvent.press(screen.getByText('Slot #1'))
|
||||
fireEvent.press(screen.getByTestId('mock-linear-gradient'))
|
||||
|
||||
expect(procCount(fetchMock, 'admin.order.rebalanceSlots')).toBe(0)
|
||||
})
|
||||
|
||||
it('opens the full product list from the +N more link', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.slots.getAll': slotsResult([futureSlot()]) },
|
||||
})
|
||||
renderWithProviders(<RebalanceOrders />)
|
||||
await screen.findByText('+1 more')
|
||||
|
||||
fireEvent.press(screen.getByText('+1 more'))
|
||||
|
||||
expect(await screen.findByText('All Products')).toBeVisible()
|
||||
expect(screen.getByText('Fish')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,255 +0,0 @@
|
|||
/**
|
||||
* Send notifications
|
||||
* (app/(drawer)/dashboard/send-notifications/index.tsx) — eligible-user
|
||||
* dropdown, the send-to-all confirmation and the sendNotification mutation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, TouchableOpacity } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
|
||||
import SendNotifications from '@/app/(drawer)/dashboard/send-notifications/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const usersResponse = {
|
||||
users: [
|
||||
{ id: 1, name: 'Alice', mobile: '9000000001', isEligibleForNotif: true },
|
||||
{ id: 2, name: 'Bob', mobile: '9000000002', isEligibleForNotif: false },
|
||||
],
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
const fillMessage = (title = 'Hello', message = 'World') => {
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter notification title...'), title)
|
||||
fireEvent.changeText(screen.getByPlaceholderText('Enter notification message...'), message)
|
||||
}
|
||||
|
||||
describe('Send notifications', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows the loading state while users load', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getUsersForNotification': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
expect(screen.getByText('Loading users...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders the form and loads eligible users only', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getUsersForNotification': usersResponse },
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
expect(await screen.findByText('Send Notifications')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter notification title...')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter notification message...')).toBeVisible()
|
||||
expect(screen.getByText('All Users')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByText('Select users'))
|
||||
expect(await screen.findByText('9000000001 - Alice')).toBeVisible()
|
||||
expect(screen.queryByText('9000000002 - Bob')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the send button disabled until both fields are filled', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getUsersForNotification': usersResponse },
|
||||
})
|
||||
const result = renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send to All Users')
|
||||
const sendDisabled = () =>
|
||||
result.UNSAFE_getAllByType(TouchableOpacity).at(-1)?.props.disabled
|
||||
expect(sendDisabled()).toBe(true)
|
||||
|
||||
fillMessage()
|
||||
await waitFor(() => expect(sendDisabled()).toBe(false))
|
||||
})
|
||||
|
||||
it('confirms and sends to all users when none are selected', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.user.getUsersForNotification': usersResponse,
|
||||
'admin.user.sendNotification': { success: true, message: 'queued' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send to All Users')
|
||||
fillMessage(' Hello ', ' World ')
|
||||
fireEvent.press(screen.getByText('Send to All Users'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Send to All Users?',
|
||||
expect.any(String),
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
pressLastAlertButton('Send')
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.user.sendNotification'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.user.sendNotification')).toEqual({
|
||||
userIds: [],
|
||||
title: 'Hello',
|
||||
text: 'World',
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Notification sent successfully!')
|
||||
)
|
||||
})
|
||||
|
||||
it('cancels the send-to-all confirmation without mutating', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.user.getUsersForNotification': usersResponse,
|
||||
'admin.user.sendNotification': { success: true, message: 'queued' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send to All Users')
|
||||
fillMessage()
|
||||
fireEvent.press(screen.getByText('Send to All Users'))
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Send to All Users?',
|
||||
expect.any(String),
|
||||
expect.any(Array)
|
||||
)
|
||||
)
|
||||
pressLastAlertButton('Cancel')
|
||||
|
||||
expect(procCount(api.fetchMock, 'admin.user.sendNotification')).toBe(0)
|
||||
})
|
||||
|
||||
it('sends to the selected user without a confirmation', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.user.getUsersForNotification': usersResponse,
|
||||
'admin.user.sendNotification': { success: true, message: 'queued' },
|
||||
},
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send to All Users')
|
||||
fireEvent.press(screen.getByText('Select users'))
|
||||
fireEvent.press(await screen.findByText('9000000001 - Alice'))
|
||||
fireEvent.press(screen.getByText('Done'))
|
||||
|
||||
// Once a user is picked the button switches label.
|
||||
await waitFor(() => expect(screen.getByText('Send Notification')).toBeVisible())
|
||||
fillMessage()
|
||||
fireEvent.press(screen.getByText('Send Notification'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.user.sendNotification'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.user.sendNotification')).toEqual({
|
||||
userIds: [1],
|
||||
title: 'Hello',
|
||||
text: 'World',
|
||||
})
|
||||
})
|
||||
|
||||
it('shows an error alert when the mutation fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.user.getUsersForNotification': usersResponse,
|
||||
'admin.user.sendNotification': () => {
|
||||
throw new Error('nope')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send to All Users')
|
||||
fireEvent.press(screen.getByText('Select users'))
|
||||
fireEvent.press(await screen.findByText('9000000001 - Alice'))
|
||||
fireEvent.press(screen.getByText('Done'))
|
||||
await waitFor(() => expect(screen.getByText('Send Notification')).toBeVisible())
|
||||
|
||||
fillMessage()
|
||||
fireEvent.press(screen.getByText('Send Notification'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String))
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the sending label while the mutation is pending', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.user.getUsersForNotification': usersResponse,
|
||||
'admin.user.sendNotification': () => new Promise(() => {}),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send to All Users')
|
||||
fireEvent.press(screen.getByText('Select users'))
|
||||
fireEvent.press(await screen.findByText('9000000001 - Alice'))
|
||||
fireEvent.press(screen.getByText('Done'))
|
||||
await waitFor(() => expect(screen.getByText('Send Notification')).toBeVisible())
|
||||
|
||||
fillMessage()
|
||||
fireEvent.press(screen.getByText('Send Notification'))
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Sending...')).toBeVisible())
|
||||
})
|
||||
|
||||
it('refetches users with the debounced search query', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'admin.user.getUsersForNotification': usersResponse },
|
||||
})
|
||||
renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send to All Users')
|
||||
fireEvent.press(screen.getByText('Select users'))
|
||||
fireEvent.changeText(screen.getByTestId('undefined-search'), 'ali')
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(2000)
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.user.getUsersForNotification')).toEqual({
|
||||
search: 'ali',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('goes back from the header', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getUsersForNotification': usersResponse },
|
||||
})
|
||||
const result = renderWithProviders(<SendNotifications />)
|
||||
|
||||
await screen.findByText('Send Notifications')
|
||||
const backIcon = result.UNSAFE_getAllByType(MaterialIcons).find(
|
||||
(node) => node.props.name === 'chevron-left'
|
||||
)!
|
||||
fireEvent.press(backIcon)
|
||||
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,154 +0,0 @@
|
|||
/**
|
||||
* Slot details screen (app/(drawer)/dashboard/slots/slot-details.tsx) —
|
||||
* loading/error states, snippet + product rendering, share and navigation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, Share } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import SlotDetails from '@/app/(drawer)/dashboard/slots/slot-details'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const slot = {
|
||||
id: 7,
|
||||
deliveryTime: '2026-10-01T10:00:00.000Z',
|
||||
freezeTime: '2026-10-01T06:00:00.000Z',
|
||||
isActive: true,
|
||||
isCapacityFull: false,
|
||||
groupIds: [2],
|
||||
products: [
|
||||
{ id: 11, name: 'Chicken' },
|
||||
{ id: 12, name: 'Mutton' },
|
||||
{ id: 13, name: 'Fish', shortDescription: 'Fresh catch' },
|
||||
],
|
||||
vendorSnippets: [
|
||||
{
|
||||
id: 100,
|
||||
snippetCode: 'SNIP-AAA',
|
||||
slotId: 7,
|
||||
skuIds: [11, 13],
|
||||
isPermanent: false,
|
||||
validTill: '2030-01-01T00:00:00.000Z',
|
||||
createdAt: '2026-09-01T00:00:00.000Z',
|
||||
accessUrl: 'https://app.freshyo.in/vendor-order-list?id=SNIP-AAA',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const procedures = {
|
||||
'admin.slots.getSlotById': { slot },
|
||||
}
|
||||
|
||||
describe('Slot details', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = { slotId: '7' }
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' } as any)
|
||||
routerMock.push.mockClear()
|
||||
})
|
||||
|
||||
it('shows a loader while fetching', () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
fetchMock.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
renderWithProviders(<SlotDetails />)
|
||||
|
||||
expect(screen.getByText('Loading slot details...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows an error state when the slot is missing', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.slots.getSlotById': null } })
|
||||
|
||||
renderWithProviders(<SlotDetails />)
|
||||
|
||||
expect(await screen.findByText('Error loading slot details')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders slot header, products and snippets', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<SlotDetails />)
|
||||
|
||||
expect(await screen.findByText('Slot #7')).toBeVisible()
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.getSlotById')).toEqual({ id: 7 })
|
||||
|
||||
expect(screen.getByText('3 items')).toBeVisible()
|
||||
expect(screen.getByText('Chicken')).toBeVisible()
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
expect(screen.getByText('Fish')).toBeVisible()
|
||||
|
||||
expect(screen.getByText('1 snippets')).toBeVisible()
|
||||
expect(screen.getByText('SNIP-AAA')).toBeVisible()
|
||||
expect(screen.getByText('2 products')).toBeVisible()
|
||||
expect(screen.getByText('Share')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders empty states when there are no snippets or products', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.slots.getSlotById': {
|
||||
slot: { ...slot, products: [], vendorSnippets: [] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
renderWithProviders(<SlotDetails />)
|
||||
|
||||
expect(await screen.findByText('No vendor snippets for this slot')).toBeVisible()
|
||||
expect(screen.getByText('No products in this slot')).toBeVisible()
|
||||
})
|
||||
|
||||
it('opens the snippet products dialog with only the snippet skus', async () => {
|
||||
setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<SlotDetails />)
|
||||
await screen.findByText('Slot #7')
|
||||
|
||||
expect(screen.queryByText('Snippet Products')).toBeNull()
|
||||
fireEvent.press(screen.getByText('2 products'))
|
||||
|
||||
expect(await screen.findByText('Snippet Products')).toBeVisible()
|
||||
expect(screen.getByText('Fresh catch')).toBeVisible()
|
||||
expect(screen.getAllByText('Chicken').length).toBe(2)
|
||||
expect(screen.getAllByText('Fish').length).toBe(2)
|
||||
expect(screen.getAllByText('Mutton').length).toBe(1)
|
||||
})
|
||||
|
||||
it('shares the snippet access url', async () => {
|
||||
setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<SlotDetails />)
|
||||
await screen.findByText('Slot #7')
|
||||
|
||||
fireEvent.press(screen.getByText('Share'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Share.share).toHaveBeenCalledWith({
|
||||
message: 'https://app.freshyo.in/vendor-order-list?id=SNIP-AAA',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to the edit screen from the FAB', async () => {
|
||||
setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<SlotDetails />)
|
||||
await screen.findByText('Slot #7')
|
||||
|
||||
fireEvent.press(screen.getByTestId('edit-slot-fab'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/slots/edit/7'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
/**
|
||||
* Add slot screen (app/(drawer)/dashboard/slots/add.tsx) — base-slot prefill,
|
||||
* loading, and the create -> back integration.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
jest.mock('common-ui/src/components/date-time-picker', () => {
|
||||
const React = require('react')
|
||||
const { View, TouchableOpacity, Text } = require('react-native')
|
||||
const FIXED = new Date('2026-10-01T10:00:00.000Z')
|
||||
return {
|
||||
__esModule: true,
|
||||
default: ({ setValue, dateTestID, timeTestID }: any) =>
|
||||
React.createElement(
|
||||
View,
|
||||
null,
|
||||
React.createElement(
|
||||
TouchableOpacity,
|
||||
{ testID: dateTestID, onPress: () => setValue(FIXED) },
|
||||
React.createElement(Text, null, 'pick-date')
|
||||
),
|
||||
React.createElement(
|
||||
TouchableOpacity,
|
||||
{ testID: timeTestID, onPress: () => setValue(FIXED) },
|
||||
React.createElement(Text, null, 'pick-time')
|
||||
)
|
||||
),
|
||||
}
|
||||
})
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import AddSlot from '@/app/(drawer)/dashboard/slots/add'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const procedures = {
|
||||
'admin.slots.getAll': { slots: [], count: 0 },
|
||||
'admin.slots.createSlot': {
|
||||
slot: { id: 10 },
|
||||
createdSnippets: [],
|
||||
message: 'Slot created successfully',
|
||||
},
|
||||
'admin.slots.getSlotById': {
|
||||
slot: {
|
||||
id: 5,
|
||||
deliveryTime: '2026-09-30T10:00:00.000Z',
|
||||
freezeTime: '2026-09-30T06:00:00.000Z',
|
||||
isActive: true,
|
||||
isCapacityFull: false,
|
||||
products: [{ id: 11, name: 'Chicken' }],
|
||||
groupIds: [3],
|
||||
vendorSnippets: [],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
describe('Add slot', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
routerMock.push.mockClear()
|
||||
routerMock.back.mockClear()
|
||||
})
|
||||
|
||||
it('renders an empty create form and does not load a base slot', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<AddSlot />)
|
||||
|
||||
expect(await screen.findByText('Create New Slot')).toBeVisible()
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.slots.getAll'))
|
||||
expect(procCount(fetchMock, 'admin.slots.getSlotById')).toBe(0)
|
||||
})
|
||||
|
||||
it('shows a loader while the base slot is loading', () => {
|
||||
searchParamsMock.current = { baseslot: '5' }
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const original = fetchMock.getMockImplementation()!
|
||||
fetchMock.mockImplementation((url: any, options: any) =>
|
||||
String(url).includes('admin.slots.getSlotById')
|
||||
? new Promise(() => {})
|
||||
: original(url, options)
|
||||
)
|
||||
|
||||
renderWithProviders(<AddSlot />)
|
||||
|
||||
expect(screen.getByText('Loading base slot...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('prefills from the base slot and goes back after creating', async () => {
|
||||
searchParamsMock.current = { baseslot: '5' }
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<AddSlot />)
|
||||
|
||||
expect(await screen.findByText('Create New Slot')).toBeVisible()
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.getSlotById')
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.getSlotById')).toEqual({
|
||||
id: 5,
|
||||
})
|
||||
|
||||
fireEvent.press(screen.getByTestId('delivery-date-picker'))
|
||||
fireEvent.press(screen.getByTestId('freeze-date-picker'))
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.slots.createSlot'))
|
||||
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.createSlot')).toMatchObject({
|
||||
skuIds: [11],
|
||||
groupIds: [3],
|
||||
})
|
||||
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.slots.getAll')).toBeGreaterThan(1)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,110 +0,0 @@
|
|||
/**
|
||||
* Edit slot screen (app/(drawer)/dashboard/slots/edit/[id].tsx) — prefill,
|
||||
* not-found/loading states and the update -> back flow.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import EditSlot from '@/app/(drawer)/dashboard/slots/edit/[id]'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const slot = {
|
||||
id: 7,
|
||||
deliveryTime: '2026-10-01T10:00:00.000Z',
|
||||
freezeTime: '2026-10-01T06:00:00.000Z',
|
||||
isActive: true,
|
||||
isCapacityFull: false,
|
||||
products: [{ id: 11, name: 'Chicken' }],
|
||||
groupIds: [2],
|
||||
vendorSnippets: [],
|
||||
}
|
||||
|
||||
const procedures = {
|
||||
'admin.slots.getSlotById': { slot },
|
||||
'admin.slots.updateSlot': {
|
||||
slot: { id: 7 },
|
||||
createdSnippets: [],
|
||||
message: 'Slot updated successfully',
|
||||
},
|
||||
}
|
||||
|
||||
describe('Edit slot', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = { id: '7' }
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
routerMock.back.mockClear()
|
||||
})
|
||||
|
||||
it('shows a loader while the slot is loading', () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
fetchMock.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
renderWithProviders(<EditSlot />)
|
||||
|
||||
expect(screen.getByText('Loading slot...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows not-found when the slot does not exist', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.slots.getSlotById': null } })
|
||||
|
||||
renderWithProviders(<EditSlot />)
|
||||
|
||||
expect(await screen.findByText('Slot not found')).toBeVisible()
|
||||
})
|
||||
|
||||
it('submits the update and navigates back on success', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<EditSlot />)
|
||||
|
||||
expect(await screen.findByText('Edit Slot')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.updateSlot')
|
||||
)
|
||||
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.updateSlot')).toEqual({
|
||||
id: 7,
|
||||
deliveryTime: '2026-10-01T10:00:00.000Z',
|
||||
freezeTime: '2026-10-01T06:00:00.000Z',
|
||||
isActive: true,
|
||||
groupIds: [2],
|
||||
skuIds: [11],
|
||||
vendorSnippets: [],
|
||||
})
|
||||
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Slot updated successfully!')
|
||||
})
|
||||
|
||||
it('surfaces an update error', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const original = fetchMock.getMockImplementation()!
|
||||
fetchMock.mockImplementation((url: any, options: any) =>
|
||||
String(url).includes('admin.slots.updateSlot')
|
||||
? Promise.reject(new Error('Unable to Update Slot'))
|
||||
: original(url, options)
|
||||
)
|
||||
|
||||
renderWithProviders(<EditSlot />)
|
||||
await screen.findByText('Edit Slot')
|
||||
|
||||
fireEvent.press(screen.getByTestId('create-slot-button'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Unable to Update Slot')
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,153 +0,0 @@
|
|||
/**
|
||||
* Slots list screen (app/(drawer)/dashboard/slots/index.tsx) — rendering,
|
||||
* empty/loading/error states, capacity toggle mutation and navigation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import { Entypo } from '@expo/vector-icons'
|
||||
|
||||
import Slots from '@/app/(drawer)/dashboard/slots/index'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const slot1 = {
|
||||
id: 1,
|
||||
deliveryTime: '2026-10-01T10:00:00.000Z',
|
||||
freezeTime: '2026-10-01T06:00:00.000Z',
|
||||
isActive: true,
|
||||
isFlash: false,
|
||||
isCapacityFull: false,
|
||||
deliverySequence: [],
|
||||
groupIds: [],
|
||||
products: [
|
||||
{ id: 11, name: 'Chicken' },
|
||||
{ id: 12, name: 'Mutton' },
|
||||
{ id: 13, name: 'Fish' },
|
||||
],
|
||||
}
|
||||
|
||||
const slot2 = {
|
||||
id: 2,
|
||||
deliveryTime: '2026-10-02T10:00:00.000Z',
|
||||
freezeTime: '2026-10-02T06:00:00.000Z',
|
||||
isActive: false,
|
||||
isFlash: false,
|
||||
isCapacityFull: true,
|
||||
deliverySequence: [],
|
||||
groupIds: [],
|
||||
products: [],
|
||||
}
|
||||
|
||||
const procedures = {
|
||||
'admin.slots.getAll': { slots: [slot1, slot2], count: 2 },
|
||||
'admin.slots.updateSlotCapacity': {
|
||||
success: true,
|
||||
slot: slot1,
|
||||
message: 'updated',
|
||||
},
|
||||
}
|
||||
|
||||
describe('Slots list', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
routerMock.push.mockClear()
|
||||
})
|
||||
|
||||
it('shows a loading state while the query is pending', () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
fetchMock.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
renderWithProviders(<Slots />)
|
||||
|
||||
expect(screen.getByText('Loading slots...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders slot rows with products and status', async () => {
|
||||
renderWithProviders(<Slots />)
|
||||
|
||||
expect(await screen.findByText('Slot #1')).toBeVisible()
|
||||
expect(screen.getByText('Slot #2')).toBeVisible()
|
||||
|
||||
expect(screen.getByText('Active')).toBeVisible()
|
||||
expect(screen.getByText('Inactive')).toBeVisible()
|
||||
expect(screen.getByText('FULL')).toBeVisible()
|
||||
|
||||
expect(screen.getByText('Chicken, Mutton')).toBeVisible()
|
||||
expect(screen.getByText('+1 more')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders nothing when there are no slots', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.slots.getAll': { slots: [], count: 0 } } })
|
||||
renderWithProviders(<Slots />)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(
|
||||
(global as any).fetch,
|
||||
'admin.slots.getAll'
|
||||
)
|
||||
)
|
||||
expect(screen.queryByText(/Slot #/)).toBeNull()
|
||||
})
|
||||
|
||||
it('navigates to add, edit and details', async () => {
|
||||
renderWithProviders(<Slots />)
|
||||
await screen.findByText('Slot #1')
|
||||
|
||||
fireEvent.press(screen.getByTestId('add-slot-fab'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/add')
|
||||
|
||||
fireEvent.press(screen.getAllByText('Edit')[0])
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/edit/1')
|
||||
|
||||
fireEvent.press(screen.getByText('Slot #1'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/slots/slot-details?slotId=1'
|
||||
)
|
||||
})
|
||||
|
||||
it('toggles capacity through the row action menu', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
renderWithProviders(<Slots />)
|
||||
await screen.findByText('Slot #1')
|
||||
|
||||
const dots = screen.UNSAFE_getAllByType(Entypo)
|
||||
expect(dots.length).toBeGreaterThan(0)
|
||||
fireEvent.press(dots[0])
|
||||
|
||||
const checkbox = await screen.findByRole('checkbox')
|
||||
fireEvent.press(checkbox)
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.slots.updateSlotCapacity')
|
||||
)
|
||||
|
||||
expect(lastProcedureInput(fetchMock, 'admin.slots.updateSlotCapacity')).toEqual({
|
||||
slotId: 1,
|
||||
isCapacityFull: true,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Success',
|
||||
'Slot marked as full capacity. It will be hidden from users.'
|
||||
)
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.slots.getAll')).toBeGreaterThan(1)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
/**
|
||||
* Add store screen (app/(drawer)/dashboard/stores/add.tsx) — create mutation,
|
||||
* owner selection, success navigation and the owner-0 validation gap.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import AddStore from '@/app/(drawer)/dashboard/stores/add'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput } from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const procedures = {
|
||||
'admin.staffUser.getStaff': {
|
||||
staff: [{ id: 1, name: 'shafi', role: null, permissions: [] }],
|
||||
},
|
||||
'admin.product.getProducts': { products: [], count: 0 },
|
||||
'common.product.getAllSkusSummary': { skus: [] },
|
||||
'admin.store.createStore': {
|
||||
store: { id: 9, name: 'Freshyo Test' },
|
||||
message: 'Store created successfully',
|
||||
},
|
||||
'admin.store.getStores': { stores: [], count: 0 },
|
||||
}
|
||||
|
||||
describe('Add store', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
routerMock.push.mockClear()
|
||||
})
|
||||
|
||||
it('renders the create form', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<AddStore />)
|
||||
|
||||
expect(screen.getByText('Add New Store')).toBeVisible()
|
||||
expect(screen.getByPlaceholderText('Enter store name')).toBeVisible()
|
||||
expect(screen.getByText('Create Store')).toBeVisible()
|
||||
|
||||
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.staffUser.getStaff'))
|
||||
expectProcedureCalled(fetchMock, 'admin.product.getProducts')
|
||||
})
|
||||
|
||||
it('creates a store with the selected owner and navigates back to the list', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<AddStore />)
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter store name'),
|
||||
'Freshyo Test'
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Select owner'))
|
||||
fireEvent.press(await screen.findByText('shafi'))
|
||||
|
||||
fireEvent.press(screen.getByText('Create Store'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.store.createStore')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.store.createStore')).toEqual({
|
||||
name: 'Freshyo Test',
|
||||
description: '',
|
||||
owner: 1,
|
||||
products: [],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Store created successfully')
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores')
|
||||
)
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.store.getStores')
|
||||
)
|
||||
})
|
||||
|
||||
it('BUG: submits owner=0 when no owner is selected', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<AddStore />)
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Enter store name'),
|
||||
'No Owner Store'
|
||||
)
|
||||
fireEvent.press(screen.getByText('Create Store'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.store.createStore')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.store.createStore')).toMatchObject({
|
||||
owner: 0,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -1,172 +0,0 @@
|
|||
/**
|
||||
* Edit store screen (app/(drawer)/dashboard/stores/edit.tsx) — prefill,
|
||||
* not-found/loading states and the update -> list flow.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import EditStore from '@/app/(drawer)/dashboard/stores/edit'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { createQueryClient, renderWithProviders } from '../helpers/render'
|
||||
|
||||
const store = {
|
||||
id: 3,
|
||||
name: 'Freshyo Edit',
|
||||
description: 'Editable outlet',
|
||||
imageUrl: 'https://cdn.freshyo.in/store.png',
|
||||
owner: { id: 1, name: 'shafi' },
|
||||
createdAt: '2026-03-01T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const procedures = {
|
||||
'admin.store.getStoreById': { store },
|
||||
'admin.staffUser.getStaff': {
|
||||
staff: [{ id: 1, name: 'shafi', role: null, permissions: [] }],
|
||||
},
|
||||
'admin.product.getProducts': {
|
||||
products: [{ id: 1, name: 'Chicken', storeId: null, skus: [] }],
|
||||
count: 1,
|
||||
},
|
||||
'common.product.getAllSkusSummary': { skus: [] },
|
||||
'admin.store.updateStore': {
|
||||
store: { id: 3 },
|
||||
message: 'Store updated successfully',
|
||||
},
|
||||
'admin.store.getStores': { stores: [], count: 0 },
|
||||
}
|
||||
|
||||
describe('Edit store', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
searchParamsMock.current = { id: '3' }
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
routerMock.push.mockClear()
|
||||
})
|
||||
|
||||
it('shows a loader while the store is loading', () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
fetchMock.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
renderWithProviders(<EditStore />)
|
||||
|
||||
expect(screen.getByText('Loading store...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows not-found when the store does not exist', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.store.getStoreById': null } })
|
||||
|
||||
renderWithProviders(<EditStore />)
|
||||
|
||||
expect(await screen.findByText('Store not found')).toBeVisible()
|
||||
})
|
||||
|
||||
it('prefills the form and submits the update', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<EditStore />)
|
||||
|
||||
expect(await screen.findByText('Edit Store')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Freshyo Edit')).toBeVisible()
|
||||
expect(screen.getByDisplayValue('Editable outlet')).toBeVisible()
|
||||
expect(lastProcedureInput(fetchMock, 'admin.store.getStoreById')).toEqual({ id: 3 })
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.product.getProducts')
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Update Store'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.store.updateStore')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.store.updateStore')).toEqual({
|
||||
id: 3,
|
||||
name: 'Freshyo Edit',
|
||||
description: 'Editable outlet',
|
||||
owner: 1,
|
||||
products: [],
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Store updated successfully')
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores')
|
||||
)
|
||||
})
|
||||
|
||||
it('surfaces an update error', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const original = fetchMock.getMockImplementation()!
|
||||
fetchMock.mockImplementation((url: any, options: any) =>
|
||||
String(url).includes('admin.store.updateStore')
|
||||
? Promise.reject(new Error('Failed to update store'))
|
||||
: original(url, options)
|
||||
)
|
||||
|
||||
renderWithProviders(<EditStore />)
|
||||
await screen.findByText('Edit Store')
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.product.getProducts')
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByText('Update Store'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Failed to update store')
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches the mounted store and invalidates the stores list by array path after a successful update', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
// The injected client is the one trpc.useUtils() acts on, so spying on it
|
||||
// observes the real invalidation (spyOn keeps calling through).
|
||||
const client = createQueryClient()
|
||||
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
|
||||
|
||||
renderWithProviders(<EditStore />, { queryClient: client })
|
||||
|
||||
expect(await screen.findByText('Edit Store')).toBeVisible()
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.product.getProducts')
|
||||
)
|
||||
|
||||
// Baseline immediately before the interaction: the app shares one
|
||||
// module-singleton httpBatchLink client, so counts can leak across cases
|
||||
// in a full-file run — always assert a delta, never an absolute number.
|
||||
const before = procCount(fetchMock, 'admin.store.getStoreById')
|
||||
|
||||
fireEvent.press(screen.getByText('Update Store'))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.store.updateStore')
|
||||
)
|
||||
|
||||
// (a) `refetch()` re-runs the getStoreById query this screen has mounted.
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.store.getStoreById')).toBeGreaterThan(
|
||||
before
|
||||
)
|
||||
)
|
||||
|
||||
// (b) the list invalidation used the array query path, not the old dotted
|
||||
// string: `queryClient.invalidateQueries({ queryKey: [['admin','store','getStores']] })`.
|
||||
const paths = invalidateSpy.mock.calls.map((call) => {
|
||||
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
|
||||
return Array.isArray(key) ? key[0] : null
|
||||
})
|
||||
expect(paths).toContainEqual(['admin', 'store', 'getStores'])
|
||||
})
|
||||
})
|
||||
|
|
@ -1,188 +0,0 @@
|
|||
/**
|
||||
* Stores list screen (app/(drawer)/dashboard/stores/index.tsx) — grid render,
|
||||
* empty/loading/error states, edit-mode delete mutation and navigation.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import { MaterialIcons } from '@expo/vector-icons'
|
||||
|
||||
import Stores from '@/app/(drawer)/dashboard/stores/index'
|
||||
import { setupApiMocks, resetStorage } from '../mocks/api'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { refreshHooks, resetRefreshHooks } from '../mocks/refresh'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const store1 = {
|
||||
id: 1,
|
||||
name: 'Freshyo Kukatpally',
|
||||
description: 'Main outlet',
|
||||
imageUrl: null,
|
||||
owner: 1,
|
||||
createdAt: '2026-01-15T00:00:00.000Z',
|
||||
}
|
||||
const store2 = {
|
||||
id: 2,
|
||||
name: 'Freshyo Gachibowli',
|
||||
description: null,
|
||||
imageUrl: 'https://cdn.freshyo.in/store.png',
|
||||
owner: 2,
|
||||
createdAt: '2026-02-20T00:00:00.000Z',
|
||||
}
|
||||
|
||||
const procedures = {
|
||||
'admin.store.getStores': { stores: [store1, store2], count: 2 },
|
||||
'admin.store.deleteStore': { message: 'Store deleted successfully' },
|
||||
}
|
||||
|
||||
const iconByName = (name: string) =>
|
||||
screen.UNSAFE_getAllByType(MaterialIcons).find((i) => i.props.name === name)
|
||||
|
||||
describe('Stores list', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRefreshHooks()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks({ procedures })
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
routerMock.push.mockClear()
|
||||
})
|
||||
|
||||
it('shows a loading state', () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
fetchMock.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
|
||||
expect(screen.getByText('Loading stores...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows an error state and retries', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
fetchMock.mockRejectedValue(new Error('network down'))
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
|
||||
expect(await screen.findByText('Oops!')).toBeVisible()
|
||||
expect(screen.getByText('Retry')).toBeVisible()
|
||||
|
||||
const callsBefore = procCount(fetchMock, 'admin.store.getStores')
|
||||
fireEvent.press(screen.getByText('Retry'))
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.store.getStores')).toBeGreaterThan(
|
||||
callsBefore
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('renders the store grid', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
|
||||
expect(await screen.findByText('Freshyo Kukatpally')).toBeVisible()
|
||||
expect(screen.getByText('Freshyo Gachibowli')).toBeVisible()
|
||||
expect(screen.getByText('2 Locations')).toBeVisible()
|
||||
expect(screen.getByText('ID: #1')).toBeVisible()
|
||||
expect(screen.getAllByText('View Details')).toHaveLength(2)
|
||||
expectProcedureCalled(fetchMock, 'admin.store.getStores')
|
||||
})
|
||||
|
||||
it('renders the empty state', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.store.getStores': { stores: [], count: 0 } },
|
||||
})
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
|
||||
expect(await screen.findByText('No stores found')).toBeVisible()
|
||||
expect(screen.getByText('0 Locations')).toBeVisible()
|
||||
})
|
||||
|
||||
it('navigates to edit when a card is pressed', async () => {
|
||||
setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
await screen.findByText('Freshyo Kukatpally')
|
||||
|
||||
fireEvent.press(screen.getByText('Freshyo Kukatpally'))
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith({
|
||||
pathname: '/(drawer)/dashboard/stores/edit',
|
||||
params: { id: 1 },
|
||||
})
|
||||
})
|
||||
|
||||
it('navigates to add from the FAB', async () => {
|
||||
setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
await screen.findByText('Freshyo Kukatpally')
|
||||
|
||||
const addIcon = iconByName('add')
|
||||
expect(addIcon).toBeTruthy()
|
||||
fireEvent.press(addIcon!)
|
||||
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/stores/add'
|
||||
)
|
||||
})
|
||||
|
||||
it('deletes a store in edit mode and refetches', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
await screen.findByText('Freshyo Kukatpally')
|
||||
|
||||
fireEvent.press(screen.getByText('Edit'))
|
||||
expect(screen.getByText('Done')).toBeVisible()
|
||||
|
||||
const deleteIcon = iconByName('delete')
|
||||
expect(deleteIcon).toBeTruthy()
|
||||
fireEvent.press(deleteIcon!)
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalled()
|
||||
const buttons = alertSpy.mock.calls.find(
|
||||
(call) => call[0] === 'Delete Store'
|
||||
)?.[2] as { text: string; onPress?: () => void }[]
|
||||
expect(buttons?.map((b) => b.text)).toEqual(['Cancel', 'Delete'])
|
||||
|
||||
act(() => {
|
||||
buttons.find((b) => b.text === 'Delete')?.onPress?.()
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.store.deleteStore')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.store.deleteStore')).toEqual({
|
||||
storeId: 1,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Success', 'Store deleted successfully')
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.store.getStores')).toBeGreaterThan(1)
|
||||
)
|
||||
})
|
||||
|
||||
it('refetches through the mark-data-fetchers callback', async () => {
|
||||
const { fetchMock } = setupApiMocks({ procedures })
|
||||
|
||||
renderWithProviders(<Stores />)
|
||||
await screen.findByText('Freshyo Kukatpally')
|
||||
|
||||
expect(refreshHooks.markDataFetchers).toBeTruthy()
|
||||
const before = procCount(fetchMock, 'admin.store.getStores')
|
||||
refreshHooks.markDataFetchers?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.store.getStores')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,248 +0,0 @@
|
|||
/**
|
||||
* User details (app/(drawer)/dashboard/user-management/[id].tsx) — detail
|
||||
* rendering, suspension toggle, order history, navigation and error/retry.
|
||||
*
|
||||
* SCOPE NOTE: this screen has no notification UI or procedure (the only
|
||||
* notification screen is app/(drawer)/dashboard/send-notifications, out of
|
||||
* scope). "Incidents" is exercised through the embedded UserIncidentsView.
|
||||
*
|
||||
* HARNESS BUG WORKAROUND: tests/mocks/native.ts has a stray top-level `return`
|
||||
* (line 89 → "'return' outside of function"). Re-mock the expo modules that
|
||||
* `common-ui` eagerly imports locally. See report.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
jest.mock('expo-image', () => {
|
||||
const React = require('react')
|
||||
const { View } = require('react-native')
|
||||
const Image = (props: Record<string, unknown>) =>
|
||||
React.createElement(View, { testID: 'mock-image', ...props })
|
||||
return { __esModule: true, Image, default: Image }
|
||||
})
|
||||
|
||||
jest.mock('expo-image-picker', () => {
|
||||
const asset = { uri: 'file:///tmp/pick.jpg', fileName: 'pick.jpg', mimeType: 'image/jpeg' }
|
||||
return {
|
||||
__esModule: true,
|
||||
MediaTypeOptions: { Images: 'Images', All: 'All', Videos: 'Videos' },
|
||||
launchImageLibraryAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
launchCameraAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
requestMediaLibraryPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
requestCameraPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('expo-document-picker', () => ({
|
||||
__esModule: true,
|
||||
getDocumentAsync: jest.fn(async () => ({
|
||||
canceled: false,
|
||||
assets: [{ uri: 'file:///tmp/doc.pdf', name: 'doc.pdf', mimeType: 'application/pdf' }],
|
||||
})),
|
||||
}))
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, TouchableOpacity } from 'react-native'
|
||||
import { Checkbox } from 'common-ui'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import UserDetails from '@/app/(drawer)/dashboard/user-management/[id]'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { expectProcedureCalled, lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const makeDetails = (overrides: Record<string, unknown> = {}) => ({
|
||||
user: {
|
||||
id: 3,
|
||||
name: 'Alice',
|
||||
mobile: '9999999999',
|
||||
createdAt: '2026-01-01T10:00:00.000Z',
|
||||
isSuspended: false,
|
||||
},
|
||||
orders: [
|
||||
{
|
||||
id: 11,
|
||||
readableId: 11,
|
||||
totalAmount: '500',
|
||||
createdAt: '2026-02-01T10:00:00.000Z',
|
||||
status: 'delivered',
|
||||
isFlashDelivery: false,
|
||||
itemCount: 2,
|
||||
},
|
||||
{
|
||||
id: 12,
|
||||
readableId: 12,
|
||||
totalAmount: '250',
|
||||
createdAt: '2026-02-02T10:00:00.000Z',
|
||||
status: 'pending',
|
||||
isFlashDelivery: true,
|
||||
itemCount: 1,
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const procedures = (overrides: Record<string, unknown> = {}) => ({
|
||||
'admin.user.getUserDetails': makeDetails(),
|
||||
'admin.user.updateUserSuspension': { success: true, message: 'ok' },
|
||||
'admin.user.getUserIncidents': { incidents: [] },
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderDetails = (overrides: Record<string, unknown> = {}) => {
|
||||
const { fetchMock } = setupApiMocks({ procedures: procedures(overrides) })
|
||||
renderWithProviders(<UserDetails />)
|
||||
return { fetchMock }
|
||||
}
|
||||
|
||||
describe('User details', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = { id: '3' }
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows a loading state while the details are pending', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getUserDetails': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<UserDetails />)
|
||||
|
||||
expect(screen.getByText('Loading user details...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('queries the user with the route id', async () => {
|
||||
const { fetchMock } = renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('User Details')).toBeVisible())
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.getUserDetails')).toEqual({ userId: 3 })
|
||||
})
|
||||
|
||||
it('renders the user info and order history', async () => {
|
||||
renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('User Details')).toBeVisible())
|
||||
expect(screen.getByText('9999999999')).toBeVisible()
|
||||
expect(screen.getByText('Alice')).toBeVisible()
|
||||
expect(screen.getByText('Order History')).toBeVisible()
|
||||
expect(screen.getByText('2 orders')).toBeVisible()
|
||||
expect(screen.getByText('#11')).toBeVisible()
|
||||
expect(screen.getByText('#12')).toBeVisible()
|
||||
expect(screen.getByText('₹500')).toBeVisible()
|
||||
expect(screen.getByText('2 items')).toBeVisible()
|
||||
expect(screen.getByText('1 item')).toBeVisible()
|
||||
expect(screen.getByText('delivered')).toBeVisible()
|
||||
expect(screen.getByText('pending')).toBeVisible()
|
||||
expect(screen.getByText(/Registered/)).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders an empty order history', async () => {
|
||||
renderDetails({ 'admin.user.getUserDetails': makeDetails({ orders: [] }) })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No orders yet')).toBeVisible())
|
||||
})
|
||||
|
||||
it('renders the suspended badge when the user is suspended', async () => {
|
||||
renderDetails({
|
||||
'admin.user.getUserDetails': makeDetails({
|
||||
user: { ...makeDetails().user, isSuspended: true },
|
||||
}),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Suspended')).toBeVisible())
|
||||
})
|
||||
|
||||
it('suspends the user through the checkbox and refetches', async () => {
|
||||
const { fetchMock } = renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('User Details')).toBeVisible())
|
||||
const before = procCount(fetchMock, 'admin.user.getUserDetails')
|
||||
|
||||
fireEvent.press(screen.UNSAFE_getByType(Checkbox as never))
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.user.updateUserSuspension')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.updateUserSuspension')).toEqual({
|
||||
userId: 3,
|
||||
isSuspended: true,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.user.getUserDetails')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('unsuspends an already suspended user', async () => {
|
||||
const { fetchMock } = renderDetails({
|
||||
'admin.user.getUserDetails': makeDetails({
|
||||
user: { ...makeDetails().user, isSuspended: true },
|
||||
}),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Suspended')).toBeVisible())
|
||||
fireEvent.press(screen.UNSAFE_getByType(Checkbox as never))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.updateUserSuspension')).toEqual({
|
||||
userId: 3,
|
||||
isSuspended: false,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the error state when the query fails and refetches on Retry', async () => {
|
||||
const { fetchMock } = renderDetails({
|
||||
'admin.user.getUserDetails': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Error')).toBeVisible())
|
||||
expect(screen.getByText('boom')).toBeVisible()
|
||||
|
||||
const before = procCount(fetchMock, 'admin.user.getUserDetails')
|
||||
fireEvent.press(screen.getByText('Retry'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(fetchMock, 'admin.user.getUserDetails')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the default error message when there is no data', async () => {
|
||||
renderDetails({ 'admin.user.getUserDetails': null })
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Failed to load user details')).toBeVisible()
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to an order and back', async () => {
|
||||
renderDetails()
|
||||
|
||||
await waitFor(() => expect(screen.getByText('#11')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('#11'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith(
|
||||
'/(drawer)/dashboard/manage-orders/order-details/11'
|
||||
)
|
||||
|
||||
const back = screen.UNSAFE_getAllByType(TouchableOpacity)[0]
|
||||
fireEvent.press(back)
|
||||
expect(routerMock.back).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes the route user id to the incidents view', async () => {
|
||||
const { fetchMock } = renderDetails()
|
||||
|
||||
await waitFor(() =>
|
||||
expectProcedureCalled(fetchMock, 'admin.user.getUserIncidents')
|
||||
)
|
||||
expect(lastProcedureInput(fetchMock, 'admin.user.getUserIncidents')).toEqual({
|
||||
userId: 3,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -1,211 +0,0 @@
|
|||
/**
|
||||
* User management list (app/(drawer)/dashboard/user-management/index.tsx) —
|
||||
* infinite list, search, rows, empty/error/loading, pagination and navigation.
|
||||
*
|
||||
* HARNESS BUG WORKAROUND: tests/mocks/native.ts has a stray top-level `return`
|
||||
* (line 89 → "'return' outside of function"). Re-mock the three expo modules
|
||||
* that `common-ui` eagerly imports, without touching the harness. See report.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
jest.mock('expo-image', () => {
|
||||
const React = require('react')
|
||||
const { View } = require('react-native')
|
||||
const Image = (props: Record<string, unknown>) =>
|
||||
React.createElement(View, { testID: 'mock-image', ...props })
|
||||
return { __esModule: true, Image, default: Image }
|
||||
})
|
||||
|
||||
jest.mock('expo-image-picker', () => {
|
||||
const asset = { uri: 'file:///tmp/pick.jpg', fileName: 'pick.jpg', mimeType: 'image/jpeg' }
|
||||
return {
|
||||
__esModule: true,
|
||||
MediaTypeOptions: { Images: 'Images', All: 'All', Videos: 'Videos' },
|
||||
launchImageLibraryAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
launchCameraAsync: jest.fn(async () => ({ canceled: false, assets: [asset] })),
|
||||
requestMediaLibraryPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
requestCameraPermissionsAsync: jest.fn(async () => ({ granted: true, status: 'granted' })),
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('expo-document-picker', () => ({
|
||||
__esModule: true,
|
||||
getDocumentAsync: jest.fn(async () => ({
|
||||
canceled: false,
|
||||
assets: [{ uri: 'file:///tmp/doc.pdf', name: 'doc.pdf', mimeType: 'application/pdf' }],
|
||||
})),
|
||||
}))
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, FlatList } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
|
||||
import UserManagement from '@/app/(drawer)/dashboard/user-management/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import { lastProcedureInput, procCount } from '../mocks/procedures'
|
||||
import { resetRouterMock, routerMock, searchParamsMock } from '../mocks/router'
|
||||
import { resetRefreshHooks } from '../mocks/refresh'
|
||||
import { resetStaffAuthMock } from '../mocks/staff-auth'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const alice = {
|
||||
id: 3,
|
||||
name: 'Alice',
|
||||
mobile: '9999999999',
|
||||
createdAt: '2026-01-01T10:00:00.000Z',
|
||||
totalOrders: 4,
|
||||
lastOrderDate: '2026-02-01T10:00:00.000Z',
|
||||
isSuspended: false,
|
||||
}
|
||||
|
||||
const bob = {
|
||||
id: 4,
|
||||
name: null,
|
||||
mobile: '8888888888',
|
||||
createdAt: '2026-01-15T10:00:00.000Z',
|
||||
totalOrders: 0,
|
||||
lastOrderDate: null,
|
||||
isSuspended: true,
|
||||
}
|
||||
|
||||
const page = (users: unknown[], nextCursor?: number) => ({
|
||||
users,
|
||||
nextCursor,
|
||||
hasMore: nextCursor != null,
|
||||
})
|
||||
|
||||
describe('User management list', () => {
|
||||
beforeEach(async () => {
|
||||
resetStaffAuthMock()
|
||||
resetRefreshHooks()
|
||||
await resetStorage()
|
||||
resetRouterMock()
|
||||
searchParamsMock.current = {}
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
it('shows a loading state while the list query is pending', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getAllUsers': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
expect(screen.getByText('Loading users...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('renders rows with mobile, name, order stats and suspension badge', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getAllUsers': page([alice, bob]) },
|
||||
})
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('9999999999')).toBeVisible())
|
||||
expect(screen.getByText('8888888888')).toBeVisible()
|
||||
expect(screen.getByText('Alice')).toBeVisible()
|
||||
expect(screen.getByText('Unnamed User')).toBeVisible()
|
||||
expect(screen.getByText('4 orders')).toBeVisible()
|
||||
expect(screen.getByText('0 orders')).toBeVisible()
|
||||
expect(screen.getByText('Suspended')).toBeVisible()
|
||||
expect(screen.getByText('Showing 2 users')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no users', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.user.getAllUsers': page([]) } })
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No users found')).toBeVisible())
|
||||
expect(screen.queryByText('Try adjusting your search')).toBeNull()
|
||||
})
|
||||
|
||||
it('hints to adjust the search when the search has no matches', async () => {
|
||||
setupApiMocks({ procedures: { 'admin.user.getAllUsers': page([]) } })
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No users found')).toBeVisible())
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Search by mobile number...'),
|
||||
'0000'
|
||||
)
|
||||
|
||||
expect(await screen.findByText('Try adjusting your search')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state and refetches on Retry', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.user.getAllUsers': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Error')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.user.getAllUsers')
|
||||
fireEvent.press(screen.getByText('Retry'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.user.getAllUsers')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
|
||||
it('sends the search term to getAllUsers', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'admin.user.getAllUsers': page([alice]) },
|
||||
})
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('9999999999')).toBeVisible())
|
||||
|
||||
fireEvent.changeText(
|
||||
screen.getByPlaceholderText('Search by mobile number...'),
|
||||
'8888'
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.user.getAllUsers')).toMatchObject({
|
||||
limit: 30,
|
||||
search: '8888',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates to the user detail screen from a row', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.user.getAllUsers': page([alice, bob]) },
|
||||
})
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('9999999999')).toBeVisible())
|
||||
|
||||
fireEvent.press(screen.getByText('9999999999'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/3')
|
||||
|
||||
fireEvent.press(screen.getByText('8888888888'))
|
||||
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/4')
|
||||
})
|
||||
|
||||
it('fetches the next page when the list end is reached', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.user.getAllUsers': (input: { cursor?: number }) =>
|
||||
input?.cursor ? page([{ ...alice, id: 9, mobile: '7777777777' }]) : page([alice], 100),
|
||||
},
|
||||
})
|
||||
renderWithProviders(<UserManagement />)
|
||||
|
||||
await screen.findByText('9999999999')
|
||||
const list = screen.UNSAFE_getByType(FlatList as never)
|
||||
act(() => list.props.onEndReached())
|
||||
|
||||
expect(await screen.findByText('7777777777')).toBeVisible()
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.user.getAllUsers')).toMatchObject({
|
||||
limit: 30,
|
||||
cursor: 100,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -1,251 +0,0 @@
|
|||
/**
|
||||
* Vendor snippets list (app/(drawer)/dashboard/vendor-snippets/index.tsx) —
|
||||
* list rows with expiry status, empty/loading/error states, share link, the
|
||||
* per-row options menu (edit / delete / view orders) and FAB create flow.
|
||||
*/
|
||||
|
||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||
|
||||
import React from 'react'
|
||||
import { Alert, Share, TouchableOpacity } from 'react-native'
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
|
||||
import VendorSnippets from '@/app/(drawer)/dashboard/vendor-snippets/index'
|
||||
import { resetStorage, setupApiMocks } from '../mocks/api'
|
||||
import {
|
||||
expectProcedureCalled,
|
||||
lastProcedureInput,
|
||||
procCount,
|
||||
} from '../mocks/procedures'
|
||||
import { renderWithProviders } from '../helpers/render'
|
||||
|
||||
const snippet = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 1,
|
||||
snippetCode: 'VS_1',
|
||||
slotId: 2,
|
||||
isPermanent: false,
|
||||
skuIds: [10, 11],
|
||||
products: [
|
||||
{ id: 10, name: 'Chicken' },
|
||||
{ id: 11, name: 'Mutton' },
|
||||
],
|
||||
validTill: '2027-01-01T00:00:00.000Z',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
accessUrl: 'https://app.freshyo.in/vendor-order-list?id=VS_1',
|
||||
slot: {
|
||||
id: 2,
|
||||
deliveryTime: '2026-12-31T10:00:00.000Z',
|
||||
freezeTime: '2026-12-30T10:00:00.000Z',
|
||||
isActive: true,
|
||||
deliverySequence: 1,
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const order = {
|
||||
orderId: 'ORD1',
|
||||
orderDate: '2026-01-02T09:00:00.000Z',
|
||||
customerName: 'Alice',
|
||||
totalAmount: 100,
|
||||
slotInfo: { time: '2026-01-03T10:00:00.000Z', sequence: [] },
|
||||
snippetCode: 'VS_1',
|
||||
matchedProducts: [10],
|
||||
products: [
|
||||
{ productId: 10, productName: 'Chicken', quantity: 2, price: 50, unit: 'kg', subtotal: 100 },
|
||||
],
|
||||
}
|
||||
|
||||
const openFirstMenu = (result: ReturnType<typeof renderWithProviders>) => {
|
||||
fireEvent.press(result.UNSAFE_getAllByType(TouchableOpacity)[0])
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
const calls = (Alert.alert as jest.Mock).mock.calls
|
||||
const call = calls[calls.length - 1]
|
||||
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
||||
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
||||
}
|
||||
|
||||
describe('Vendor snippets list', () => {
|
||||
beforeEach(async () => {
|
||||
await resetStorage()
|
||||
setupApiMocks()
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||
jest.spyOn(Share, 'share').mockResolvedValue({ action: Share.sharedAction } as never)
|
||||
})
|
||||
|
||||
it('shows the loading state while the query is pending', () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.vendorSnippets.getAll': () => new Promise(() => {}) },
|
||||
})
|
||||
renderWithProviders(<VendorSnippets />)
|
||||
|
||||
expect(screen.getByText('Loading vendor snippets...')).toBeVisible()
|
||||
})
|
||||
|
||||
it('shows the error state when the query fails', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.vendorSnippets.getAll': () => {
|
||||
throw new Error('boom')
|
||||
},
|
||||
},
|
||||
})
|
||||
renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Error loading snippets')).toBeVisible())
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no snippets', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.vendorSnippets.getAll': [] },
|
||||
})
|
||||
renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('No Snippets Yet')).toBeVisible())
|
||||
})
|
||||
|
||||
it('renders snippet rows with status and item count', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.vendorSnippets.getAll': [
|
||||
snippet(),
|
||||
snippet({
|
||||
id: 2,
|
||||
snippetCode: 'VS_EXPIRED',
|
||||
isPermanent: true,
|
||||
validTill: '2020-01-01T00:00:00.000Z',
|
||||
slot: null,
|
||||
}),
|
||||
],
|
||||
},
|
||||
})
|
||||
renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
expect(screen.getByText('VS_EXPIRED')).toBeVisible()
|
||||
expect(screen.getByText('Active')).toBeVisible()
|
||||
expect(screen.getByText('Expired')).toBeVisible()
|
||||
expect(screen.getByText('Permanent')).toBeVisible()
|
||||
expect(screen.getByText('Always Active')).toBeVisible()
|
||||
expect(screen.getAllByText('2 Items')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('shares the snippet access link', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.vendorSnippets.getAll': [snippet()] },
|
||||
})
|
||||
renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Share'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(Share.share).toHaveBeenCalledWith({
|
||||
message: 'https://app.freshyo.in/vendor-order-list?id=VS_1',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('warns instead of sharing when the link is missing', async () => {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'admin.vendorSnippets.getAll': [snippet({ accessUrl: undefined })],
|
||||
},
|
||||
})
|
||||
renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
fireEvent.press(screen.getByText('Share'))
|
||||
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Error', 'No link available')
|
||||
expect(Share.share).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the create form from the FAB', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.vendorSnippets.getAll': [snippet()] },
|
||||
})
|
||||
const result = renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
const addIcon = result.UNSAFE_getAllByType(MaterialIcons).find(
|
||||
(node) => node.props.name === 'add'
|
||||
)!
|
||||
fireEvent.press(addIcon)
|
||||
|
||||
expect(await screen.findByText('Create Vendor Snippet')).toBeVisible()
|
||||
})
|
||||
|
||||
it('deletes a snippet through the row menu', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.vendorSnippets.getAll': [snippet()],
|
||||
'admin.vendorSnippets.delete': { message: 'Vendor snippet deleted successfully' },
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
openFirstMenu(result)
|
||||
fireEvent.press(await screen.findByText('Delete'))
|
||||
pressLastAlertButton('Delete')
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.vendorSnippets.delete'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.vendorSnippets.delete')).toEqual({ id: 1 })
|
||||
})
|
||||
|
||||
it('loads the matched orders through the row menu', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: {
|
||||
'admin.vendorSnippets.getAll': [snippet()],
|
||||
'admin.vendorSnippets.getOrdersBySnippet': {
|
||||
success: true,
|
||||
data: [order],
|
||||
snippet: snippet(),
|
||||
},
|
||||
},
|
||||
})
|
||||
const result = renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
openFirstMenu(result)
|
||||
fireEvent.press(await screen.findByText('View Orders'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.vendorSnippets.getOrdersBySnippet'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'admin.vendorSnippets.getOrdersBySnippet')).toEqual({
|
||||
snippetCode: 'VS_1',
|
||||
})
|
||||
expect(await screen.findByText('Orders for "VS_1"')).toBeVisible()
|
||||
expect(screen.getByText('ORD1')).toBeVisible()
|
||||
})
|
||||
|
||||
it('opens the edit form from the row menu', async () => {
|
||||
setupApiMocks({
|
||||
procedures: { 'admin.vendorSnippets.getAll': [snippet()] },
|
||||
})
|
||||
const result = renderWithProviders(<VendorSnippets />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
openFirstMenu(result)
|
||||
fireEvent.press(await screen.findByText('Edit'))
|
||||
|
||||
expect(await screen.findByText('Edit Vendor Snippet')).toBeVisible()
|
||||
})
|
||||
|
||||
it('refetches through the mark-data-fetchers hook', async () => {
|
||||
const api = setupApiMocks({
|
||||
procedures: { 'admin.vendorSnippets.getAll': [snippet()] },
|
||||
})
|
||||
renderWithProviders(<VendorSnippets />)
|
||||
await waitFor(() => expect(screen.getByText('VS_1')).toBeVisible())
|
||||
|
||||
const before = procCount(api.fetchMock, 'admin.vendorSnippets.getAll')
|
||||
const { refreshHooks } = require('../mocks/refresh')
|
||||
refreshHooks.markDataFetchers?.()
|
||||
await waitFor(() =>
|
||||
expect(procCount(api.fetchMock, 'admin.vendorSnippets.getAll')).toBeGreaterThan(before)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,122 +0,0 @@
|
|||
/**
|
||||
* Shared Jest setup for apps/admin-ui.
|
||||
*
|
||||
* Only the native/context dependencies that cannot run under a plain Jest
|
||||
* environment are stubbed here. Components, stores and hooks stay real.
|
||||
*
|
||||
* expo-router is NOT mocked globally — tests that need it add the mock
|
||||
* themselves (see tests/mocks/router.ts), and router tests can use the real one.
|
||||
*/
|
||||
|
||||
jest.mock('common-ui/hooks/useMarkDataFetchers', () => ({
|
||||
__esModule: true,
|
||||
useMarkDataFetchers: (cb: () => void) => {
|
||||
require('./mocks/refresh').refreshHooks.markDataFetchers = cb
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('common-ui/hooks/useManualRefresh', () => ({
|
||||
__esModule: true,
|
||||
default: (cb: () => void) => {
|
||||
require('./mocks/refresh').refreshHooks.manualRefresh = cb
|
||||
},
|
||||
}))
|
||||
|
||||
/**
|
||||
* Native / third-party modules that cannot run under jest. Stubs live in
|
||||
* tests/mocks/native.ts.
|
||||
*/
|
||||
jest.mock('react-native-draggable-flatlist', () => require('./mocks/native').draggableFlatListMock())
|
||||
jest.mock('react-native-tab-view', () => require('./mocks/native').tabViewMock())
|
||||
jest.mock('react-native-toast-message', () => require('./mocks/native').toastMock())
|
||||
jest.mock('expo-location', () => require('./mocks/native').locationMock())
|
||||
jest.mock('expo-image-picker', () => require('./mocks/native').imagePickerMock())
|
||||
jest.mock('expo-document-picker', () => require('./mocks/native').documentPickerMock())
|
||||
jest.mock('expo-device', () => require('./mocks/native').deviceMock())
|
||||
jest.mock('expo-haptics', () => require('./mocks/native').hapticsMock())
|
||||
jest.mock('expo-linear-gradient', () => require('./mocks/native').linearGradientMock())
|
||||
jest.mock('expo-blur', () => require('./mocks/native').blurMock())
|
||||
jest.mock('expo-image', () => require('./mocks/native').imageMock())
|
||||
|
||||
/**
|
||||
* useFocusEffect throws without a NavigationContainer. Run the callback once on
|
||||
* mount instead so focus-driven side effects are testable.
|
||||
*/
|
||||
jest.mock('@react-navigation/native', () => {
|
||||
const actual = jest.requireActual('@react-navigation/native')
|
||||
const React = require('react')
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useFocusEffect: (callback: () => void | (() => void)) => {
|
||||
const ran = React.useRef(false)
|
||||
React.useEffect(() => {
|
||||
if (ran.current) return
|
||||
ran.current = true
|
||||
return callback()
|
||||
}, [])
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Staff auth is stubbed with a signed-in shape, overridable via
|
||||
* tests/mocks/staff-auth.ts. Real-provider tests unmock this module.
|
||||
*/
|
||||
jest.mock('@/components/context/staff-auth-context', () =>
|
||||
require('./mocks/staff-auth').staffAuthContextMock()
|
||||
)
|
||||
|
||||
/**
|
||||
* Secure + casual storage services are backed by expo-secure-store. Mock at the
|
||||
* service module path with an in-memory map.
|
||||
*/
|
||||
jest.mock('common-ui/src/services/StorageService', () => {
|
||||
const store = new Map<string, string>()
|
||||
|
||||
return {
|
||||
StorageService: {
|
||||
getItem: jest.fn(async (key: string) => store.get(key) ?? null),
|
||||
setItem: jest.fn(async (key: string, value: string) => {
|
||||
store.set(key, value)
|
||||
return true
|
||||
}),
|
||||
removeItem: jest.fn(async (key: string) => {
|
||||
store.delete(key)
|
||||
return true
|
||||
}),
|
||||
clearAll: jest.fn(async (keys: string[]) => {
|
||||
keys.forEach((key) => store.delete(key))
|
||||
return true
|
||||
}),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
jest.mock('common-ui/src/services/StorageServiceCasual', () => {
|
||||
const store = new Map<string, string>()
|
||||
|
||||
return {
|
||||
StorageServiceCasual: {
|
||||
getItem: jest.fn(async (key: string) => store.get(key) ?? null),
|
||||
setItem: jest.fn(async (key: string, value: string) => {
|
||||
store.set(key, value)
|
||||
return true
|
||||
}),
|
||||
removeItem: jest.fn(async (key: string) => {
|
||||
store.delete(key)
|
||||
return true
|
||||
}),
|
||||
clearAll: jest.fn(async (keys: string[]) => {
|
||||
keys.forEach((key) => store.delete(key))
|
||||
return true
|
||||
}),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Freeze the clock so date-sensitive screens (slots, orders, banners) are
|
||||
* deterministic. Move it with jest.setSystemTime / advanceTimersByTime.
|
||||
*/
|
||||
jest.useFakeTimers({ now: Date.now() })
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
Review and fix the top 3 React Doctor findings in user-ui. Leave the rest for a follow-up.
|
||||
|
||||
1. WARN Maintainability: React function has high control-flow complexity (×15)
|
||||
`Login` has cyclomatic complexity 30, cognitive complexity 30, and maximum nesting depth 3, so its React logic is hard to understand and change. Extract independent branches into components or hooks.
|
||||
Curl with no cache & follow the canonical fix and false positive check recipe before fixing: https://react.doctor/docs/rules/react-doctor/no-high-complexity-react-function
|
||||
- app/(auth)/login.tsx:15
|
||||
- app/(drawer)/(tabs)/me/my-orders/[id].tsx:14
|
||||
- app/(drawer)/(tabs)/me/my-orders/index.tsx:74
|
||||
- +11 more files
|
||||
2. WARN Maintainability: Large component is hard to read and change (×11)
|
||||
Component "Login" is over 300 lines long, which is hard to read & change. Split it into a few smaller components.
|
||||
Curl with no cache & follow the canonical fix and false positive check recipe before fixing: https://react.doctor/docs/rules/react-doctor/no-giant-component
|
||||
- app/(auth)/login.tsx:15
|
||||
- app/(drawer)/(tabs)/me/my-orders/[id].tsx:14
|
||||
- components/PaymentAndOrderComponent.tsx:32
|
||||
- +8 more files
|
||||
3. WARN Performance: State only used in handlers (×10)
|
||||
Each update to "passwordBackTo" redraws your component for nothing because this useState is set but never shown on screen.
|
||||
Curl with no cache & follow the canonical fix and false positive check recipe before fixing: https://react.doctor/docs/rules/react-doctor/rerender-state-only-in-handlers
|
||||
- app/(auth)/login.tsx:19
|
||||
- app/(drawer)/(tabs)/me/my-orders/index.tsx:373
|
||||
- components/ProductCard.tsx:55
|
||||
- +3 more files
|
||||
|
||||
Full results for all 121 issues (diagnostics.json + a .txt per rule): /var/folders/6t/3blzq7_j6p95xzry6t7c14hw0000gn/T/react-doctor-d12050a6-1365-4f35-8c90-23fa748a45bd
|
||||
|
||||
Read each file and fix the root cause — don't suppress or silence the rule.
|
||||
|
||||
Findings that share a `fixGroupId` (in diagnostics.json) are one root cause — a single fix clears all of them, so treat each `fixGroupId` as ONE task, not one per site.
|
||||
|
||||
Verify against the real thing, don't assume: confirm each change matches the canonical fix recipe you fetched for that rule, then re-run `npx react-doctor@latest --verbose` and check the issue is actually gone against the real tool before moving on.
|
||||
|
||||
Teach me as you go: for every issue you touch, explain it in plain language (no jargon) — what the problem is, why it's a problem, and how serious it is in human terms. Describe the real-world impact and severity concretely (e.g. "this crashes the page for users on Safari" vs. "this is a minor cleanup with no user impact") so I understand why it matters, not just what changed.
|
||||
|
||||
Stop after this pass. Summarize the remaining findings for a follow-up.
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
# Backend API tests — fill these in before running `bun run test:api`.
|
||||
# This file is git-ignored.
|
||||
|
||||
API_BASE_URL=http://localhost:8787
|
||||
|
||||
ADMIN_NAME=shafi
|
||||
ADMIN_PASSWORD=shafI123
|
||||
|
||||
USER_IDENTIFIER=9676651496
|
||||
USER_PASSWORD=meatfarmer@123
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
# Backend API tests — copy this file to `tests/.env` and fill in the values.
|
||||
# `tests/.env` is git-ignored.
|
||||
|
||||
# Backend base URL. `bun run dev` serves wrangler dev on :8787.
|
||||
API_BASE_URL=http://localhost:8787
|
||||
|
||||
# Staff (admin-ui) credentials — used for admin.* procedures.
|
||||
ADMIN_NAME=
|
||||
ADMIN_PASSWORD=
|
||||
|
||||
# User (app) credentials — used for user.* procedures.
|
||||
# USER_IDENTIFIER is the email or the 10-digit mobile number.
|
||||
USER_IDENTIFIER=
|
||||
USER_PASSWORD=
|
||||
|
|
@ -1,545 +0,0 @@
|
|||
# Known bugs — apps/backend
|
||||
|
||||
Found while writing the API integration suites under `tests/api/`. Each entry
|
||||
gives the source location, the actual behaviour, the expected behaviour and the
|
||||
test that pins it. Severity is my judgement of impact.
|
||||
|
||||
---
|
||||
|
||||
## High — security / data integrity
|
||||
|
||||
### 1. A user token can perform admin writes (missing staff guard)
|
||||
|
||||
`src/trpc/trpc-index.ts` — `protectedProcedure` only requires *some* identity
|
||||
(`ctx.user` OR `ctx.staffUser`). Many `admin.*` procedures never re-check
|
||||
`ctx.staffUser`, so a plain user token can call them.
|
||||
|
||||
Confirmed reachable with a user token:
|
||||
|
||||
- `admin.order.cancelOrder` — cancel any order
|
||||
- `admin.user.updateUserSuspension` — suspend any user
|
||||
- `admin.user.sendNotification` — broadcast notifications
|
||||
- `admin.product.toggleOutOfStock` (and the other `admin.product.*` writes)
|
||||
- `admin.staffUser.createStaffUser` — **create a usable staff account (privilege escalation)**; the new account can log in
|
||||
|
||||
Procedures that *do* guard correctly: `admin.slots.*`, `admin.coupon.create`,
|
||||
`admin.coupon.createReservedCoupon` (they check `ctx.staffUser?.id`).
|
||||
|
||||
**Fix:** add a `staffProcedure` (or a `ctx.staffUser` check) to every `admin.*`
|
||||
write.
|
||||
|
||||
**Pinned by:** `tests/api/authorization-matrix.test.ts`.
|
||||
|
||||
> **Fixed (FC-01/SEC-01), route removed:** the merged staff `admin.const.*` route is
|
||||
> gone. It had no production caller (the admin apps use `admin.region.*`, the
|
||||
> superadmin UI uses `superadmin.const.*`) and was the last place that could rebuild
|
||||
> every region's cache files on a region-key change, hand a staff token a merged read
|
||||
> of global constants, and accept bound-scope keys while silently dropping them.
|
||||
> Writes now go to the scope-specific routes, all of which are `staffProcedure` /
|
||||
> `superadminProcedure` and scope-checked (`assertConstantKeysInScope`).
|
||||
> `apps/backend/tests/helpers/consts.ts` reads/writes bound + region constants through
|
||||
> those routes; legacy constants have no staff-readable endpoint by design, so the api
|
||||
> tests no longer cover them. The remaining entries above are still open.
|
||||
|
||||
### 2. Public `admin.vendorSnippets` endpoints
|
||||
|
||||
`src/trpc/apis/admin-apis/apis/vendor-snippets.ts`
|
||||
|
||||
- `getUpcomingSlots:176? / 259` — `publicProcedure`
|
||||
- `getOrdersBySnippet:176` — `publicProcedure`, returns order/customer data for a snippet code
|
||||
- `getOrdersBySnippetAndSlot:275` — `publicProcedure`
|
||||
- `updateOrderItemPackaging:362` — `publicProcedure` with the staff check **commented out** (lines 355-360), so anyone can flip packaging state
|
||||
|
||||
**Fix:** require staff on all four.
|
||||
|
||||
**Pinned by:** `tests/api/authorization-matrix.test.ts`.
|
||||
|
||||
### 3. `user.auth.updateProfile` always throws
|
||||
|
||||
`src/trpc/apis/user-apis/apis/auth.ts:342`
|
||||
|
||||
```ts
|
||||
const authHeader = ctx.req.header('authorization');
|
||||
```
|
||||
|
||||
`ctx.req` is a fetch `Request` (see `src/app.ts` context: `{ req, c, ... }`),
|
||||
which has `.headers.get(...)`, not `.header(...)`. The call throws
|
||||
`TypeError: ctx.req.header is not a function`.
|
||||
|
||||
Worse, the profile update (`updateUserProfileInDb`) and the profile image URL
|
||||
resolving both run *before* line 342, so the write is committed and the client
|
||||
still receives an error — a silent partial success.
|
||||
|
||||
**Fix:** `ctx.req.headers.get('authorization')` (or use `ctx.c`).
|
||||
|
||||
**Pinned by:** `tests/api/misc-procedures.test.ts` — "pins: updateProfile
|
||||
crashes after writing the change".
|
||||
|
||||
> **Fixed (FC-15/AU-07):** `Context.req` is now typed as the fetch `Request` the
|
||||
> adapter actually passes, and `updateProfile` reads
|
||||
> `ctx.req.headers.get('authorization')`. The optional email was also relaxed:
|
||||
> an empty email means "no change" (the client only requires it when registering).
|
||||
|
||||
### 4. `user.auth.updatePassword` silently does nothing
|
||||
|
||||
`packages/db_helper_sqlite/src/user-apis/auth.ts:177` (`upsertUserPassword`)
|
||||
|
||||
```ts
|
||||
try {
|
||||
await db.insert(userCreds).values({ userId, userPassword: hashedPassword })
|
||||
return
|
||||
} catch (error) {
|
||||
if (error.code === '23505') { /* postgres unique violation -> UPDATE */ }
|
||||
throw error
|
||||
}
|
||||
```
|
||||
|
||||
`user_creds` has **no UNIQUE constraint on `user_id`** (schema: `id, user_id,
|
||||
user_password, created_at`), and `23505` is the *Postgres* unique-violation code
|
||||
— on D1 the insert simply succeeds. Result: a second credentials row is created,
|
||||
`getUserAuthCreds` keeps returning the original row, and the account's password
|
||||
never changes.
|
||||
|
||||
Verified: after "updating" the password, the **old password still logs in** and
|
||||
the new one is rejected; the user now has duplicate rows in `user_creds`.
|
||||
|
||||
**Fix:** add a UNIQUE index on `user_creds.user_id` and handle the SQLite
|
||||
constraint code, or do an explicit select-then-insert/update.
|
||||
|
||||
**Pinned by:** `tests/api/misc-procedures.test.ts` — "pins: updatePassword
|
||||
reports success but the old password still works".
|
||||
|
||||
> **Fixed (FC-16/AU-08):** `upsertUserPassword` now does an explicit
|
||||
> select-then-update-or-insert (updating every row for the user, which also
|
||||
> repairs existing duplicates), and a `uniqueIndex` on `user_creds.user_id` was
|
||||
> added to the schema. Existing duplicate rows must be deduped before the index
|
||||
> migration can be applied (the local DB has duplicates for users 379, 908, 1311).
|
||||
|
||||
---
|
||||
|
||||
## High — money
|
||||
|
||||
### 5. A ≥100% coupon produces a negative order total
|
||||
|
||||
`packages/db_helper_sqlite/src/user-apis/order.ts` (`applyDiscountToOrder`)
|
||||
|
||||
The percentage branch caps the discount at `maxValue * proportion` or `Infinity`
|
||||
and **never at `orderTotal`** (the flat branch does cap at the order total). A
|
||||
coupon with `discountPercent >= 100` and no `maxValue` therefore drives
|
||||
`orders.totalAmount` to zero or negative. `admin.coupon.create` accepts any
|
||||
`discountPercent` (no upper bound).
|
||||
|
||||
**Pinned by:** `tests/api/coupon-math.test.ts` — "pins: a 150% coupon produces a
|
||||
negative total".
|
||||
|
||||
### 6. The discount is applied to the delivery-inclusive base
|
||||
|
||||
`src/trpc/apis/user-apis/apis/order.ts:156`
|
||||
|
||||
```ts
|
||||
const orderTotalAmount = isFirstOrder ? subOrderTotalWithDelivery : subOrderTotal;
|
||||
```
|
||||
|
||||
`isFirstOrder` is true for the **first sub-order of every placeOrder call**, so
|
||||
that sub-order's discount is computed on `goods + deliveryCharge`. A percentage
|
||||
coupon therefore discounts the delivery fee as well.
|
||||
|
||||
**Pinned by:** `tests/api/coupon-math.test.ts` — "pins: a percentage coupon
|
||||
discounts the delivery fee too".
|
||||
|
||||
> **Fixed (FC-08):** `placeOrderUtil` now computes the coupon discount on the
|
||||
> whole cart **subtotal** and decides delivery on the **post-discount** total
|
||||
> (`finalTotal < freeDeliveryThreshold`), mirroring the customer app. A
|
||||
> percentage coupon no longer touches the delivery fee. (FC-07 is fixed too: the
|
||||
> threshold key is now `freeDeliveryThreshold`, not `minRegularOrderValue`.)
|
||||
|
||||
### 7. Money is never rounded
|
||||
|
||||
Nothing rounds `totalAmount`; it is written with `.toString()` on a raw float, so
|
||||
percentage discounts leave float noise (e.g. `999 - 15%`).
|
||||
|
||||
**Pinned by:** `tests/api/coupon-math.test.ts` — "pins: amounts are stored
|
||||
unrounded".
|
||||
|
||||
> **Fixed (coupon stacking):** coupon discounts are now rounded to the nearest
|
||||
> rupee in the shared `computeCartPricing` / `computeCouponStack`
|
||||
> (`packages/shared/cart-pricing.ts`) and multiple coupons stack **sequentially in
|
||||
> the order the customer applied them**. `orders.totalAmount` no longer carries
|
||||
> float noise.
|
||||
|
||||
---
|
||||
|
||||
## Medium — coupon rules
|
||||
|
||||
### 8. Coupon scoping is not enforced at placeOrder
|
||||
|
||||
`validateAndGetCoupon` checks invalidated / expiry / per-user limit / minOrder /
|
||||
first-order-only, but **not** `isUserBased`, `applicableUsers`, `skuIds` or
|
||||
`exclusiveApply`. Only the display endpoints (`getEligible` / `getMyCoupons`)
|
||||
filter by applicability, so user B can spend a coupon issued to user A by
|
||||
passing its id to `placeOrder`.
|
||||
|
||||
**Pinned by:** `tests/api/coupon-ux.test.ts` — "rejects user B applying a coupon
|
||||
issued to user A".
|
||||
|
||||
> **FIXED 2026-10-11:** `validateAndGetCoupons` now enforces, per coupon: user-based
|
||||
> applicability, `skuIds`/`coupon_applicable_products` product targeting (the coupon must
|
||||
> match at least one cart line, and `minOrder` compares against the targeted subtotal),
|
||||
> region (`coupons.regionId` null = global, else the order's region), and `exclusiveApply`
|
||||
> (an exclusive coupon cannot be combined with any other). The customer coupon list
|
||||
> (`getEligible`/`getMyCoupons`) is region-filtered too.
|
||||
|
||||
### 9. Cancelling an order does not release its coupon usage
|
||||
|
||||
`recordUserCouponUsage` runs at placement; `cancelOrderTransaction` never touches
|
||||
`coupon_usage`. A cancelled order permanently consumes a `maxLimitForUser` slot.
|
||||
|
||||
**Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: cancelling an
|
||||
order does not release its coupon usage".
|
||||
|
||||
> **FIXED 2026-10-11:** both cancel paths now delete the group's `coupon_usage`
|
||||
> row(s) once **every** sibling order sharing the `orderGroupId` is cancelled
|
||||
> (`releaseCouponUsageIfGroupFullyCancelled`, called from `cancelOrderTransaction`
|
||||
> and admin `cancelOrder`). A lone order counts as "all" and releases on cancel.
|
||||
> The lifecycle tests now assert the release.
|
||||
|
||||
### 10. A cancelled first order poisons an `isFirstOrderOnly` coupon
|
||||
|
||||
`getOrderCount` counts every order including cancelled ones, and
|
||||
`isUserBased`/first-order checks run off it — so placing and cancelling a first
|
||||
order permanently blocks a first-order-only coupon for that user.
|
||||
|
||||
**Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: a cancelled
|
||||
first order poisons an isFirstOrderOnly coupon".
|
||||
|
||||
> **FIXED 2026-10-11:** first-order eligibility now uses `countEffectiveOrders`
|
||||
> — distinct, non-cancelled order groups (a split placement counts once, a
|
||||
> cancelled order not at all). `getOrderCount` keeps its row-count meaning for
|
||||
> pagination. The lifecycle test now asserts the coupon still applies.
|
||||
|
||||
### 11. Reserved-coupon expiry is not checked at redemption — **FIXED 2026-10-10**
|
||||
|
||||
`redeemReservedCoupon` checked "already redeemed" and first-order-only, but not
|
||||
`validTill`, so an expired reserved code still redeemed (it only failed later at
|
||||
`placeOrder`) and the secret was burned for a dead coupon.
|
||||
|
||||
**Fix:** the redeem route now rejects `validTill < now` with "This coupon has
|
||||
expired" (policy: one deadline for both claiming the secret and spending the
|
||||
coupon), and `redeemReservedCoupon` claims the secret with a conditional update
|
||||
(`WHERE is_redeemed = 0`) before creating the coupon, so two customers racing the
|
||||
same code can no longer both receive one.
|
||||
|
||||
**Covered by:** `tests/api/coupon-ux.test.ts` — "rejects an expired reserved
|
||||
code" and "lets only one of two simultaneous claims win".
|
||||
|
||||
### 12. `exclusiveApply` is stored but never enforced
|
||||
|
||||
Coupons carry `exclusiveApply`, and `placeOrder` accepts a single `couponId`, so
|
||||
the flag has no effect anywhere. (Observation from reading the code; no runtime
|
||||
test.)
|
||||
|
||||
> **FIXED 2026-10-11:** orders now accept `couponIds: number[]` and
|
||||
> `validateAndGetCoupons` rejects any combination where one coupon is exclusive
|
||||
> (it must be the only coupon on the order).
|
||||
|
||||
---
|
||||
|
||||
## Medium — placeOrder guards
|
||||
|
||||
### 13. Out-of-stock products are still orderable
|
||||
|
||||
`placeOrderUtil` checks `isFlashAvailable` for flash orders but never
|
||||
`isOutOfStock`.
|
||||
|
||||
**Pinned by:** `tests/api/place-order-edge-cases.test.ts`.
|
||||
|
||||
> **Fixed (FC-03/SEC-05):** `placeOrderUtil` now rejects a product that is
|
||||
> `isDeleted`, `isOutOfStock` or `isSuspended` (400 "… is unavailable"). The
|
||||
> cross-region-SKU case (FC-02/SEC-04) is rejected too: the SKU's product
|
||||
> `regionId` must equal the order region (409).
|
||||
|
||||
### 14. An empty `selectedItems` list fails with a raw DB error
|
||||
|
||||
There is no `.min(1)` on `selectedItems`, so an empty list reaches Drizzle, which
|
||||
throws `values() must be called with at least one value` instead of returning a
|
||||
400.
|
||||
|
||||
**Pinned by:** `tests/api/place-order-edge-cases.test.ts`.
|
||||
|
||||
### 15. No quantity cap
|
||||
|
||||
`quantity` is `z.number().int().positive()` with no upper bound; `1_000_000`
|
||||
units are accepted.
|
||||
|
||||
**Pinned by:** `tests/api/place-order-edge-cases.test.ts`.
|
||||
|
||||
### 16. No slot validity checks
|
||||
|
||||
`placeOrder` only checks slot *capacity*. An inactive slot, a slot whose delivery
|
||||
time has already passed, and a slot that does not carry the ordered SKU are all
|
||||
accepted.
|
||||
|
||||
**Pinned by:** `tests/api/place-order-edge-cases.test.ts`.
|
||||
|
||||
> **Fixed (FC-03/SEC-05, FC-13/SL-04):** `placeOrderUtil` now requires a
|
||||
> non-null `slotId` for scheduled orders and validates the slot: it must exist,
|
||||
> belong to the order region (409), be `isActive`, have `freezeTime > now` and
|
||||
> `deliveryTime > now`, and carry every ordered `skuId` in `slot.skuIds` (400
|
||||
> otherwise).
|
||||
|
||||
### 17. No idempotency
|
||||
|
||||
Two identical `placeOrder` calls create two orders (`orderGroupId` is
|
||||
`Date.now()-userId`, with no uniqueness check).
|
||||
|
||||
**Pinned by:** `tests/api/place-order-edge-cases.test.ts`.
|
||||
|
||||
> **Mitigated client-side (FC-17/OR-12):** the Place Order button is disabled while a
|
||||
> submit is in flight and `handlePlaceOrder` early-returns via a synchronous `useRef`
|
||||
> guard, so an accidental double-tap cannot submit twice. **Server-side idempotency is
|
||||
> still absent** — a direct API replay or network retry can create duplicates. A
|
||||
> client-generated idempotency key remains the proper fix if/when wanted.
|
||||
|
||||
---
|
||||
|
||||
## Low — error handling / lifecycle
|
||||
|
||||
### 18. `cancelOrder` swallows every error into one generic message
|
||||
|
||||
`src/trpc/apis/user-apis/apis/order.ts:554-599` wraps the whole handler in a
|
||||
`try/catch` that rethrows `new ApiError("failed to cancel order")`, discarding
|
||||
the specific 404/400 messages it constructs ("Order not found", "Order is already
|
||||
cancelled", "Cannot cancel delivered order"). `updateUserNotes`, by contrast, has
|
||||
no catch and propagates its real messages.
|
||||
|
||||
**Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` and
|
||||
`tests/api/authorization-matrix.test.ts`.
|
||||
|
||||
### 19. No order status transition guards
|
||||
|
||||
`admin.order.updateDelivered` / `updatePackaged` accept any state: a cancelled
|
||||
order can be marked delivered, and delivered is reversible.
|
||||
|
||||
**Pinned by:** `tests/api/order-lifecycle-gaps.test.ts`.
|
||||
|
||||
### 20. `getUserDetails` breaks past ~110 orders
|
||||
|
||||
`admin.user.getUserDetails` builds an unchunked `IN (...)` over the user's order
|
||||
ids and fails once the history is large. Documented in
|
||||
`tests/api/admin-users.test.ts` (that suite uses a throwaway user to avoid it).
|
||||
|
||||
---
|
||||
|
||||
### 21. Bound pricing followed a client-supplied `boundId` — **FIXED 2026-10-10**
|
||||
|
||||
`placeOrderUtil` resolved the delivery charge and free-delivery threshold from
|
||||
`params.boundId ?? getEffectiveBoundId(regionId)`. `boundId` is a plain optional
|
||||
mutation input, and `getRegionSettingsForBound` only checked that the bound
|
||||
belongs to the **region** — never to the order's **address**. So an order against
|
||||
an address in bound 2 (₹200 / free above ₹800) could be placed with `boundId: 1`
|
||||
(₹20 / free above ₹300) and be charged ₹20. The address's own `boundId` was never
|
||||
read on this path.
|
||||
|
||||
**Fix (policy):** the delivery address's bound is authoritative —
|
||||
`address.boundId ?? params.boundId ?? getEffectiveBoundId(regionId)`. This mirrors
|
||||
the customer app, which already prices the selected address's bound
|
||||
(`apps/user-ui/src/hooks/prominent-api-hooks.ts` → `useGetEssentialConsts`), and
|
||||
keeps the bound-less-address fallback intact. Verified live: address 879 (bound 2)
|
||||
+ `boundId: 1` now charges ₹200 (was ₹20); a bound-less address still honours the
|
||||
client bound (₹20 for bound 1, ₹200 for bound 2).
|
||||
|
||||
**No regression test yet:** the suite has no bound fixtures and no superadmin
|
||||
session helper, so it cannot create a second bound to compare against.
|
||||
|
||||
---
|
||||
|
||||
### 22. Explicit rebalance dropped the delivery charge — **FIXED 2026-10-10**
|
||||
|
||||
`rebalanceSlots` repriced an order as `total = items(latest prices) − discount`,
|
||||
never adding `deliveryCharge` back — so every rebalanced order lost its fee from
|
||||
the payable (while the `delivery_charge` column kept the old value). It also
|
||||
re-derived the discount from the coupon's **current** state and looked it up per
|
||||
order, so invalidating/expiring a coupon silently raised a historical total, and
|
||||
multi-slot sub-orders (which own no `coupon_usage` row) lost their prorated
|
||||
discount entirely. Delivered and cancelled orders were repriced too.
|
||||
|
||||
**Fix (policy): freeze the historic discount and delivery fee; rebalance only
|
||||
product prices.** The charged discount is recovered from the stored row itself
|
||||
(`items + fee − total`), which is immune to later coupon changes and preserves a
|
||||
sub-order's prorated share; the fee is added back; delivered/cancelled orders are
|
||||
skipped; a SKU with no price for the region keeps its stored price instead of
|
||||
dropping to 0. Verified live: a no-op rebalance now leaves the payable untouched,
|
||||
an invalidated coupon no longer changes it, and repricing keeps
|
||||
`items − frozen discount + fee`.
|
||||
|
||||
**Known residue:** the customer/admin order **detail display** still recomputes
|
||||
the discount from the coupon, so after a reprice it can show a discount that
|
||||
differs from the frozen one (the payable is correct). Same family as the A23
|
||||
display decision; `db.transaction` is still the no-op stub, so the write loop is
|
||||
not atomic; money is still written unrounded (see #7). Orders rebalanced by the
|
||||
old code carry a phantom discount equal to the dropped fee and were not
|
||||
auto-repaired.
|
||||
|
||||
---
|
||||
|
||||
### 23. `updateProduct` stored unvalidated image keys — **FIXED 2026-10-10**
|
||||
|
||||
`createProduct` validated every referenced image
|
||||
(`skus.flatMap((s) => s.images)` → `assertUploadUrlsClaimable` → `claimUploadUrls`), but
|
||||
`updateProduct` validated only the declared `newImageUrls` and then wrote
|
||||
`skus[].images` straight through (`extractKeyFromPresignedUrl` → `updateProductInDb`)
|
||||
with no check and no claim. A fabricated key therefore produced a permanently
|
||||
broken image, and another product's already-claimed key could be silently reused
|
||||
(`createProduct` rejects that as "already used").
|
||||
|
||||
**Fix:** validate the *delta* — the keys the product does not already own (via a
|
||||
new `getProductImageKeys(regionId, productId)` helper) plus `newImageUrls` —
|
||||
before the write, and claim them after it. The product's own images may be
|
||||
re-sent by the edit form untouched. Verified live: fabricated key → rejected with
|
||||
nothing written; another product's claimed image → rejected; own image re-sent →
|
||||
200; genuine pending upload → 200 and claimed.
|
||||
|
||||
Banners, stores and global stores also convert URLs to keys without this guard,
|
||||
but the upload endpoint only issues the contexts
|
||||
`review | product_info | notification | complaint | profile | tags`, so those
|
||||
images are never registered in `upload_url_status` — guarding them would reject
|
||||
legitimate images.
|
||||
|
||||
---
|
||||
|
||||
### 24. Editing an address cleared its default flag — **FIXED 2026-10-10**
|
||||
|
||||
`user.address.updateAddress` forwarded `isDefault: isDefault || false` while the
|
||||
input schema declares `isDefault` **optional**. An edit that omitted the field —
|
||||
the natural partial update — therefore unset the address's default and left the
|
||||
user with **zero** default addresses. (`createAddress` computes
|
||||
`makeDefault = isDefault || no-other-addresses`, so it never had the bug; the
|
||||
AddressForm and checkout selector already send the current value, so the UI did
|
||||
not expose it.)
|
||||
|
||||
**Fix:** `isDefault: isDefault ?? existingAddress.isDefault` — omitted keeps the
|
||||
current value, explicit `true` sets it and clears the other addresses' defaults,
|
||||
explicit `false` still clears it.
|
||||
|
||||
**Related, still open:** explicitly sending `isDefault: false` (or deleting the
|
||||
only default address, see AD-08) can still leave a user with no default.
|
||||
|
||||
---
|
||||
|
||||
### 25. Address phone/pincode were unvalidated — **FIXED 2026-10-10**
|
||||
|
||||
`user.address.createAddress` / `updateAddress` accepted any non-empty string for
|
||||
`phone` and `pincode` (only `min(1)`), so `phone: "123"` and `pincode: "12"` were
|
||||
persisted. The app's form validated both client-side, so only a non-app client
|
||||
could store garbage — which is what the run did.
|
||||
|
||||
**Fix (rule):** phone = exactly 10 digits starting **6/7/8/9**; pincode = exactly
|
||||
6 digits, enforced in both procedures, with the UI's phone regex aligned. Verified
|
||||
live: `123` / `1234567890` / `5678901234` / 9-digit / 11-digit phones and 5-digit /
|
||||
7-digit / non-numeric pincodes all return **400**; a valid pair is accepted; the
|
||||
update path rejects too.
|
||||
|
||||
**Note:** zod-level input validation already surfaces as HTTP 400 — only
|
||||
`ApiError` throws are flattened to 500 (see #… / A19).
|
||||
|
||||
---
|
||||
|
||||
### 26. A user could delete their only address — **FIXED 2026-10-10**
|
||||
|
||||
`user.address.deleteAddress` guarded against an address attached to an ongoing
|
||||
order and against the **default** address, but nothing stopped the user deleting
|
||||
their **only** address — leaving an account with nowhere to deliver to (the same
|
||||
zero-address state that editing could reach, see #24). The refusals were also
|
||||
plain `Error`s, so they surfaced as HTTP 500.
|
||||
|
||||
**Fix (rule):** deleting the user's only address is refused with
|
||||
“This is your only address. Add another address before deleting this one.”, and
|
||||
the app shows it in a **BottomDialog** (checked before the “are you sure?” step
|
||||
and again from the mutation's `onError`). The other refusals now throw `ApiError`
|
||||
(409 / 404) so they reach the customer as 4xx.
|
||||
|
||||
**Still open:** explicitly sending `isDefault: false` for the last default can
|
||||
still leave an account with no default address.
|
||||
|
||||
---
|
||||
|
||||
### 27. `updateProductPrices` addressed SKUs as `productId` — **FIXED 2026-10-10**
|
||||
|
||||
`admin.product.updateProductPrices` took `updates[].productId`, but the helper
|
||||
validated it against `productSkus.id` and wrote `product_market_stats.skuId`. A
|
||||
product id therefore landed on whatever SKU carried the same number (product ids
|
||||
and SKU ids are separate, overlapping sequences), and the response still said
|
||||
“Updated prices for N **product(s)**”. An entry with no price field wrote nothing
|
||||
yet was counted as updated and reported as a success.
|
||||
|
||||
**Fix:** the input field is **`skuId`** (no alias), the messages say SKU, an entry
|
||||
with no price field is rejected up front
|
||||
(`No price fields to update for SKU(s): …`), and `updatedCount` counts rows actually written. The admin-ui and admin-web price screens were updated, along with
|
||||
three test payloads — `cache-invalidation.test.ts` had been passing a *product* id
|
||||
and only passed while the two ids happened to coincide.
|
||||
|
||||
**Residual (accepted):** id *values* still overlap, so a caller that passes a
|
||||
product id for `skuId` still hits the same-numbered SKU. That is now an explicit
|
||||
caller error rather than an API trap; mapping a product id to its SKUs is
|
||||
deliberately not done because that ambiguity is what caused the bug.
|
||||
|
||||
---
|
||||
|
||||
### 28. Business errors left tRPC as HTTP 500 — **FIXED 2026-10-10**
|
||||
|
||||
`errorLoggerMiddleware` translated our `ApiError` to a `TRPCError` inside a
|
||||
`try/catch` around `next()`. In tRPC 11 that catch is **unreachable for resolver
|
||||
errors**: `callRecursive` catches them and returns the middleware a
|
||||
`{ ok: false, error }` result, and `getTRPCErrorFromUnknown` has already wrapped a
|
||||
non-`TRPCError` as `INTERNAL_SERVER_ERROR` (keeping the original on `cause`) —
|
||||
which is why every business rejection arrived as HTTP 500 with the correct
|
||||
message.
|
||||
|
||||
**Fix:** the middleware now inspects the result and re-throws
|
||||
`translateResultError(result.error)`, which maps `result.error.cause` **only** when
|
||||
it is an `ApiError`, so zod `BAD_REQUEST`s, `UNAUTHORIZED`s and genuine 500s keep
|
||||
the code tRPC gave them. Verified live: 400 (expired reserved coupon, duplicate
|
||||
product name, bogus upload URL on product + tag, wrong-scope const writes on both
|
||||
admin and superadmin), 403 (capacity-full slot), 409 (only address, default
|
||||
address, address on an open order); controls unchanged (400 zod, 404 unknown
|
||||
procedure, 401 no token).
|
||||
|
||||
**Residual:** business rejections thrown as **plain `Error` inside the db-helper
|
||||
packages** still return 500 — `validateAndGetCoupon` (`not applicable`, `Coupon has
|
||||
expired`, invalidated, usage-limit, min-order, first-order-only) is the main one.
|
||||
Those need a status attached at the throw site (or a package-level ApiError).
|
||||
|
||||
---
|
||||
|
||||
### 29. Global products were visible but unusable — **FIXED 2026-10-10**
|
||||
|
||||
A product with `regionId = null` is **global**: every catalogue read path serves it in
|
||||
every region (`or(eq(productInfo.regionId, regionId), isNull(productInfo.regionId))` in
|
||||
`user-apis/stores.ts`, `admin-apis/product.ts`), so customers saw global products with a
|
||||
regional price. The write guards disagreed:
|
||||
|
||||
- `placeOrderUtil` (SEC-04) required `product.regionId === regionId` and its comment read
|
||||
*“a product with no region is treated as not available anywhere”* → ordering a global SKU
|
||||
failed with **409 `Product N is not available in this region`** (verified live with SKU 102).
|
||||
- `assertSkuIdsInRegion` in `slots.ts` / `banner.ts` / `coupon.ts` rejected a global SKU as
|
||||
*“belongs to a different region”* → a global product could not be attached to a region slot,
|
||||
and a scheduled order needs its SKU in the slot.
|
||||
|
||||
**Fix (rule):** a SKU is acceptable when its product's region is **`null` (global) or the target
|
||||
region**. `placeOrderUtil` now allows globals, and the three `assertSkuIdsInRegion` copies accept
|
||||
them. `admin-apis/product.ts` already allowed a global SKU inside a regional product.
|
||||
|
||||
**Verified live:** global SKU 102 attached to region-1 slot 2036 → 200; a scheduled order for it
|
||||
→ 200 (Basa Fish Fillets ₹498, free delivery above the threshold); a genuine region-2 SKU is still
|
||||
rejected when attached to a region-1 slot and at order time (409). The scheduled slot-SKU
|
||||
verification is unchanged.
|
||||
|
||||
**Not changed:** `admin-apis/vendor-snippets.ts` has the same assert but vendor snippets are
|
||||
deprecated/out of scope.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope (per request)
|
||||
|
||||
OTP (`sendOtp`/`verifyOtp`) and `deleteAccount` are deliberately untested and not
|
||||
listed here. Online payments were removed from the product (COD-only).
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
/**
|
||||
* Admin banner CRUD. `imageUrl` must be a URL; the backend extracts an object key
|
||||
* from it, so a plausible bucket URL is enough (nothing is uploaded here).
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
const IMAGE_URL = 'https://assets2.freshyo.in/banner-images/api-test.png'
|
||||
|
||||
describe('admin banner CRUD', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let bannerId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
})
|
||||
|
||||
it('getBanners returns a banners array', async () => {
|
||||
const res = await admin.admin.banner.getBanners.query()
|
||||
expect(Array.isArray(res.banners)).toBe(true)
|
||||
})
|
||||
|
||||
it('createBanner creates a banner that getBanner returns', async () => {
|
||||
const name = `API Test Banner ${Date.now()}`
|
||||
|
||||
const created = await admin.admin.banner.createBanner.mutate({
|
||||
name,
|
||||
imageUrl: IMAGE_URL,
|
||||
description: 'Created by API tests',
|
||||
})
|
||||
bannerId = (created as { id: number }).id
|
||||
|
||||
expect(bannerId).toBeGreaterThan(0)
|
||||
|
||||
const fetched = await admin.admin.banner.getBanner.query({ id: bannerId })
|
||||
expect(fetched?.name).toBe(name)
|
||||
})
|
||||
|
||||
it('updateBanner renames the banner', async () => {
|
||||
const name = `API Test Banner renamed ${Date.now()}`
|
||||
|
||||
await admin.admin.banner.updateBanner.mutate({ id: bannerId, name })
|
||||
|
||||
const fetched = await admin.admin.banner.getBanner.query({ id: bannerId })
|
||||
expect(fetched?.name).toBe(name)
|
||||
})
|
||||
|
||||
it('deleteBanner removes it', async () => {
|
||||
const res = await admin.admin.banner.deleteBanner.mutate({ id: bannerId })
|
||||
expect(res.success).toBe(true)
|
||||
|
||||
const fetched = await admin.admin.banner.getBanner.query({ id: bannerId })
|
||||
expect(fetched).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
/**
|
||||
* Admin read/update surface: store, product, groups, coupons, vendor snippets
|
||||
* and complaints — all with the staff token.
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import { createStoreWithSku, type StoreWithSku } from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
describe('admin catalog surface', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let store: StoreWithSku
|
||||
let staffId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
staffId = staff.staffId
|
||||
admin = apiClient(staff.token)
|
||||
store = await createStoreWithSku()
|
||||
})
|
||||
|
||||
it('getStoreById returns the created store', async () => {
|
||||
const res = await admin.admin.store.getStoreById.query({ id: store.storeId })
|
||||
expect(res.store?.id).toBe(store.storeId)
|
||||
})
|
||||
|
||||
it('updateStore renames the store', async () => {
|
||||
const name = `${store.storeName} (renamed)`
|
||||
|
||||
await admin.admin.store.updateStore.mutate({
|
||||
id: store.storeId,
|
||||
name,
|
||||
owner: staffId,
|
||||
description: 'Renamed by API tests',
|
||||
})
|
||||
|
||||
const after = await admin.admin.store.getStoreById.query({ id: store.storeId })
|
||||
expect(after.store.name).toBe(name)
|
||||
})
|
||||
|
||||
it('getProductById returns the product with its SKU', async () => {
|
||||
const res = (await admin.admin.product.getProductById.query({
|
||||
id: store.productId,
|
||||
})) as {
|
||||
product?: { id: number; skus?: { id: number }[] }
|
||||
id?: number
|
||||
skus?: { id: number }[]
|
||||
}
|
||||
const product = res.product ?? res
|
||||
|
||||
expect(product.id).toBe(store.productId)
|
||||
expect(product.skus!.some((s) => s.id === store.skuId)).toBe(true)
|
||||
})
|
||||
|
||||
it('updateProduct renames the product', async () => {
|
||||
const name = `${store.productName} (renamed)`
|
||||
|
||||
await admin.admin.product.updateProduct.mutate({
|
||||
id: store.productId,
|
||||
name,
|
||||
storeId: store.storeId,
|
||||
productType: 'item',
|
||||
skus: [
|
||||
{
|
||||
id: store.skuId,
|
||||
price: 199,
|
||||
// The backend requires a feature literally named "quantity".
|
||||
features: [{ featureName: 'quantity', featureValue: '1pc' }],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
// Read back through the list — a known shape.
|
||||
const list = await admin.admin.product.getProducts.query()
|
||||
const product = list.products.find((p) => p.id === store.productId)
|
||||
expect(product?.name).toBe(name)
|
||||
})
|
||||
|
||||
it('getGroups lists product groups', async () => {
|
||||
const res = await admin.admin.product.getGroups.query()
|
||||
expect(Array.isArray(res.groups)).toBe(true)
|
||||
})
|
||||
|
||||
it('createGroup adds a group that getGroups returns', async () => {
|
||||
const groupName = `API Test Group ${Date.now()}`
|
||||
|
||||
await admin.admin.product.createGroup.mutate({
|
||||
group_name: groupName,
|
||||
description: 'Created by API tests',
|
||||
product_ids: [store.skuId],
|
||||
})
|
||||
|
||||
const res = await admin.admin.product.getGroups.query()
|
||||
const names = res.groups.map(
|
||||
(g: { groupName?: string; group_name?: string }) => g.groupName ?? g.group_name
|
||||
)
|
||||
expect(names).toContain(groupName)
|
||||
})
|
||||
|
||||
it('coupon.getAll returns a coupons array', async () => {
|
||||
const res = await admin.admin.coupon.getAll.query({ limit: 5 })
|
||||
expect(Array.isArray(res.coupons)).toBe(true)
|
||||
})
|
||||
|
||||
it('vendorSnippets.getAll returns an array', async () => {
|
||||
const res = await admin.admin.vendorSnippets.getAll.query()
|
||||
expect(Array.isArray(res)).toBe(true)
|
||||
})
|
||||
|
||||
it('complaint.getAll returns a complaints array', async () => {
|
||||
const res = await admin.admin.complaint.getAll.query({ limit: 10 })
|
||||
expect(Array.isArray(res.complaints)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,136 +0,0 @@
|
|||
/**
|
||||
* Admin ops: config round-trip, group/product/store lifecycle, and two orders
|
||||
* placed concurrently.
|
||||
*/
|
||||
|
||||
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
|
||||
import { getRegionConstants, setRegionConst } from '../helpers/consts'
|
||||
import { createFutureSlot, createStoreWithSku, ensureUserAddress } from '../helpers/fixtures'
|
||||
import { staffSession, userSession } from '../helpers/sessions'
|
||||
|
||||
describe('admin ops', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let user: ReturnType<typeof apiClient>
|
||||
let staffId = 0
|
||||
let skuId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
staffId = staff.staffId
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const session = await userSession()
|
||||
user = apiClient(session.token)
|
||||
|
||||
// A suspended user is rejected by placeOrder — make sure the shared test user
|
||||
// is active regardless of what other suites left behind.
|
||||
await admin.admin.user.updateUserSuspension.mutate({
|
||||
userId: session.userId,
|
||||
isSuspended: false,
|
||||
})
|
||||
|
||||
const store = await createStoreWithSku()
|
||||
skuId = store.skuId
|
||||
})
|
||||
|
||||
it('round-trips a region constant through updateRegionConstants', async () => {
|
||||
const before = await getRegionConstants()
|
||||
const original = before.welcomeMessage
|
||||
const next = `API welcome ${uniqueSuffix()}`
|
||||
|
||||
await setRegionConst('welcomeMessage', next)
|
||||
expect((await getRegionConstants()).welcomeMessage).toBe(next)
|
||||
|
||||
// Restore whatever the region had (a string, or no row at all).
|
||||
await setRegionConst('welcomeMessage', typeof original === 'string' ? original : null)
|
||||
})
|
||||
|
||||
it('updates and deletes a product group', async () => {
|
||||
const base = `API Group ${uniqueSuffix()}`
|
||||
const renamed = `${base} renamed`
|
||||
|
||||
const created = (await admin.admin.product.createGroup.mutate({
|
||||
group_name: base,
|
||||
product_ids: [skuId],
|
||||
})) as { group?: { id: number }; id?: number }
|
||||
const groupId = created.group?.id ?? created.id
|
||||
expect(groupId).toBeGreaterThan(0)
|
||||
|
||||
await admin.admin.product.updateGroup.mutate({ id: groupId!, group_name: renamed })
|
||||
|
||||
const groups = await admin.admin.product.getGroups.query()
|
||||
const name = (g: { groupName?: string; group_name?: string }) =>
|
||||
g.groupName ?? g.group_name
|
||||
expect(groups.groups.some((g) => name(g) === renamed)).toBe(true)
|
||||
|
||||
await admin.admin.product.deleteGroup.mutate({ id: groupId! })
|
||||
|
||||
const after = await admin.admin.product.getGroups.query()
|
||||
expect(after.groups.some((g: { id: number }) => g.id === groupId)).toBe(false)
|
||||
})
|
||||
|
||||
it('deleteProduct rejects for a product that still has SKUs', async () => {
|
||||
// The delete is a hard `delete from product_info`, which fails on the FK from
|
||||
// the product's SKUs/market stats — so a product cannot be deleted this way.
|
||||
const target = await createStoreWithSku()
|
||||
|
||||
const error = await captureError(() =>
|
||||
admin.admin.product.deleteProduct.mutate({ id: target.productId })
|
||||
)
|
||||
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
})
|
||||
|
||||
it('deletes a store', async () => {
|
||||
const created = (await admin.admin.store.createStore.mutate({
|
||||
name: `API Store to delete ${uniqueSuffix()}`,
|
||||
owner: staffId,
|
||||
})) as { store?: { id: number } }
|
||||
const storeId = created.store!.id
|
||||
|
||||
// NOTE: the input field is `storeId`, not `id`.
|
||||
const res = await admin.admin.store.deleteStore.mutate({ storeId })
|
||||
expect(res).toBeTruthy()
|
||||
|
||||
const error = await captureError(() =>
|
||||
admin.admin.store.getStoreById.query({ id: storeId })
|
||||
)
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
})
|
||||
|
||||
it('rejects deleting a store that still has products', async () => {
|
||||
const target = await createStoreWithSku()
|
||||
|
||||
const error = await captureError(() =>
|
||||
admin.admin.store.deleteStore.mutate({ storeId: target.storeId })
|
||||
)
|
||||
expect(error.message).toMatch(/still has products/i)
|
||||
|
||||
// The store (and its products) are untouched.
|
||||
const still = await admin.admin.store.getStoreById.query({ id: target.storeId })
|
||||
expect(still).toBeTruthy()
|
||||
})
|
||||
|
||||
it('places two concurrent orders for different slots', async () => {
|
||||
const slotA = await createFutureSlot([skuId], { deliveryInHours: 4, freezeInHours: 3 })
|
||||
const slotB = await createFutureSlot([skuId], { deliveryInHours: 8, freezeInHours: 7 })
|
||||
const address = await ensureUserAddress()
|
||||
|
||||
const [a, b] = await Promise.all([
|
||||
user.user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId: slotA.slotId }],
|
||||
addressId: address.addressId,
|
||||
regionId: 1,
|
||||
}),
|
||||
user.user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId: slotB.slotId }],
|
||||
addressId: address.addressId,
|
||||
regionId: 1,
|
||||
}),
|
||||
])
|
||||
|
||||
expect(a.data[0].id).toBeGreaterThan(0)
|
||||
expect(b.data[0].id).toBeGreaterThan(0)
|
||||
expect(a.data[0].id).not.toBe(b.data[0].id)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
/**
|
||||
* Admin order operations and their user-visible effect.
|
||||
*
|
||||
* `admin.order.*` uses a mix of numeric and string ids:
|
||||
* getOrderDetails / updateNotes / removeDeliveryCharge / cancelOrder -> orderId: number
|
||||
* updatePackaged / updateDelivered / getSlotOrders -> orderId/slotId: string
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import { createFutureSlot, createStoreWithSku, ensureUserAddress } from '../helpers/fixtures'
|
||||
import { staffSession, userSession } from '../helpers/sessions'
|
||||
|
||||
describe('admin order operations', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let user: ReturnType<typeof apiClient>
|
||||
let orderId = 0
|
||||
let skuId = 0
|
||||
let slotId = 0
|
||||
let addressId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const store = await createStoreWithSku()
|
||||
const slot = await createFutureSlot([store.skuId])
|
||||
const address = await ensureUserAddress()
|
||||
const session = await userSession()
|
||||
user = apiClient(session.token)
|
||||
|
||||
skuId = store.skuId
|
||||
slotId = slot.slotId
|
||||
addressId = address.addressId
|
||||
|
||||
const placed = await user.user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||
addressId,
|
||||
})
|
||||
orderId = placed.data[0].id
|
||||
})
|
||||
|
||||
it('getAll returns recent orders', async () => {
|
||||
const res = await admin.admin.order.getAll.query({ limit: 5 })
|
||||
expect(Array.isArray(res?.orders)).toBe(true)
|
||||
})
|
||||
|
||||
it('getOrderDetails returns the order', async () => {
|
||||
const details = (await admin.admin.order.getOrderDetails.query({ orderId })) as {
|
||||
id?: number
|
||||
}
|
||||
|
||||
expect(details).toBeTruthy()
|
||||
if (details.id != null) expect(details.id).toBe(orderId)
|
||||
})
|
||||
|
||||
it('getSlotOrders lists the orders for a slot (string slotId)', async () => {
|
||||
const res = await admin.admin.order.getSlotOrders.query({ slotId: String(slotId) })
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
it('updateNotes stores admin notes on the order', async () => {
|
||||
const notes = `Admin note ${Date.now()}`
|
||||
|
||||
await admin.admin.order.updateNotes.mutate({ orderId, adminNotes: notes })
|
||||
|
||||
const details = (await admin.admin.order.getOrderDetails.query({ orderId })) as {
|
||||
adminNotes?: string
|
||||
}
|
||||
if (details.adminNotes != null) expect(details.adminNotes).toBe(notes)
|
||||
})
|
||||
|
||||
it('marks the order packaged', async () => {
|
||||
const res = await admin.admin.order.updatePackaged.mutate({
|
||||
orderId: String(orderId),
|
||||
isPackaged: true,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
})
|
||||
|
||||
it('marks the order delivered and the user sees deliveryStatus "success"', async () => {
|
||||
const res = await admin.admin.order.updateDelivered.mutate({
|
||||
orderId: String(orderId),
|
||||
isDelivered: true,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
|
||||
const detail = await user.user.order.getOrderById.query({ orderId: String(orderId) })
|
||||
expect(String(detail.deliveryStatus).toLowerCase()).toBe('success')
|
||||
})
|
||||
|
||||
it('removes the delivery charge', async () => {
|
||||
await admin.admin.order.removeDeliveryCharge.mutate({ orderId })
|
||||
|
||||
const detail = await user.user.order.getOrderById.query({ orderId: String(orderId) })
|
||||
expect(Number(detail.deliveryCharge)).toBe(0)
|
||||
})
|
||||
|
||||
it('updates the address coordinates', async () => {
|
||||
const res = await admin.admin.order.updateAddressCoords.mutate({
|
||||
addressId,
|
||||
latitude: 16.7488,
|
||||
longitude: 77.9852,
|
||||
})
|
||||
expect(res).toBeTruthy()
|
||||
|
||||
// NOTE: the coordinates set here are not exposed by the user-facing
|
||||
// `address.getUserAddresses` read (latitude comes back null/0), so the
|
||||
// contract under test is the mutation succeeding + the address surviving.
|
||||
const addresses = await user.user.address.getUserAddresses.query()
|
||||
expect(addresses.data.some((a) => a.id === addressId)).toBe(true)
|
||||
})
|
||||
|
||||
it('cancels a fresh order as staff and the user sees it cancelled', async () => {
|
||||
// The main order above is already delivered, which admin cancel refuses —
|
||||
// so place a new one to cancel.
|
||||
const placed = await user.user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||
addressId,
|
||||
})
|
||||
const freshOrderId = placed.data[0].id
|
||||
|
||||
await admin.admin.order.cancelOrder.mutate({
|
||||
orderId: freshOrderId,
|
||||
reason: `Cancelled by API test ${Date.now()}`,
|
||||
})
|
||||
|
||||
const detail = await user.user.order.getOrderById.query({
|
||||
orderId: String(freshOrderId),
|
||||
})
|
||||
expect(String(detail.orderStatus).toLowerCase()).toMatch(/cancel/)
|
||||
})
|
||||
|
||||
it('rebalances the orders for a slot', async () => {
|
||||
const res = await admin.admin.order.rebalanceSlots.mutate({ slotIds: [slotId] })
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
/**
|
||||
* Admin product-tag CRUD.
|
||||
*/
|
||||
|
||||
import { apiClient, uniqueSuffix } from '../helpers/api'
|
||||
import { createStoreWithSku } from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
describe('admin product tag CRUD', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let tagId = 0
|
||||
let tagName = ''
|
||||
let skuId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const store = await createStoreWithSku()
|
||||
skuId = store.skuId
|
||||
})
|
||||
|
||||
it('creates a tag that getProductTags returns', async () => {
|
||||
tagName = `API Tag ${uniqueSuffix()}`
|
||||
|
||||
const created = await admin.admin.product.createProductTag.mutate({
|
||||
tagName,
|
||||
tagDescription: 'Created by API tests',
|
||||
isDashboardTag: true,
|
||||
})
|
||||
tagId = (created as { tag: { id: number } }).tag.id
|
||||
expect(tagId).toBeGreaterThan(0)
|
||||
|
||||
const list = await admin.admin.product.getProductTags.query()
|
||||
const tags = Array.isArray(list)
|
||||
? list
|
||||
: ((list as { tags?: { id: number }[] }).tags ?? [])
|
||||
expect(tags.some((t) => t.id === tagId)).toBe(true)
|
||||
})
|
||||
|
||||
it('getProductTagById returns the tag', async () => {
|
||||
const tag = (await admin.admin.product.getProductTagById.query({
|
||||
id: tagId,
|
||||
})) as unknown as { tag?: { tagName: string }; tagName?: string }
|
||||
const resolved = tag.tag ?? tag
|
||||
expect(resolved.tagName).toBe(tagName)
|
||||
})
|
||||
|
||||
it('updateProductTag renames the tag', async () => {
|
||||
const renamed = `${tagName} renamed`
|
||||
|
||||
await admin.admin.product.updateProductTag.mutate({ id: tagId, tagName: renamed })
|
||||
|
||||
const tag = (await admin.admin.product.getProductTagById.query({
|
||||
id: tagId,
|
||||
})) as unknown as { tag?: { tagName: string }; tagName?: string }
|
||||
const resolved = tag.tag ?? tag
|
||||
expect(resolved.tagName).toBe(renamed)
|
||||
})
|
||||
|
||||
it('deleteProductTag removes it', async () => {
|
||||
const res = await admin.admin.product.deleteProductTag.mutate({ id: tagId })
|
||||
expect((res as { message?: string }).message ?? '').toMatch(/deleted/i)
|
||||
|
||||
const list = await admin.admin.product.getProductTags.query()
|
||||
const tags = Array.isArray(list)
|
||||
? list
|
||||
: ((list as { tags?: { id: number }[] }).tags ?? [])
|
||||
expect(tags.some((t) => t.id === tagId)).toBe(false)
|
||||
})
|
||||
|
||||
it('deleteProductTag removes a tag that has products', async () => {
|
||||
const created = await admin.admin.product.createProductTag.mutate({
|
||||
tagName: `API Tag w/ product ${uniqueSuffix()}`,
|
||||
isDashboardTag: true,
|
||||
productIds: [skuId],
|
||||
})
|
||||
const id = (created as { tag: { id: number } }).tag.id
|
||||
|
||||
const res = await admin.admin.product.deleteProductTag.mutate({ id })
|
||||
expect((res as { message?: string }).message ?? '').toMatch(/deleted/i)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,109 +0,0 @@
|
|||
/**
|
||||
* Admin user management: listing, details, incidents, notification audience,
|
||||
* suspension and the staff list.
|
||||
*
|
||||
* Per-user endpoints are exercised against a freshly registered user rather than
|
||||
* the shared test account: `getUserDetails` builds an unchunked `IN (...)` over
|
||||
* the user's order ids and fails once that history is large (~110 orders), which
|
||||
* the shared account has accumulated from repeated runs. (Documented finding.)
|
||||
*
|
||||
* sendNotification targets a user with no push token, so nothing is delivered.
|
||||
*/
|
||||
|
||||
import { apiClient, uniqueSuffix } from '../helpers/api'
|
||||
import { registerThrowawayUser } from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
describe('admin user management', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let staffId = 0
|
||||
let subjectUserId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
staffId = staff.staffId
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const subject = await registerThrowawayUser()
|
||||
subjectUserId = subject.userId
|
||||
})
|
||||
|
||||
it('getEssentials returns the dashboard counters', async () => {
|
||||
const res = await admin.admin.user.getEssentials.query()
|
||||
expect(typeof res.unresolvedComplaints).toBe('number')
|
||||
})
|
||||
|
||||
it('getAllUsers returns users', async () => {
|
||||
const res = await admin.admin.user.getAllUsers.query({ limit: 5 })
|
||||
expect(Array.isArray(res.users)).toBe(true)
|
||||
})
|
||||
|
||||
it('getUserDetails returns the user', async () => {
|
||||
const res = await admin.admin.user.getUserDetails.query({ userId: subjectUserId })
|
||||
const user = (res as { user?: { id: number }; id?: number }).user ?? res
|
||||
expect((user as { id: number }).id).toBe(subjectUserId)
|
||||
})
|
||||
|
||||
it('getStaff lists the staff (including the logged-in one)', async () => {
|
||||
const res = (await admin.admin.staffUser.getStaff.query()) as
|
||||
| { id: number }[]
|
||||
| { staff?: { id: number }[] }
|
||||
const list = Array.isArray(res) ? res : (res.staff ?? [])
|
||||
|
||||
expect(list.some((s) => s.id === staffId)).toBe(true)
|
||||
})
|
||||
|
||||
it('adds a user incident that getUserIncidents returns', async () => {
|
||||
const comment = `API test incident ${uniqueSuffix()}`
|
||||
|
||||
await admin.admin.user.addUserIncident.mutate({
|
||||
userId: subjectUserId,
|
||||
adminComment: comment,
|
||||
})
|
||||
|
||||
const res = await admin.admin.user.getUserIncidents.query({ userId: subjectUserId })
|
||||
expect(Array.isArray(res.incidents)).toBe(true)
|
||||
expect(
|
||||
res.incidents.some((i: { adminComment: string | null }) => i.adminComment === comment)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('getUsersForNotification returns a users array', async () => {
|
||||
const res = await admin.admin.user.getUsersForNotification.query({ search: '' })
|
||||
expect(Array.isArray(res.users)).toBe(true)
|
||||
})
|
||||
|
||||
it('suspends and unsuspends the user', async () => {
|
||||
const suspendedFlag = async () => {
|
||||
const res = (await admin.admin.user.getUserDetails.query({
|
||||
userId: subjectUserId,
|
||||
})) as { isSuspended?: boolean; user?: { isSuspended?: boolean } }
|
||||
return res.isSuspended ?? res.user?.isSuspended
|
||||
}
|
||||
|
||||
await admin.admin.user.updateUserSuspension.mutate({
|
||||
userId: subjectUserId,
|
||||
isSuspended: true,
|
||||
})
|
||||
|
||||
try {
|
||||
expect(await suspendedFlag()).toBe(true)
|
||||
} finally {
|
||||
await admin.admin.user.updateUserSuspension.mutate({
|
||||
userId: subjectUserId,
|
||||
isSuspended: false,
|
||||
})
|
||||
}
|
||||
|
||||
expect(await suspendedFlag()).toBe(false)
|
||||
})
|
||||
|
||||
it('sendNotification tolerates a recipient with no push token', async () => {
|
||||
const res = await admin.admin.user.sendNotification.mutate({
|
||||
userIds: [subjectUserId],
|
||||
title: 'API test',
|
||||
text: 'No-op recipient',
|
||||
})
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
/**
|
||||
* Admin vendor-snippet CRUD (+ the orders-per-snippet report).
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import { createFutureSlot, createStoreWithSku } from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
describe('admin vendor snippet CRUD', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let snippetId = 0
|
||||
let snippetCode = ''
|
||||
let skuId = 0
|
||||
let slotId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const store = await createStoreWithSku()
|
||||
const slot = await createFutureSlot([store.skuId])
|
||||
skuId = store.skuId
|
||||
slotId = slot.slotId
|
||||
})
|
||||
|
||||
it('creates a snippet that getAll returns', async () => {
|
||||
const code = `APISNIP${Date.now().toString(36)}`.toUpperCase()
|
||||
|
||||
// getOrdersBySnippet resolves orders through the snippet's slot, so link one.
|
||||
const created = (await admin.admin.vendorSnippets.create.mutate({
|
||||
snippetCode: code,
|
||||
slotId,
|
||||
skuIds: [skuId],
|
||||
isPermanent: true,
|
||||
})) as { id: number; snippetCode: string }
|
||||
|
||||
snippetId = created.id
|
||||
snippetCode = created.snippetCode
|
||||
expect(snippetId).toBeGreaterThan(0)
|
||||
expect(snippetCode).toBeTruthy()
|
||||
|
||||
const all = await admin.admin.vendorSnippets.getAll.query()
|
||||
expect(all.some((s) => s.id === snippetId)).toBe(true)
|
||||
})
|
||||
|
||||
it('updates the snippet', async () => {
|
||||
await admin.admin.vendorSnippets.update.mutate({
|
||||
id: snippetId,
|
||||
updates: { validTill: new Date(Date.now() + 24 * 3600_000).toISOString() },
|
||||
})
|
||||
|
||||
const all = await admin.admin.vendorSnippets.getAll.query()
|
||||
expect(all.some((s) => s.id === snippetId)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns the orders for the snippet code', async () => {
|
||||
const res = await admin.admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode,
|
||||
})
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
it('deletes the snippet', async () => {
|
||||
const res = await admin.admin.vendorSnippets.delete.mutate({ id: snippetId })
|
||||
expect((res as { message?: string }).message ?? '').toMatch(/deleted/i)
|
||||
|
||||
const all = await admin.admin.vendorSnippets.getAll.query()
|
||||
expect(all.some((s) => s.id === snippetId)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
/**
|
||||
* Admin (staff) surface: the created fixtures are visible to the admin APIs.
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import {
|
||||
createFutureSlot,
|
||||
createStoreWithSku,
|
||||
type CreatedSlot,
|
||||
type StoreWithSku,
|
||||
} from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
describe('admin API surface', () => {
|
||||
let store: StoreWithSku
|
||||
let slot: CreatedSlot
|
||||
|
||||
beforeAll(async () => {
|
||||
store = await createStoreWithSku()
|
||||
slot = await createFutureSlot([store.skuId])
|
||||
})
|
||||
|
||||
it('admin.product.getProducts includes the created SKU', async () => {
|
||||
const staff = await staffSession()
|
||||
const { products } = await apiClient(staff.token).admin.product.getProducts.query()
|
||||
|
||||
const product = products.find((p) => p.id === store.productId)
|
||||
expect(product).toBeDefined()
|
||||
expect(product!.skus.some((sku) => sku.id === store.skuId)).toBe(true)
|
||||
})
|
||||
|
||||
it('admin.slots.getAll returns slots (capped at 20) and the public list has ours', async () => {
|
||||
const staff = await staffSession()
|
||||
const result = await apiClient(staff.token).admin.slots.getAll.query()
|
||||
|
||||
const list = Array.isArray(result)
|
||||
? result
|
||||
: ((result as { slots?: { id: number }[] })?.slots ?? [])
|
||||
|
||||
expect(list.length).toBeGreaterThan(0)
|
||||
// getAll only returns the first 20 slots, and this suite leaves data behind,
|
||||
// so membership is asserted against the unbounded public list instead.
|
||||
expect(list.length).toBeLessThanOrEqual(20)
|
||||
|
||||
const publicSlots = await apiClient().user.slots.getSlots.query({ regionId: 1 })
|
||||
expect(publicSlots.slots.some((s) => s.id === slot.slotId)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
/**
|
||||
* Auth: log in with the credentials from tests/.env and use the issued tokens.
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import { staffSession, userSession } from '../helpers/sessions'
|
||||
|
||||
describe('auth tokens', () => {
|
||||
it('staff login returns a token and staff id', async () => {
|
||||
const staff = await staffSession()
|
||||
|
||||
expect(typeof staff.token).toBe('string')
|
||||
expect(staff.token.length).toBeGreaterThan(10)
|
||||
expect(staff.staffId).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('user login returns a token and user id', async () => {
|
||||
const user = await userSession()
|
||||
|
||||
expect(typeof user.token).toBe('string')
|
||||
expect(user.token.length).toBeGreaterThan(10)
|
||||
expect(user.userId).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('each token authenticates its own protected procedures', async () => {
|
||||
const [staff, user] = await Promise.all([staffSession(), userSession()])
|
||||
|
||||
const products = await apiClient(staff.token).admin.product.getProducts.query()
|
||||
expect(Array.isArray(products.products)).toBe(true)
|
||||
|
||||
const addresses = await apiClient(user.token).user.address.getUserAddresses.query()
|
||||
expect(Array.isArray(addresses.data)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,258 +0,0 @@
|
|||
/**
|
||||
* Authorization boundaries across the two token kinds.
|
||||
*
|
||||
* `protectedProcedure` only requires *some* identity (ctx.user OR ctx.staffUser),
|
||||
* so every admin procedure that does not additionally check `ctx.staffUser` is
|
||||
* reachable with a plain user token. The "pins: a user token CAN ..." tests
|
||||
* document that gap; the staff-guarded ones assert the rejection.
|
||||
*
|
||||
* See tests/BUGS.md.
|
||||
*/
|
||||
|
||||
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
|
||||
import {
|
||||
createFutureSlot,
|
||||
createStoreWithSku,
|
||||
registerThrowawayUser,
|
||||
registerUserWithAddress,
|
||||
} from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
describe('authorization matrix', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let userToken = ''
|
||||
let otherToken = ''
|
||||
let addressId = 0
|
||||
let skuId = 0
|
||||
let slotId = 0
|
||||
let orderId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const store = await createStoreWithSku()
|
||||
const slot = await createFutureSlot([store.skuId])
|
||||
const owner = await registerUserWithAddress()
|
||||
const other = await registerUserWithAddress()
|
||||
|
||||
userToken = owner.token
|
||||
otherToken = other.token
|
||||
addressId = owner.addressId
|
||||
skuId = store.skuId
|
||||
slotId = slot.slotId
|
||||
|
||||
const placed = await apiClient(userToken).user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||
addressId,
|
||||
})
|
||||
orderId = placed.data[0].id
|
||||
})
|
||||
|
||||
describe('admin procedures guarded only by protectedProcedure', () => {
|
||||
it('pins: a user token CAN cancel an order via admin.order.cancelOrder', async () => {
|
||||
const res = await apiClient(userToken).admin.order.cancelOrder.mutate({
|
||||
orderId,
|
||||
reason: 'authorization matrix pin',
|
||||
})
|
||||
|
||||
expect(res.success).toBe(true)
|
||||
|
||||
const detail = await apiClient(userToken).user.order.getOrderById.query({
|
||||
orderId: String(orderId),
|
||||
})
|
||||
expect(String(detail.orderStatus).toLowerCase()).toMatch(/cancel/)
|
||||
})
|
||||
|
||||
it('pins: a user token CAN suspend a user via admin.user.updateUserSuspension', async () => {
|
||||
const victim = await registerThrowawayUser()
|
||||
|
||||
try {
|
||||
const res = await apiClient(userToken).admin.user.updateUserSuspension.mutate({
|
||||
userId: victim.userId,
|
||||
isSuspended: true,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
} finally {
|
||||
await admin.admin.user.updateUserSuspension.mutate({
|
||||
userId: victim.userId,
|
||||
isSuspended: false,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('pins: a user token CAN send a notification via admin.user.sendNotification', async () => {
|
||||
const target = await registerThrowawayUser()
|
||||
|
||||
const res = await apiClient(userToken).admin.user.sendNotification.mutate({
|
||||
userIds: [target.userId],
|
||||
title: 'API test',
|
||||
text: 'authorization matrix pin',
|
||||
})
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
it('pins: a user token CAN toggle stock via admin.product.toggleOutOfStock', async () => {
|
||||
const target = await createStoreWithSku()
|
||||
|
||||
try {
|
||||
const res = await apiClient(userToken).admin.product.toggleOutOfStock.mutate({
|
||||
id: target.productId,
|
||||
})
|
||||
expect(res.isOutOfStock).toBe(true)
|
||||
} finally {
|
||||
await admin.admin.product.toggleOutOfStock.mutate({ id: target.productId })
|
||||
}
|
||||
})
|
||||
|
||||
it('pins: a user token CAN create a staff account (admin.staffUser.createStaffUser)', async () => {
|
||||
const roles = await apiClient(userToken).admin.staffUser.getRoles.query()
|
||||
const roleId = roles.roles[0]?.id
|
||||
expect(roleId).toBeGreaterThan(0)
|
||||
|
||||
const name = `matrix-staff-${uniqueSuffix()}`
|
||||
|
||||
const res = await apiClient(userToken).admin.staffUser.createStaffUser.mutate({
|
||||
name,
|
||||
password: 'Passw0rd!',
|
||||
roleId,
|
||||
})
|
||||
expect(res).toBeTruthy()
|
||||
|
||||
// It really is a usable staff account.
|
||||
const login = await apiClient().admin.staffUser.login.mutate({
|
||||
name,
|
||||
password: 'Passw0rd!',
|
||||
})
|
||||
expect(login.token).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('staff-guarded admin procedures', () => {
|
||||
it('rejects a user token on admin.slots.createSlot', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient(userToken).admin.slots.createSlot.mutate({
|
||||
deliveryTime: new Date(Date.now() + 3 * 3600_000).toISOString(),
|
||||
freezeTime: new Date(Date.now() + 2 * 3600_000).toISOString(),
|
||||
isActive: true,
|
||||
skuIds: [],
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/UNAUTHORIZED|Access denied/i)
|
||||
})
|
||||
|
||||
it('rejects a user token on admin.coupon.create', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient(userToken).admin.coupon.create.mutate({
|
||||
couponCode: `AUTH${uniqueSuffix()}`.toUpperCase(),
|
||||
flatDiscount: 5,
|
||||
isApplyForAll: true,
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i)
|
||||
})
|
||||
|
||||
it('rejects a user token on admin.region.updateRegionConstants', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient(userToken).admin.region.updateRegionConstants.mutate({
|
||||
constants: [{ key: 'welcomeMessage', value: 'nope' }],
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i)
|
||||
})
|
||||
|
||||
it('rejects a staff token writing a global constant via admin.region.updateRegionConstants', async () => {
|
||||
const staff = await staffSession()
|
||||
const error = await captureError(() =>
|
||||
apiClient(staff.token).admin.region.updateRegionConstants.mutate({
|
||||
constants: [{ key: 'versionNum', value: '9.9.9' }],
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/global constant/i)
|
||||
})
|
||||
})
|
||||
|
||||
describe('public admin.vendorSnippets procedures', () => {
|
||||
it('serves getUpcomingSlots to anonymous callers', async () => {
|
||||
const res = await apiClient().admin.vendorSnippets.getUpcomingSlots.query()
|
||||
expect(res.success).toBe(true)
|
||||
expect(Array.isArray(res.data)).toBe(true)
|
||||
})
|
||||
|
||||
it('reaches updateOrderItemPackaging anonymously (domain error, not auth)', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient().admin.vendorSnippets.updateOrderItemPackaging.mutate({
|
||||
orderItemId: 99_999_999,
|
||||
is_packaged: true,
|
||||
})
|
||||
)
|
||||
expect(error.message).not.toMatch(/UNAUTHORIZED|Access denied/i)
|
||||
})
|
||||
|
||||
it('reaches getOrdersBySnippet anonymously (domain error, not auth)', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient().admin.vendorSnippets.getOrdersBySnippet.query({
|
||||
snippetCode: `NO-SUCH-${uniqueSuffix()}`,
|
||||
})
|
||||
)
|
||||
expect(error.message).not.toMatch(/UNAUTHORIZED|Access denied/i)
|
||||
})
|
||||
})
|
||||
|
||||
describe('staff token on user endpoints', () => {
|
||||
it('cannot placeOrder', async () => {
|
||||
const staff = await staffSession()
|
||||
const error = await captureError(() =>
|
||||
apiClient(staff.token).user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||
addressId,
|
||||
})
|
||||
)
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
})
|
||||
|
||||
it('cannot read user coupons', async () => {
|
||||
const staff = await staffSession()
|
||||
const error = await captureError(() =>
|
||||
apiClient(staff.token).user.coupon.getEligible.query()
|
||||
)
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cross-user order access', () => {
|
||||
it('user B cannot read user A order (getOrderById)', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient(otherToken).user.order.getOrderById.query({ orderId: String(orderId) })
|
||||
)
|
||||
expect(error.message).toMatch(/order not found/i)
|
||||
})
|
||||
|
||||
it('user B cannot add notes to user A order', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient(otherToken).user.order.updateUserNotes.mutate({
|
||||
id: orderId,
|
||||
userNotes: 'nope',
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/order not found/i)
|
||||
})
|
||||
|
||||
it('pins: user B cancelling user A order is swallowed into a generic message', async () => {
|
||||
const fresh = await registerUserWithAddress()
|
||||
const placed = await apiClient(fresh.token).user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||
addressId: fresh.addressId,
|
||||
})
|
||||
|
||||
const error = await captureError(() =>
|
||||
apiClient(otherToken).user.order.cancelOrder.mutate({
|
||||
id: placed.data[0].id,
|
||||
reason: 'not mine',
|
||||
})
|
||||
)
|
||||
// The specific 404 is masked by the try/catch in cancelOrder.
|
||||
expect(error.message).toMatch(/failed to cancel order/i)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
/**
|
||||
* Authorization boundaries across the two token kinds, plus cross-user isolation.
|
||||
*
|
||||
* tRPC `protectedProcedure` only requires *some* identity (`ctx.user` OR
|
||||
* `ctx.staffUser`), so procedures that don't additionally check `ctx.staffUser`
|
||||
* are reachable with a user token. Case 4 documents that gap.
|
||||
*/
|
||||
|
||||
import { apiClient, captureError } from '../helpers/api'
|
||||
import {
|
||||
createFutureSlot,
|
||||
createStoreWithSku,
|
||||
ensureUserAddress,
|
||||
registerThrowawayUser,
|
||||
} from '../helpers/fixtures'
|
||||
import { staffSession, userSession } from '../helpers/sessions'
|
||||
|
||||
describe('authorization boundaries', () => {
|
||||
let ownerToken = ''
|
||||
let ownerAddressId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const store = await createStoreWithSku()
|
||||
await createFutureSlot([store.skuId])
|
||||
const address = await ensureUserAddress()
|
||||
const user = await userSession()
|
||||
|
||||
ownerToken = user.token
|
||||
ownerAddressId = address.addressId
|
||||
})
|
||||
|
||||
it('rejects anonymous requests', async () => {
|
||||
const error = await captureError(() =>
|
||||
apiClient().user.order.getOrders.query({ page: 1, pageSize: 5 })
|
||||
)
|
||||
|
||||
expect(error.message).toMatch(/UNAUTHORIZED|unauthorized/i)
|
||||
})
|
||||
|
||||
it('a staff token cannot act as a user (no ctx.user)', async () => {
|
||||
const staff = await staffSession()
|
||||
|
||||
const error = await captureError(() =>
|
||||
apiClient(staff.token).user.order.getOrders.query({ page: 1, pageSize: 5 })
|
||||
)
|
||||
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
})
|
||||
|
||||
it('a user token cannot use staff-guarded admin writes', async () => {
|
||||
const deliveryTime = new Date(Date.now() + 3 * 3600_000).toISOString()
|
||||
const freezeTime = new Date(Date.now() + 2 * 3600_000).toISOString()
|
||||
|
||||
const error = await captureError(() =>
|
||||
apiClient(ownerToken).admin.slots.createSlot.mutate({
|
||||
deliveryTime,
|
||||
freezeTime,
|
||||
isActive: true,
|
||||
skuIds: [],
|
||||
})
|
||||
)
|
||||
|
||||
expect(error.message).toMatch(/UNAUTHORIZED|Access denied|unauthorized/i)
|
||||
})
|
||||
|
||||
it('DOCUMENTS: a user token CAN read admin.product.getProducts (no staff guard)', async () => {
|
||||
// admin.product.getProducts is a bare protectedProcedure — no ctx.staffUser
|
||||
// check — so any authenticated user can read the full admin product list.
|
||||
const products = await apiClient(ownerToken).admin.product.getProducts.query()
|
||||
|
||||
expect(Array.isArray(products.products)).toBe(true)
|
||||
})
|
||||
|
||||
it("one user cannot see another user's addresses", async () => {
|
||||
const other = await registerThrowawayUser()
|
||||
|
||||
const addresses = await apiClient(other.token).user.address.getUserAddresses.query()
|
||||
|
||||
expect(addresses.data.some((a) => a.id === ownerAddressId)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
/**
|
||||
* availability.json — regenerated SYNCHRONOUSLY by
|
||||
* admin.product.toggleOutOfStock (it calls createAvailabilityCacheFile()),
|
||||
* so the file can be read immediately after the mutation.
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import {
|
||||
availabilityCacheUrl,
|
||||
essentialConsts,
|
||||
fetchCacheJson,
|
||||
} from '../helpers/cache'
|
||||
import { createStoreWithSku, type StoreWithSku } from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
interface AvailabilityCache {
|
||||
availability: { id: number; isOutOfStock: boolean }[]
|
||||
count: number
|
||||
}
|
||||
|
||||
describe('availability.json cache', () => {
|
||||
let store: StoreWithSku
|
||||
|
||||
beforeAll(async () => {
|
||||
store = await createStoreWithSku()
|
||||
})
|
||||
|
||||
it('reflects an out-of-stock toggle for the new SKU', async () => {
|
||||
const staff = await staffSession()
|
||||
const admin = apiClient(staff.token)
|
||||
|
||||
const before = await essentialConsts()
|
||||
const toggled = await admin.admin.product.toggleOutOfStock.mutate({
|
||||
id: store.productId,
|
||||
})
|
||||
expect(toggled.isOutOfStock).toBe(true)
|
||||
|
||||
const after = await essentialConsts()
|
||||
expect(after.availabilityVersionNum).toBeGreaterThan(before.availabilityVersionNum)
|
||||
|
||||
const cache = await fetchCacheJson<AvailabilityCache>(
|
||||
availabilityCacheUrl(after, after.availabilityVersionNum)
|
||||
)
|
||||
|
||||
// availability.json is keyed by SKU id (not product id).
|
||||
const entry = cache.availability.find((a) => a.id === store.skuId)
|
||||
expect(entry).toBeDefined()
|
||||
expect(entry!.isOutOfStock).toBe(true)
|
||||
})
|
||||
|
||||
it('has a count matching the number of entries', async () => {
|
||||
const current = await essentialConsts()
|
||||
const cache = await fetchCacheJson<AvailabilityCache>(
|
||||
availabilityCacheUrl(current, current.availabilityVersionNum)
|
||||
)
|
||||
|
||||
expect(cache.count).toBe(cache.availability.length)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,141 +0,0 @@
|
|||
/**
|
||||
* Cross-file cache invariants — the relationships the app relies on when it
|
||||
* merges these files at runtime.
|
||||
*
|
||||
* Two of these can legitimately lag: `slots.json` is rewritten synchronously on
|
||||
* a slot mutation while `products.json` only rebuilds ~30s later (CACHE_CREATOR),
|
||||
* and `essential-consts.json` embeds the versions that were current when it was
|
||||
* written. So the version-sensitive checks re-read the current versions and poll.
|
||||
*/
|
||||
|
||||
import {
|
||||
availabilityCacheUrl,
|
||||
essentialConsts,
|
||||
essentialConstsCacheUrl,
|
||||
fetchCacheJson,
|
||||
pollUntil,
|
||||
productsCacheUrl,
|
||||
slotsCacheUrl,
|
||||
storesCacheUrl,
|
||||
storeDetailCacheUrl,
|
||||
} from '../helpers/cache'
|
||||
|
||||
interface ProductsCache {
|
||||
products: { id: number }[]
|
||||
count: number
|
||||
}
|
||||
|
||||
interface AvailabilityCache {
|
||||
availability: { id: number }[]
|
||||
count: number
|
||||
}
|
||||
|
||||
interface SlotsCache {
|
||||
slots: { id: number; products: { id: number }[] }[]
|
||||
}
|
||||
|
||||
interface StoresCache {
|
||||
stores: { id: number; productCount: number }[]
|
||||
}
|
||||
|
||||
interface StoreDetailCache {
|
||||
store: { id: number }
|
||||
products: unknown[]
|
||||
}
|
||||
|
||||
interface EssentialConstsCache {
|
||||
cacheVersion: number
|
||||
slotsVersionNum: number
|
||||
availabilityVersionNum: number
|
||||
}
|
||||
|
||||
describe('cache consistency', () => {
|
||||
it('every availability entry maps to a product in products.json', async () => {
|
||||
// availability.json is bumped synchronously by stock toggles, so it can lead
|
||||
// products.json (which waits for the rebuild) — poll for them to converge.
|
||||
await pollUntil<number[]>(
|
||||
'every availability id to appear in products.json',
|
||||
async () => {
|
||||
const consts = await essentialConsts()
|
||||
const [products, availability] = await Promise.all([
|
||||
fetchCacheJson<ProductsCache>(productsCacheUrl(consts, consts.cacheVersion)),
|
||||
fetchCacheJson<AvailabilityCache>(
|
||||
availabilityCacheUrl(consts, consts.availabilityVersionNum)
|
||||
),
|
||||
])
|
||||
|
||||
const productIds = new Set(products.products.map((p) => p.id))
|
||||
const orphans = availability.availability
|
||||
.map((a) => a.id)
|
||||
.filter((id) => !productIds.has(id))
|
||||
|
||||
return orphans.length === 0 ? [] : null
|
||||
},
|
||||
{ timeoutMs: 120_000, intervalMs: 5_000 }
|
||||
)
|
||||
})
|
||||
|
||||
it('availability count matches the number of entries', async () => {
|
||||
const consts = await essentialConsts()
|
||||
|
||||
const availability = await fetchCacheJson<AvailabilityCache>(
|
||||
availabilityCacheUrl(consts, consts.availabilityVersionNum)
|
||||
)
|
||||
|
||||
expect(availability.count).toBe(availability.availability.length)
|
||||
})
|
||||
|
||||
it('every product referenced by slots.json exists in products.json', async () => {
|
||||
// slots.json is synchronous; products.json catches up via the rebuild, so poll.
|
||||
await pollUntil<number[]>(
|
||||
'every product id referenced by slots.json to appear in products.json',
|
||||
async () => {
|
||||
const consts = await essentialConsts()
|
||||
const [products, slots] = await Promise.all([
|
||||
fetchCacheJson<ProductsCache>(productsCacheUrl(consts, consts.cacheVersion)),
|
||||
fetchCacheJson<SlotsCache>(slotsCacheUrl(consts, consts.slotsVersionNum)),
|
||||
])
|
||||
|
||||
const productIds = new Set(products.products.map((p) => p.id))
|
||||
const referenced = new Set<number>()
|
||||
slots.slots.forEach((slot) => slot.products.forEach((p) => referenced.add(p.id)))
|
||||
|
||||
const orphans = [...referenced].filter((id) => !productIds.has(id))
|
||||
return orphans.length === 0 ? [] : null
|
||||
},
|
||||
{ timeoutMs: 120_000, intervalMs: 5_000 }
|
||||
)
|
||||
})
|
||||
|
||||
it('essential-consts.json is self-consistent with the version in its path', async () => {
|
||||
const consts = await essentialConsts()
|
||||
|
||||
const cache = await fetchCacheJson<EssentialConstsCache>(
|
||||
essentialConstsCacheUrl(consts, consts.cacheVersion)
|
||||
)
|
||||
|
||||
// The file lives at v-<cacheVersion>, so it must report that same version.
|
||||
expect(cache.cacheVersion).toBe(consts.cacheVersion)
|
||||
// The embedded slots/availability versions are a snapshot at write time and
|
||||
// may lag the live ones (slots are bumped independently) — assert shape only.
|
||||
expect(typeof cache.slotsVersionNum).toBe('number')
|
||||
expect(typeof cache.availabilityVersionNum).toBe('number')
|
||||
})
|
||||
|
||||
it('stores.json productCount matches each store detail file', async () => {
|
||||
const consts = await essentialConsts()
|
||||
|
||||
const stores = await fetchCacheJson<StoresCache>(
|
||||
storesCacheUrl(consts, consts.cacheVersion)
|
||||
)
|
||||
expect(stores.stores.length).toBeGreaterThan(0)
|
||||
|
||||
const store = stores.stores[0]
|
||||
const detail = await fetchCacheJson<StoreDetailCache>(
|
||||
storeDetailCacheUrl(consts, consts.cacheVersion, store.id)
|
||||
)
|
||||
|
||||
expect(detail.store.id).toBe(store.id)
|
||||
expect(detail.products).toHaveLength(store.productCount)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,109 +0,0 @@
|
|||
/**
|
||||
* Cache regeneration for the writes the existing cache suites do not cover:
|
||||
* price updates (availability, synchronous), slot updates (slots.json,
|
||||
* synchronous) and banner creation (products.json, eventual via CACHE_CREATOR).
|
||||
*
|
||||
* The write paths differ: toggleOutOfStock/updateProductPrices/slot mutations
|
||||
* rewrite their cache file inline, while product/store/banner/tag changes go
|
||||
* through scheduleStoreInitialization (a Durable Object that rebuilds ~30s
|
||||
* later). See apps/backend/src/lib/cloud_cache.ts.
|
||||
*/
|
||||
|
||||
import { apiClient } from '../helpers/api'
|
||||
import {
|
||||
availabilityCacheUrl,
|
||||
essentialConsts,
|
||||
fetchCacheJson,
|
||||
pollUntil,
|
||||
slotsCacheUrl,
|
||||
type EssentialConsts,
|
||||
} from '../helpers/cache'
|
||||
import { createFutureSlot, createStoreWithSku } from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
interface AvailabilityCache {
|
||||
availability: { id: number; price: number }[]
|
||||
count: number
|
||||
}
|
||||
|
||||
interface SlotsCache {
|
||||
slots: { id: number; deliveryTime: string; freezeTime: string }[]
|
||||
}
|
||||
|
||||
describe('cache invalidation', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
})
|
||||
|
||||
it('refreshes availability.json synchronously on updateProductPrices', async () => {
|
||||
const store = await createStoreWithSku({ price: 199 })
|
||||
|
||||
const before = await essentialConsts()
|
||||
await admin.admin.product.updateProductPrices.mutate({
|
||||
updates: [{ skuId: store.skuId, price: 250 }],
|
||||
})
|
||||
const after = await essentialConsts()
|
||||
|
||||
expect(after.availabilityVersionNum).toBeGreaterThan(before.availabilityVersionNum)
|
||||
|
||||
const cache = await fetchCacheJson<AvailabilityCache>(
|
||||
availabilityCacheUrl(after, after.availabilityVersionNum)
|
||||
)
|
||||
// availability.json is keyed by SKU id.
|
||||
const entry = cache.availability.find((a) => a.id === store.skuId)
|
||||
expect(entry).toBeDefined()
|
||||
expect(entry!.price).toBe(250)
|
||||
})
|
||||
|
||||
it('refreshes slots.json synchronously on updateSlot', async () => {
|
||||
const store = await createStoreWithSku()
|
||||
const slot = await createFutureSlot([store.skuId])
|
||||
|
||||
const newDelivery = new Date(Date.now() + 9 * 3600_000).toISOString()
|
||||
const newFreeze = new Date(Date.now() + 8 * 3600_000).toISOString()
|
||||
|
||||
const before = await essentialConsts()
|
||||
await admin.admin.slots.updateSlot.mutate({
|
||||
id: slot.slotId,
|
||||
deliveryTime: newDelivery,
|
||||
freezeTime: newFreeze,
|
||||
isActive: true,
|
||||
skuIds: [store.skuId],
|
||||
})
|
||||
const after = await essentialConsts()
|
||||
|
||||
expect(after.slotsVersionNum).toBeGreaterThan(before.slotsVersionNum)
|
||||
|
||||
const cache = await fetchCacheJson<SlotsCache>(
|
||||
slotsCacheUrl(after, after.slotsVersionNum)
|
||||
)
|
||||
const found = cache.slots.find((s) => s.id === slot.slotId)
|
||||
expect(found).toBeDefined()
|
||||
expect(new Date(found!.deliveryTime).toISOString()).toBe(newDelivery)
|
||||
})
|
||||
|
||||
it('rebuilds the versioned cache eventually after creating a banner', async () => {
|
||||
const before = await essentialConsts()
|
||||
|
||||
await admin.admin.banner.createBanner.mutate({
|
||||
name: `API banner ${Date.now()}`,
|
||||
imageUrl: 'https://assets.freshyo.in/api-cache/test-banner.png',
|
||||
})
|
||||
|
||||
const advanced = await pollUntil<EssentialConsts>(
|
||||
`cacheVersion to advance past ${before.cacheVersion} after a banner create`,
|
||||
async () => {
|
||||
const now = await essentialConsts()
|
||||
return now.cacheVersion > before.cacheVersion ? now : null
|
||||
},
|
||||
// The CACHE_CREATOR Durable Object rebuilds ~30s after the write, but can
|
||||
// lag when the suite has queued many writes — mirror cache-products' 180s.
|
||||
{ timeoutMs: 180_000, intervalMs: 5_000 }
|
||||
)
|
||||
|
||||
expect(advanced.cacheVersion).toBeGreaterThan(before.cacheVersion)
|
||||
}, 210_000)
|
||||
})
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
/**
|
||||
* products.json + stores/<id>.json — EVENTUAL cache.
|
||||
*
|
||||
* Product/store/banner changes go through the CACHE_CREATOR Durable Object,
|
||||
* whose alarm fires ~30s later and then rebuilds the cache fire-and-forget.
|
||||
* So these tests poll for the cacheVersion to advance before reading.
|
||||
*/
|
||||
|
||||
import {
|
||||
essentialConsts,
|
||||
fetchCacheJson,
|
||||
pollUntil,
|
||||
productsCacheUrl,
|
||||
storeDetailCacheUrl,
|
||||
type EssentialConsts,
|
||||
} from '../helpers/cache'
|
||||
import { createStoreWithSku, type StoreWithSku } from '../helpers/fixtures'
|
||||
|
||||
interface ProductsCache {
|
||||
products: { id: number; skus?: { id: number }[] }[]
|
||||
count: number
|
||||
}
|
||||
|
||||
interface StoreDetailCache {
|
||||
store: { id: number }
|
||||
products: unknown[]
|
||||
}
|
||||
|
||||
describe('products.json + stores/<id>.json cache (eventual)', () => {
|
||||
let store: StoreWithSku
|
||||
let consts: EssentialConsts
|
||||
|
||||
beforeAll(async () => {
|
||||
const before = await essentialConsts()
|
||||
store = await createStoreWithSku()
|
||||
|
||||
consts = await pollUntil<EssentialConsts>(
|
||||
`cacheVersion to advance past ${before.cacheVersion} after creating a product`,
|
||||
async () => {
|
||||
const now = await essentialConsts()
|
||||
return now.cacheVersion > before.cacheVersion ? now : null
|
||||
},
|
||||
{ timeoutMs: 180_000, intervalMs: 5_000 }
|
||||
)
|
||||
}, 200_000)
|
||||
|
||||
it('lists the new product in products.json', async () => {
|
||||
// The rebuild PUTs the files in parallel, so poll for this one to land.
|
||||
const cache = await pollUntil<ProductsCache>(
|
||||
`products.json at v-${consts.cacheVersion} to include product ${store.productId}`,
|
||||
async () => {
|
||||
try {
|
||||
const body = await fetchCacheJson<ProductsCache>(
|
||||
productsCacheUrl(consts, consts.cacheVersion)
|
||||
)
|
||||
return body.products.some((p) => p.id === store.productId) ? body : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
{ timeoutMs: 60_000, intervalMs: 3_000 }
|
||||
)
|
||||
|
||||
expect(cache.products.some((p) => p.id === store.productId)).toBe(true)
|
||||
})
|
||||
|
||||
it('writes stores/<id>.json for the new store', async () => {
|
||||
// The version keeps advancing with every admin write, and the parallel rebuild
|
||||
// may land the per-store file in a *later* version than the one captured in
|
||||
// beforeAll — so resolve the current version on each attempt instead of pinning it.
|
||||
const cache = await pollUntil<StoreDetailCache>(
|
||||
`stores/${store.storeId}.json to appear`,
|
||||
async () => {
|
||||
try {
|
||||
const now = await essentialConsts()
|
||||
return await fetchCacheJson<StoreDetailCache>(
|
||||
storeDetailCacheUrl(now, now.cacheVersion, store.storeId)
|
||||
)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
{ timeoutMs: 120_000, intervalMs: 5_000 }
|
||||
)
|
||||
|
||||
expect(cache.store?.id).toBe(store.storeId)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
/**
|
||||
* slots.json — regenerated SYNCHRONOUSLY inside admin.slots.createSlot
|
||||
* (it awaits createSlotsCacheFile()), so the file can be read immediately.
|
||||
*/
|
||||
|
||||
import {
|
||||
essentialConsts,
|
||||
fetchCacheJson,
|
||||
slotsCacheUrl,
|
||||
type EssentialConsts,
|
||||
} from '../helpers/cache'
|
||||
import { createFutureSlot, createStoreWithSku } from '../helpers/fixtures'
|
||||
|
||||
interface SlotsCache {
|
||||
slots: { id: number; deliveryTime: string; freezeTime: string }[]
|
||||
count: number
|
||||
}
|
||||
|
||||
describe('slots.json cache', () => {
|
||||
let skuId = 0
|
||||
let consts: EssentialConsts
|
||||
|
||||
beforeAll(async () => {
|
||||
const store = await createStoreWithSku()
|
||||
skuId = store.skuId
|
||||
consts = await essentialConsts()
|
||||
})
|
||||
|
||||
it('exposes a numeric slotsVersionNum', () => {
|
||||
expect(typeof consts.slotsVersionNum).toBe('number')
|
||||
expect(consts.slotsVersionNum).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('contains a newly created slot', async () => {
|
||||
const slot = await createFutureSlot([skuId])
|
||||
const current = await essentialConsts()
|
||||
|
||||
const cache = await fetchCacheJson<SlotsCache>(
|
||||
slotsCacheUrl(current, current.slotsVersionNum)
|
||||
)
|
||||
|
||||
const found = cache.slots.find((s) => s.id === slot.slotId)
|
||||
expect(found).toBeDefined()
|
||||
expect(new Date(found!.deliveryTime).toISOString()).toBe(slot.deliveryTime)
|
||||
})
|
||||
|
||||
it('bumps the version and rewrites the file for a second slot', async () => {
|
||||
const before = await essentialConsts()
|
||||
const slot = await createFutureSlot([skuId], { deliveryInHours: 5, freezeInHours: 4 })
|
||||
const after = await essentialConsts()
|
||||
|
||||
expect(after.slotsVersionNum).toBeGreaterThan(before.slotsVersionNum)
|
||||
|
||||
const cache = await fetchCacheJson<SlotsCache>(
|
||||
slotsCacheUrl(after, after.slotsVersionNum)
|
||||
)
|
||||
expect(cache.slots.some((s) => s.id === slot.slotId)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,263 +0,0 @@
|
|||
/**
|
||||
* Coupon discount maths at placeOrder time.
|
||||
*
|
||||
* The discount is computed server-side in placeOrderUtil
|
||||
* (apps/backend/src/trpc/apis/user-apis/apis/order.ts) and persisted to
|
||||
* orders.totalAmount. These tests read the order row returned by placeOrder
|
||||
* (totalAmount is the stored string).
|
||||
*
|
||||
* The backend mirrors the customer app's model: coupons discount the goods
|
||||
* subtotal and delivery is decided on the post-discount total. Multiple coupons
|
||||
* stack sequentially in the order they are applied, each rounded to the nearest
|
||||
* rupee. Remaining KNOWN BUGS are pinned here (negative totals for >=100%
|
||||
* coupons). See tests/BUGS.md.
|
||||
*/
|
||||
|
||||
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
|
||||
import { asNumber, getConstants } from '../helpers/consts'
|
||||
import {
|
||||
createFutureSlot,
|
||||
createStoreWithSku,
|
||||
registerUserWithAddress,
|
||||
} from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
type OrderRow = { id: number; totalAmount: string; slotId: number | null }
|
||||
type Placed = { success: boolean; data: OrderRow[] }
|
||||
|
||||
const couponCode = () =>
|
||||
`CM${uniqueSuffix()}`.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 20)
|
||||
|
||||
/** price 5 is used so quantities map straight onto the totals below. */
|
||||
const UNIT_PRICE = 5
|
||||
|
||||
describe('coupon discount maths', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let userToken = ''
|
||||
let addressId = 0
|
||||
let skuId = 0
|
||||
let slotId = 0
|
||||
let secondSlotId = 0
|
||||
let roundingSkuId = 0
|
||||
let roundingSlotId = 0
|
||||
let deliveryCharge = 0
|
||||
let freeDeliveryThreshold = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const store = await createStoreWithSku({ price: UNIT_PRICE })
|
||||
const slot = await createFutureSlot([store.skuId])
|
||||
const second = await createFutureSlot([store.skuId], {
|
||||
deliveryInHours: 6,
|
||||
freezeInHours: 5,
|
||||
})
|
||||
|
||||
// A second store at 333 so 3 units = 999 exercises float maths.
|
||||
const rounding = await createStoreWithSku({ price: 333 })
|
||||
const roundingSlot = await createFutureSlot([rounding.skuId])
|
||||
|
||||
const buyer = await registerUserWithAddress()
|
||||
const consts = await getConstants()
|
||||
|
||||
userToken = buyer.token
|
||||
addressId = buyer.addressId
|
||||
skuId = store.skuId
|
||||
slotId = slot.slotId
|
||||
secondSlotId = second.slotId
|
||||
roundingSkuId = rounding.skuId
|
||||
roundingSlotId = roundingSlot.slotId
|
||||
deliveryCharge = asNumber(consts.deliveryCharge)
|
||||
freeDeliveryThreshold = asNumber(consts.freeDeliveryThreshold)
|
||||
|
||||
// The totals below assume these thresholds.
|
||||
expect(freeDeliveryThreshold).toBeGreaterThan(UNIT_PRICE)
|
||||
expect(freeDeliveryThreshold).toBeLessThan(500)
|
||||
})
|
||||
|
||||
const createCoupon = async (over: Record<string, unknown> = {}) => {
|
||||
const created = await admin.admin.coupon.create.mutate({
|
||||
couponCode: couponCode(),
|
||||
minOrder: 1,
|
||||
isApplyForAll: true,
|
||||
validTill: new Date(Date.now() + 24 * 3600_000).toISOString(),
|
||||
...over,
|
||||
})
|
||||
return created[0]
|
||||
}
|
||||
|
||||
const place = (
|
||||
items: { skuId: number; quantity: number; slotId: number | null }[],
|
||||
couponId?: number | number[]
|
||||
): Promise<Placed> =>
|
||||
apiClient(userToken).user.order.placeOrder.mutate({
|
||||
selectedItems: items,
|
||||
addressId,
|
||||
regionId: 1,
|
||||
...(couponId != null
|
||||
? { couponIds: Array.isArray(couponId) ? couponId : [couponId] }
|
||||
: {}),
|
||||
}) as unknown as Promise<Placed>
|
||||
|
||||
const total = (res: Placed) => parseFloat(res.data[0].totalAmount)
|
||||
|
||||
it('applies an uncapped percentage discount', async () => {
|
||||
const coupon = await createCoupon({ discountPercent: 10 })
|
||||
|
||||
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
|
||||
// 500 >= freeDeliveryThreshold -> free delivery; 10% of 500 = 50.
|
||||
expect(total(res)).toBe(450)
|
||||
})
|
||||
|
||||
it('caps a percentage discount at maxValue', async () => {
|
||||
const coupon = await createCoupon({ discountPercent: 50, maxValue: 100 })
|
||||
|
||||
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
|
||||
// min(50% of 500 = 250, maxValue 100) = 100.
|
||||
expect(total(res)).toBe(400)
|
||||
})
|
||||
|
||||
it('caps a flat discount at maxValue', async () => {
|
||||
const coupon = await createCoupon({ flatDiscount: 200, maxValue: 30 })
|
||||
|
||||
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
|
||||
// min(flat 200, maxValue 30) = 30.
|
||||
expect(total(res)).toBe(470)
|
||||
})
|
||||
|
||||
/**
|
||||
* KNOWN BUG: the percentage branch caps at `maxValue * proportion` or
|
||||
* Infinity and never at orderTotal, so a >=100% coupon drives totalAmount to
|
||||
* zero or negative. The flat branch does cap at the order total.
|
||||
*/
|
||||
it('pins: a 150% coupon produces a negative total', async () => {
|
||||
const coupon = await createCoupon({ discountPercent: 150 })
|
||||
|
||||
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
|
||||
// 500 - 150% (750) = -250.
|
||||
expect(total(res)).toBeLessThan(0)
|
||||
})
|
||||
|
||||
it('a 100% coupon zeroes the goods but delivery still applies', async () => {
|
||||
const coupon = await createCoupon({ discountPercent: 100 })
|
||||
|
||||
const res = await place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
|
||||
// Goods 500 - 100% = 0; 0 is below the free-delivery threshold, so the
|
||||
// delivery charge is added on top (matching the customer app).
|
||||
expect(total(res)).toBe(deliveryCharge)
|
||||
})
|
||||
|
||||
it('accepts a cart exactly at the coupon minOrder and rejects below it', async () => {
|
||||
const coupon = await createCoupon({ flatDiscount: 10, minOrder: 500 })
|
||||
|
||||
// 100 * 5 = 500 == minOrder -> the guard is `minOrder > total`, so it passes.
|
||||
const ok = await place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
expect(ok.success).toBe(true)
|
||||
expect(total(ok)).toBe(490)
|
||||
|
||||
// 99 * 5 = 495 < 500 -> rejected.
|
||||
const error = await captureError(() =>
|
||||
place([{ skuId, quantity: 99, slotId }], coupon.id)
|
||||
)
|
||||
expect(error.message).toMatch(/minimum requirement/i)
|
||||
})
|
||||
|
||||
it('applies a percentage coupon to the goods subtotal only', async () => {
|
||||
const coupon = await createCoupon({ discountPercent: 10 })
|
||||
|
||||
// 1 * 5 = 5; 10% off the goods = 4.5. Delivery is decided on 4.5, which is
|
||||
// below the free-delivery threshold, so the charge is added on top.
|
||||
const res = await place([{ skuId, quantity: 1, slotId }], coupon.id)
|
||||
|
||||
expect(total(res)).toBeCloseTo(UNIT_PRICE * 0.9 + deliveryCharge, 6)
|
||||
})
|
||||
|
||||
it('splits a flat discount across slots by orderGroupProportion', async () => {
|
||||
const coupon = await createCoupon({ flatDiscount: 20 })
|
||||
|
||||
const res = await place(
|
||||
[
|
||||
{ skuId, quantity: 40, slotId }, // 200
|
||||
{ skuId, quantity: 60, slotId: secondSlotId }, // 300
|
||||
],
|
||||
coupon.id
|
||||
)
|
||||
|
||||
// 500 >= freeDeliveryThreshold -> no delivery, so both sub-orders are the plain
|
||||
// subtotal. Proportions 0.4 / 0.6 -> discounts 8 / 12.
|
||||
const totals = res.data
|
||||
.map((order) => parseFloat(order.totalAmount))
|
||||
.sort((a, b) => a - b)
|
||||
|
||||
expect(totals).toEqual([192, 288])
|
||||
expect(totals[0] + totals[1]).toBe(480)
|
||||
})
|
||||
|
||||
it('rounds the discount to the nearest rupee', async () => {
|
||||
const coupon = await createCoupon({ discountPercent: 15 })
|
||||
|
||||
const res = await place(
|
||||
[{ skuId: roundingSkuId, quantity: 3, slotId: roundingSlotId }],
|
||||
coupon.id
|
||||
)
|
||||
|
||||
// 999 - round(15% of 999 = 149.85) = 999 - 150 = 849.
|
||||
expect(total(res)).toBe(849)
|
||||
})
|
||||
|
||||
it('stacks multiple coupons sequentially in the order applied', async () => {
|
||||
const tenPct = await createCoupon({ discountPercent: 10 })
|
||||
const flat100 = await createCoupon({ flatDiscount: 100 })
|
||||
|
||||
// 200 * 5 = 1000. Above the free-delivery threshold, so delivery is free.
|
||||
// 10% first: -100 -> 900; then flat 100 -> 800.
|
||||
const pctThenFlat = await place(
|
||||
[{ skuId, quantity: 200, slotId }],
|
||||
[tenPct.id, flat100.id]
|
||||
)
|
||||
expect(total(pctThenFlat)).toBe(800)
|
||||
|
||||
// Same two coupons, reversed: flat 100 first -> 900; then 10% of 900 = 90 -> 810.
|
||||
const flatThenPct = await place(
|
||||
[{ skuId, quantity: 200, slotId }],
|
||||
[flat100.id, tenPct.id]
|
||||
)
|
||||
expect(total(flatThenPct)).toBe(810)
|
||||
})
|
||||
|
||||
it('enforces maxLimitForUser', async () => {
|
||||
const coupon = await createCoupon({ flatDiscount: 5, maxLimitForUser: 1 })
|
||||
|
||||
await place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
|
||||
const error = await captureError(() =>
|
||||
place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
)
|
||||
expect(error.message).toMatch(/usage limit/i)
|
||||
})
|
||||
|
||||
it('rejects an expired coupon at order time', async () => {
|
||||
const coupon = await createCoupon({
|
||||
flatDiscount: 5,
|
||||
validTill: new Date(Date.now() - 3600_000).toISOString(),
|
||||
})
|
||||
|
||||
const error = await captureError(() =>
|
||||
place([{ skuId, quantity: 100, slotId }], coupon.id)
|
||||
)
|
||||
expect(error.message).toMatch(/expired/i)
|
||||
})
|
||||
|
||||
it('rejects an unknown coupon id', async () => {
|
||||
const error = await captureError(() =>
|
||||
place([{ skuId, quantity: 100, slotId }], 99_999_999)
|
||||
)
|
||||
expect(error.message).toMatch(/invalid coupon/i)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,253 +0,0 @@
|
|||
/**
|
||||
* Coupon UX surfaces: reserved-code redemption, getMyCoupons, the admin create
|
||||
* guards and the user-scoping guard at placeOrder.
|
||||
*
|
||||
* See tests/BUGS.md.
|
||||
*/
|
||||
|
||||
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
|
||||
import {
|
||||
createFutureSlot,
|
||||
createStoreWithSku,
|
||||
registerUserWithAddress,
|
||||
} from '../helpers/fixtures'
|
||||
import { staffSession } from '../helpers/sessions'
|
||||
|
||||
const code = (prefix = 'UX') =>
|
||||
`${prefix}${uniqueSuffix()}`.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 20)
|
||||
|
||||
const future = () => new Date(Date.now() + 24 * 3600_000).toISOString()
|
||||
|
||||
describe('coupon UX', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let userA: { token: string; userId: number; addressId: number }
|
||||
let userB: { token: string; userId: number; addressId: number }
|
||||
let skuId = 0
|
||||
let slotId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const store = await createStoreWithSku({ price: 100 })
|
||||
const slot = await createFutureSlot([store.skuId])
|
||||
userA = await registerUserWithAddress()
|
||||
userB = await registerUserWithAddress()
|
||||
skuId = store.skuId
|
||||
slotId = slot.slotId
|
||||
})
|
||||
|
||||
const createCoupon = async (over: Record<string, unknown> = {}) => {
|
||||
const created = await admin.admin.coupon.create.mutate({
|
||||
couponCode: code(),
|
||||
minOrder: 1,
|
||||
isApplyForAll: true,
|
||||
validTill: future(),
|
||||
...over,
|
||||
})
|
||||
return created[0]
|
||||
}
|
||||
|
||||
const createReserved = async (over: Record<string, unknown> = {}) => {
|
||||
const reservedCode = code('RSV')
|
||||
const created = await admin.admin.coupon.createReservedCoupon.mutate({
|
||||
couponCode: reservedCode,
|
||||
flatDiscount: 5,
|
||||
minOrder: 1,
|
||||
validTill: future(),
|
||||
...over,
|
||||
})
|
||||
return { secretCode: reservedCode, coupon: created[0] }
|
||||
}
|
||||
|
||||
const redeem = (token: string, secretCode: string) =>
|
||||
apiClient(token).user.coupon.redeemReservedCoupon.mutate({ secretCode })
|
||||
|
||||
const place = (
|
||||
user: { token: string; addressId: number },
|
||||
couponId?: number,
|
||||
quantity = 1
|
||||
) =>
|
||||
apiClient(user.token).user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity, slotId }],
|
||||
addressId: user.addressId,
|
||||
regionId: 1,
|
||||
...(couponId ? { couponIds: [couponId] } : {}),
|
||||
})
|
||||
|
||||
describe('redeemReservedCoupon', () => {
|
||||
it('redeems a reserved code for the user', async () => {
|
||||
const { secretCode } = await createReserved()
|
||||
|
||||
const res = await redeem(userA.token, secretCode)
|
||||
|
||||
expect(res.success).toBe(true)
|
||||
expect(res.coupon).toBeTruthy()
|
||||
})
|
||||
|
||||
it('rejects a second redemption by the same user', async () => {
|
||||
const { secretCode } = await createReserved()
|
||||
await redeem(userA.token, secretCode)
|
||||
|
||||
const error = await captureError(() => redeem(userA.token, secretCode))
|
||||
expect(error.message).toMatch(/already redeemed/i)
|
||||
})
|
||||
|
||||
it('rejects redeeming an unknown code', async () => {
|
||||
const error = await captureError(() => redeem(userA.token, code('NOPE')))
|
||||
expect(error.message).toMatch(/invalid|redeemed/i)
|
||||
})
|
||||
|
||||
it('rejects an expired reserved code', async () => {
|
||||
const { secretCode } = await createReserved({
|
||||
validTill: new Date(Date.now() - 3600_000).toISOString(),
|
||||
})
|
||||
|
||||
const error = await captureError(() => redeem(userA.token, secretCode))
|
||||
expect(error.message).toMatch(/expired/i)
|
||||
})
|
||||
|
||||
it('lets only one of two simultaneous claims win', async () => {
|
||||
const { secretCode } = await createReserved()
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
redeem(userA.token, secretCode),
|
||||
redeem(userB.token, secretCode),
|
||||
])
|
||||
|
||||
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rejects an isFirstOrderOnly reserved code for a user with orders', async () => {
|
||||
await place(userB) // give B an order
|
||||
|
||||
const { secretCode } = await createReserved({ isFirstOrderOnly: true })
|
||||
|
||||
const error = await captureError(() => redeem(userB.token, secretCode))
|
||||
expect(error.message).toMatch(/first order only/i)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getMyCoupons', () => {
|
||||
it('categorises a user coupon as personal and an apply-for-all as general', async () => {
|
||||
await createCoupon({
|
||||
isUserBased: true,
|
||||
isApplyForAll: false,
|
||||
applicableUsers: [userA.userId],
|
||||
flatDiscount: 5,
|
||||
})
|
||||
await createCoupon({ isApplyForAll: true, flatDiscount: 5 })
|
||||
|
||||
const res = await apiClient(userA.token).user.coupon.getMyCoupons.query()
|
||||
|
||||
expect(Array.isArray(res.data.personal)).toBe(true)
|
||||
expect(Array.isArray(res.data.general)).toBe(true)
|
||||
expect(res.data.personal.length).toBeGreaterThan(0)
|
||||
expect(res.data.general.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('marks a coupon isUsedUp once maxLimitForUser is reached', async () => {
|
||||
const coupon = await createCoupon({
|
||||
isUserBased: true,
|
||||
isApplyForAll: false,
|
||||
applicableUsers: [userA.userId],
|
||||
flatDiscount: 5,
|
||||
maxLimitForUser: 1,
|
||||
})
|
||||
|
||||
await place(userA, coupon.id)
|
||||
|
||||
const res = await apiClient(userA.token).user.coupon.getMyCoupons.query()
|
||||
const found = res.data.personal.find((c: { id: number }) => c.id === coupon.id)
|
||||
|
||||
expect(found).toBeDefined()
|
||||
expect(found!.isUsedUp).toBe(true)
|
||||
expect(found!.usageCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('admin coupon create guards', () => {
|
||||
it('rejects both discount types', async () => {
|
||||
const error = await captureError(() =>
|
||||
admin.admin.coupon.create.mutate({
|
||||
couponCode: code(),
|
||||
discountPercent: 10,
|
||||
flatDiscount: 5,
|
||||
isApplyForAll: true,
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/discountPercent or flatDiscount/i)
|
||||
})
|
||||
|
||||
it('rejects a user-based coupon without applicableUsers', async () => {
|
||||
const error = await captureError(() =>
|
||||
admin.admin.coupon.create.mutate({
|
||||
couponCode: code(),
|
||||
flatDiscount: 5,
|
||||
isUserBased: true,
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/applicableUsers is required/i)
|
||||
})
|
||||
|
||||
it('rejects a coupon that is both user-based and apply-for-all', async () => {
|
||||
const error = await captureError(() =>
|
||||
admin.admin.coupon.create.mutate({
|
||||
couponCode: code(),
|
||||
flatDiscount: 5,
|
||||
isUserBased: true,
|
||||
isApplyForAll: true,
|
||||
applicableUsers: [userA.userId],
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/both user-based and apply for all/i)
|
||||
})
|
||||
|
||||
it('rejects a duplicate coupon code', async () => {
|
||||
const duplicate = code()
|
||||
await admin.admin.coupon.create.mutate({
|
||||
couponCode: duplicate,
|
||||
flatDiscount: 5,
|
||||
isApplyForAll: true,
|
||||
})
|
||||
|
||||
const error = await captureError(() =>
|
||||
admin.admin.coupon.create.mutate({
|
||||
couponCode: duplicate,
|
||||
flatDiscount: 5,
|
||||
isApplyForAll: true,
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/already exists/i)
|
||||
})
|
||||
|
||||
it('rejects unknown applicableUsers', async () => {
|
||||
const error = await captureError(() =>
|
||||
admin.admin.coupon.create.mutate({
|
||||
couponCode: code(),
|
||||
flatDiscount: 5,
|
||||
isUserBased: true,
|
||||
applicableUsers: [99_999_999],
|
||||
})
|
||||
)
|
||||
expect(error.message).toMatch(/not found/i)
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects user B applying a coupon issued to user A', async () => {
|
||||
const coupon = await createCoupon({
|
||||
isUserBased: true,
|
||||
isApplyForAll: false,
|
||||
applicableUsers: [userA.userId],
|
||||
flatDiscount: 5,
|
||||
})
|
||||
|
||||
// 3 * 100 = 300 >= threshold -> no delivery, isolating the scope check.
|
||||
const error = await captureError(() => place(userB, coupon.id, 3))
|
||||
expect(error.message).toMatch(/not applicable/i)
|
||||
|
||||
// The intended user can still spend it.
|
||||
const ok = await place(userA, coupon.id, 3)
|
||||
expect(ok.success).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
/**
|
||||
* Coupon CRUD as staff, then the user end: the coupon must show up as eligible
|
||||
* and actually reduce an order's amount when passed to placeOrder.
|
||||
*
|
||||
* Flow (ordered within the file):
|
||||
* create -> getById -> update -> eligible for the user -> apply to an order
|
||||
* -> delete invalidates it (no longer eligible).
|
||||
*/
|
||||
|
||||
import { apiClient, captureError, uniqueSuffix } from '../helpers/api'
|
||||
import { createFutureSlot, createStoreWithSku, ensureUserAddress } from '../helpers/fixtures'
|
||||
import { staffSession, userSession } from '../helpers/sessions'
|
||||
|
||||
const FLAT_DISCOUNT = 2
|
||||
|
||||
describe('coupon CRUD + apply', () => {
|
||||
let admin: ReturnType<typeof apiClient>
|
||||
let user: ReturnType<typeof apiClient>
|
||||
let code = ''
|
||||
let couponId = 0
|
||||
let skuId = 0
|
||||
let slotId = 0
|
||||
let addressId = 0
|
||||
|
||||
beforeAll(async () => {
|
||||
const staff = await staffSession()
|
||||
admin = apiClient(staff.token)
|
||||
|
||||
const store = await createStoreWithSku()
|
||||
const slot = await createFutureSlot([store.skuId])
|
||||
const address = await ensureUserAddress()
|
||||
const session = await userSession()
|
||||
user = apiClient(session.token)
|
||||
|
||||
skuId = store.skuId
|
||||
slotId = slot.slotId
|
||||
addressId = address.addressId
|
||||
|
||||
code = `APITEST${uniqueSuffix()}`.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 20)
|
||||
|
||||
const created = await admin.admin.coupon.create.mutate({
|
||||
couponCode: code,
|
||||
flatDiscount: FLAT_DISCOUNT,
|
||||
minOrder: 1,
|
||||
maxLimitForUser: 3,
|
||||
isApplyForAll: true,
|
||||
validTill: new Date(Date.now() + 24 * 3600_000).toISOString(),
|
||||
})
|
||||
|
||||
couponId = created[0].id
|
||||
})
|
||||
|
||||
it('creates the coupon and getById returns it', async () => {
|
||||
expect(couponId).toBeGreaterThan(0)
|
||||
|
||||
const coupon = await admin.admin.coupon.getById.query({ id: couponId })
|
||||
expect(coupon.couponCode).toBe(code)
|
||||
expect(Number(coupon.flatDiscount)).toBe(FLAT_DISCOUNT)
|
||||
})
|
||||
|
||||
it('updates the coupon', async () => {
|
||||
await admin.admin.coupon.update.mutate({
|
||||
id: couponId,
|
||||
updates: { maxLimitForUser: 7 },
|
||||
})
|
||||
|
||||
const coupon = await admin.admin.coupon.getById.query({ id: couponId })
|
||||
expect(Number(coupon.maxLimitForUser)).toBe(7)
|
||||
})
|
||||
|
||||
it('is eligible for the user', async () => {
|
||||
const eligible = await user.user.coupon.getEligible.query()
|
||||
|
||||
const match = eligible.data.find((c) => c.id === couponId)
|
||||
expect(match).toBeDefined()
|
||||
expect(match!.couponCode).toBe(code)
|
||||
})
|
||||
|
||||
it('reduces the order amount when the user applies it', async () => {
|
||||
const placed = await user.user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||
addressId,
|
||||
regionId: 1,
|
||||
couponIds: [couponId],
|
||||
})
|
||||
|
||||
const orderId = placed.data[0].id
|
||||
const detail = await user.user.order.getOrderById.query({ orderId: String(orderId) })
|
||||
|
||||
expect(detail.couponCode).toBe(code)
|
||||
expect(Number(detail.discountAmount)).toBe(FLAT_DISCOUNT)
|
||||
})
|
||||
|
||||
it('deleting the coupon invalidates it for the user', async () => {
|
||||
await admin.admin.coupon.delete.mutate({ id: couponId })
|
||||
|
||||
const eligible = await user.user.coupon.getEligible.query()
|
||||
expect(eligible.data.some((c) => c.id === couponId)).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects applying the invalidated coupon to an order', async () => {
|
||||
const error = await captureError(() =>
|
||||
user.user.order.placeOrder.mutate({
|
||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||
addressId,
|
||||
regionId: 1,
|
||||
couponIds: [couponId],
|
||||
})
|
||||
)
|
||||
|
||||
expect(error.message).toMatch(/invalid|expired|no longer valid/i)
|
||||
})
|
||||
|
||||
it('rejects a coupon with both discount types', async () => {
|
||||
const error = await captureError(() =>
|
||||
admin.admin.coupon.create.mutate({
|
||||
couponCode: `BOTH${uniqueSuffix()}`.toUpperCase(),
|
||||
discountPercent: 10,
|
||||
flatDiscount: 5,
|
||||
isApplyForAll: true,
|
||||
})
|
||||
)
|
||||
|
||||
expect(error.message).toMatch(/discountPercent or flatDiscount/i)
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue