479 lines
18 KiB
TypeScript
479 lines
18 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
/**
|
|
* Catalogue section 14 — PaymentAndOrder shared component
|
|
* (`tests/pages/payment-and-order.test.tsx`, PAY-01..PAY-29).
|
|
*
|
|
* The real component runs with the real tRPC registry mock, cart storage,
|
|
* central stores and `useRegion`. Cart helpers from `@packages/shared` stay real.
|
|
*/
|
|
import * as React from 'react'
|
|
import { Alert } from 'react-native'
|
|
import { QueryClient } from '@tanstack/react-query'
|
|
import { StorageServiceCasual } from 'common-ui'
|
|
import { act, fireEvent, within } from '@testing-library/react-native'
|
|
|
|
import PaymentAndOrder from '@/components/PaymentAndOrderComponent'
|
|
import { useCheckoutStore } from '@/src/store/checkoutStore'
|
|
import { useRegionStore } from '@/src/store/regionStore'
|
|
|
|
import { createTestQueryClient, flush, renderWithProviders, seedBoot } from '../helpers/test-utils'
|
|
import { resetAllMocks } from '../helpers/reset'
|
|
import {
|
|
lastProcedureInput,
|
|
procedureInvalidations,
|
|
procedureMutationCalls,
|
|
setProcedure,
|
|
} from '../mocks/trpc-client'
|
|
import { __set, __snapshot } from '../mocks/secure-store-mock'
|
|
import { router } from '../mocks/expo-router-mock'
|
|
import { A1, CONSTS, O1, O2 } from '../fixtures'
|
|
|
|
const CART_KEY = 'cart_items'
|
|
const FLASH_KEY = 'flash_cart_items'
|
|
|
|
const line = (id: number, skuId: number, quantity: number, slotId: number) => ({
|
|
id,
|
|
skuId,
|
|
quantity,
|
|
slotId,
|
|
addedAt: '2024-01-01T00:00:00.000Z',
|
|
})
|
|
|
|
function createClient(): QueryClient {
|
|
// Use the harness client so real tRPC invalidations are recorded for
|
|
// `procedureInvalidations()`, then drop finished mutations from the cache.
|
|
const queryClient = createTestQueryClient()
|
|
queryClient.setDefaultOptions({
|
|
...queryClient.getDefaultOptions(),
|
|
mutations: { retry: false, gcTime: 0 },
|
|
})
|
|
return queryClient
|
|
}
|
|
|
|
const BASE_PROPS: any = {
|
|
selectedAddress: A1.id,
|
|
selectedSlots: { 1: 1849 },
|
|
selectedCouponIds: [],
|
|
cartItems: [line(1, 2, 2, 1849)],
|
|
totalPrice: 430,
|
|
totalSavings: 0,
|
|
discountAmount: 0,
|
|
finalTotal: 430,
|
|
finalTotalWithDelivery: 430,
|
|
deliveryCharge: 0,
|
|
constsData: CONSTS,
|
|
selectedCoupons: [],
|
|
isFlashDelivery: false,
|
|
}
|
|
|
|
interface PayOptions {
|
|
noRegion?: boolean
|
|
queryClient?: QueryClient
|
|
}
|
|
|
|
async function mountPay(overrides: Record<string, any> = {}, opts: PayOptions = {}) {
|
|
seedBoot({ addressId: A1.id })
|
|
if (opts.noRegion) {
|
|
useRegionStore.setState({ selectedRegionId: null, selectedRegion: null, selectedBoundId: null })
|
|
}
|
|
const props = { ...BASE_PROPS, ...overrides }
|
|
const queryClient = opts.queryClient ?? createClient()
|
|
const result = renderWithProviders(<PaymentAndOrder {...props} />, {
|
|
auth: false,
|
|
queryClient,
|
|
})
|
|
await flush(3)
|
|
return { ...result, queryClient, props }
|
|
}
|
|
|
|
function spyAlert() {
|
|
return jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
|
}
|
|
|
|
describe('PaymentAndOrder — PAY-01..29', () => {
|
|
beforeEach(() => resetAllMocks())
|
|
|
|
/* ------------------------------------------------------------------------ */
|
|
/* Address gate, validation and payload */
|
|
/* ------------------------------------------------------------------------ */
|
|
|
|
it('PAY-01: a bill with an address shows the rows and enables Place Order', async () => {
|
|
const { getByTestId, getByText } = await mountPay()
|
|
expect(getByText('Bill Details')).toBeTruthy()
|
|
expect(getByTestId('bill-item-total-amount')).toHaveTextContent('₹430')
|
|
expect(getByTestId('bill-delivery-amount')).toHaveTextContent('Free')
|
|
expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹430')
|
|
expect(getByTestId('place-order-button')).not.toBeDisabled()
|
|
})
|
|
|
|
it('PAY-02: no address shows the red banner and disables Place Order', async () => {
|
|
const { getByTestId } = await mountPay({ selectedAddress: null })
|
|
expect(getByTestId('select-address-error')).toBeTruthy()
|
|
expect(getByTestId('place-order-button')).toBeDisabled()
|
|
})
|
|
|
|
it('PAY-03: pressing with no region alerts "Please select a delivery region..."', async () => {
|
|
const alert = spyAlert()
|
|
const { getByTestId } = await mountPay({}, { noRegion: true })
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(1)
|
|
|
|
expect(alert).toHaveBeenCalledWith(
|
|
'Error',
|
|
'Please select a delivery region before placing an order'
|
|
)
|
|
expect(lastProcedureInput('user.order.placeOrder')).toBeUndefined()
|
|
})
|
|
|
|
it('PAY-04: no valid items alerts "No valid items to order"', async () => {
|
|
const alert = spyAlert()
|
|
// Mutton (sku 6) is out of stock in the availability fixture.
|
|
const { getByTestId } = await mountPay({
|
|
cartItems: [line(1, 6, 1, 1849)],
|
|
selectedSlots: { 1: 1849 },
|
|
})
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(1)
|
|
|
|
expect(alert).toHaveBeenCalledWith('Error', 'No valid items to order')
|
|
expect(procedureMutationCalls('user.order.placeOrder')).toHaveLength(0)
|
|
})
|
|
|
|
it('PAY-05: an out-of-stock item is filtered from the payload', async () => {
|
|
const { getByTestId } = await mountPay({
|
|
cartItems: [line(1, 2, 2, 1849), line(2, 6, 1, 1849)],
|
|
selectedSlots: { 1: 1849, 2: 1849 },
|
|
})
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(lastProcedureInput('user.order.placeOrder').selectedItems).toEqual([
|
|
{ skuId: 2, quantity: 2, slotId: 1849 },
|
|
])
|
|
})
|
|
|
|
it('PAY-06: a regular item without a selected slot is filtered out', async () => {
|
|
const { getByTestId } = await mountPay({
|
|
cartItems: [line(1, 2, 1, 1849), line(2, 5, 1, 1849)],
|
|
selectedSlots: { 1: 1849 },
|
|
})
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(lastProcedureInput('user.order.placeOrder').selectedItems).toEqual([
|
|
{ skuId: 2, quantity: 1, slotId: 1849 },
|
|
])
|
|
})
|
|
|
|
it('PAY-07: an eligible flash item is sent with slotId null', async () => {
|
|
const { getByTestId } = await mountPay({
|
|
isFlashDelivery: true,
|
|
cartItems: [line(1, 8, 1, 0)],
|
|
selectedSlots: {},
|
|
})
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(lastProcedureInput('user.order.placeOrder')).toMatchObject({
|
|
selectedItems: [{ skuId: 8, quantity: 1, slotId: null }],
|
|
isFlashDelivery: true,
|
|
})
|
|
})
|
|
|
|
it('PAY-08: place order sends selectedItems, address, region, bound, coupons, notes and flash flag', async () => {
|
|
useCheckoutStore.setState({ userNotes: 'Ring the bell' })
|
|
const { getByTestId } = await mountPay({
|
|
selectedCouponIds: [21, 22],
|
|
selectedCoupons: [{ id: 21 }, { id: 22 }],
|
|
})
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(lastProcedureInput('user.order.placeOrder')).toEqual({
|
|
selectedItems: [{ skuId: 2, quantity: 2, slotId: 1849 }],
|
|
addressId: A1.id,
|
|
regionId: 1,
|
|
boundId: CONSTS.boundId,
|
|
couponIds: [21, 22],
|
|
userNotes: 'Ring the bell',
|
|
isFlashDelivery: false,
|
|
})
|
|
})
|
|
|
|
it('PAY-09: with no coupons couponIds is omitted/undefined', async () => {
|
|
const { getByTestId } = await mountPay({ selectedCouponIds: [] })
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(lastProcedureInput('user.order.placeOrder').couponIds).toBeUndefined()
|
|
})
|
|
|
|
it('PAY-10: selected coupon ids keep their order', async () => {
|
|
const { getByTestId } = await mountPay({
|
|
selectedCouponIds: [22, 21],
|
|
selectedCoupons: [{ id: 22 }, { id: 21 }],
|
|
})
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(lastProcedureInput('user.order.placeOrder').couponIds).toEqual([22, 21])
|
|
})
|
|
|
|
it('PAY-11: bound resolution prefers constsData.boundId, else useRegion().boundId', async () => {
|
|
const first = await mountPay({ constsData: { ...CONSTS, boundId: 99 } })
|
|
fireEvent.press(first.getByTestId('place-order-button'))
|
|
await flush(4)
|
|
expect(lastProcedureInput('user.order.placeOrder').boundId).toBe(99)
|
|
first.unmount()
|
|
|
|
const second = await mountPay({ constsData: undefined })
|
|
fireEvent.press(second.getByTestId('place-order-button'))
|
|
await flush(4)
|
|
expect(lastProcedureInput('user.order.placeOrder').boundId).toBe(7)
|
|
})
|
|
|
|
/* ------------------------------------------------------------------------ */
|
|
/* Success, failure and loading */
|
|
/* ------------------------------------------------------------------------ */
|
|
|
|
it('PAY-12: success clears the regular cart and invalidates local-cart + getOrders', async () => {
|
|
__set(CART_KEY, JSON.stringify([line(1, 2, 2, 1849)]))
|
|
__set(FLASH_KEY, JSON.stringify([line(9, 8, 1, 0)]))
|
|
const { getByTestId, queryClient } = await mountPay()
|
|
const invalidate = jest.spyOn(queryClient, 'invalidateQueries')
|
|
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(5)
|
|
|
|
expect(JSON.parse(__snapshot()[CART_KEY])).toEqual([])
|
|
expect(JSON.parse(__snapshot()[FLASH_KEY])).toHaveLength(1)
|
|
expect(invalidate).toHaveBeenCalledWith({ queryKey: ['local-cart-regular'] })
|
|
expect(procedureInvalidations('user.order.getOrders').length).toBeGreaterThan(0)
|
|
})
|
|
|
|
it('PAY-13: success uses the sum of every returned order total', async () => {
|
|
setProcedure('user.order.placeOrder', {
|
|
data: { data: [{ ...O1, totalAmount: 445 }, { ...O2, totalAmount: 90 }] },
|
|
})
|
|
const { getByTestId } = await mountPay()
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(router.replace).toHaveBeenCalledWith(
|
|
'./order-success?orderId=1001&totalAmount=535'
|
|
)
|
|
})
|
|
|
|
it('PAY-14: a zero/missing server total falls back to finalTotalWithDelivery', async () => {
|
|
setProcedure('user.order.placeOrder', {
|
|
data: { data: [{ ...O1, totalAmount: 0 }] },
|
|
})
|
|
const { getByTestId } = await mountPay({ finalTotalWithDelivery: 430 })
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(router.replace).toHaveBeenCalledWith(
|
|
'./order-success?orderId=1001&totalAmount=430'
|
|
)
|
|
})
|
|
|
|
it('PAY-15: regular success navigates to ./order-success with the order id and total', async () => {
|
|
setProcedure('user.order.placeOrder', { data: { data: [O1] } })
|
|
const { getByTestId } = await mountPay()
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(router.replace).toHaveBeenCalledWith(
|
|
'./order-success?orderId=1001&totalAmount=445'
|
|
)
|
|
})
|
|
|
|
it('PAY-16: flash success navigates to the flash order-success route', async () => {
|
|
setProcedure('user.order.placeOrder', { data: { data: [O2] } })
|
|
const { getByTestId } = await mountPay({
|
|
isFlashDelivery: true,
|
|
cartItems: [line(1, 8, 1, 0)],
|
|
selectedSlots: {},
|
|
})
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(router.replace).toHaveBeenCalledWith(
|
|
'/(drawer)/(tabs)/flash-delivery/order-success?orderId=1002&totalAmount=90'
|
|
)
|
|
})
|
|
|
|
it('PAY-17: a rejected placeOrder alerts its message and does not clear the cart', async () => {
|
|
__set(CART_KEY, JSON.stringify([line(1, 2, 2, 1849)]))
|
|
setProcedure('user.order.placeOrder', {
|
|
mode: 'error',
|
|
error: new Error('Region mismatch'),
|
|
})
|
|
const alert = spyAlert()
|
|
const { getByTestId } = await mountPay()
|
|
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
expect(alert).toHaveBeenCalledWith('Error', 'Region mismatch')
|
|
expect(JSON.parse(__snapshot()[CART_KEY])).toHaveLength(1)
|
|
expect(router.replace).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('PAY-18: a double press fires only one mutation', async () => {
|
|
// Keep the first submit in flight so the re-entrancy guard is observable.
|
|
setProcedure('user.order.placeOrder', { mode: 'pending' })
|
|
const { getByTestId } = await mountPay()
|
|
const button = getByTestId('place-order-button')
|
|
act(() => {
|
|
fireEvent.press(button)
|
|
fireEvent.press(button)
|
|
})
|
|
await flush(2)
|
|
|
|
// `mode: 'pending'` short-circuits the registry before it records calls, so
|
|
// count the real client's requests at the network boundary instead.
|
|
const placeOrderRequests = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
|
|
String(url).includes('user.order.placeOrder')
|
|
)
|
|
expect(placeOrderRequests).toHaveLength(1)
|
|
})
|
|
|
|
it('PAY-19: a pending placeOrder disables the button and opens the loading dialog', async () => {
|
|
setProcedure('user.order.placeOrder', { mode: 'pending' })
|
|
const { getByTestId, getByText } = await mountPay()
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(1)
|
|
|
|
expect(getByTestId('place-order-button')).toBeDisabled()
|
|
expect(getByText('Placing your order...')).toBeTruthy()
|
|
})
|
|
|
|
it('PAY-20: onSettled after an error resets the submitting ref and loading state', async () => {
|
|
setProcedure('user.order.placeOrder', { mode: 'error', error: new Error('boom') })
|
|
spyAlert()
|
|
const { getByTestId, queryByText } = await mountPay()
|
|
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
expect(queryByText('Placing your order...')).toBeNull()
|
|
expect(getByTestId('place-order-button')).not.toBeDisabled()
|
|
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
expect(procedureMutationCalls('user.order.placeOrder')).toHaveLength(2)
|
|
})
|
|
|
|
it('PAY-21: onCancel renders a Back to Cart block whose press calls the callback', async () => {
|
|
const onCancel = jest.fn()
|
|
const { getByTestId } = await mountPay({ onCancel })
|
|
expect(within(getByTestId('payment-cancel')).getByText('Back to Cart')).toBeTruthy()
|
|
fireEvent.press(getByTestId('payment-cancel'))
|
|
expect(onCancel).toHaveBeenCalled()
|
|
})
|
|
|
|
/* ------------------------------------------------------------------------ */
|
|
/* Payment, delivery and bill details */
|
|
/* ------------------------------------------------------------------------ */
|
|
|
|
it('PAY-22: COD only — the online payment row is disabled and COD is selected', async () => {
|
|
const { getByTestId, getByText } = await mountPay()
|
|
expect(getByTestId('payment-online-row')).toBeDisabled()
|
|
expect(getByText('Pay Online (Coming Soon)')).toBeTruthy()
|
|
expect(getByTestId('payment-cod-row')).toBeTruthy()
|
|
expect(getByText('Cash on Delivery')).toBeTruthy()
|
|
})
|
|
|
|
it('PAY-23: free delivery strikes through the old charge and shows Free', async () => {
|
|
const regular = await mountPay({ deliveryCharge: 0 })
|
|
expect(regular.getByTestId('bill-delivery-strike')).toHaveTextContent('₹15')
|
|
expect(regular.getByTestId('bill-delivery-amount')).toHaveTextContent('Free')
|
|
regular.unmount()
|
|
|
|
const flash = await mountPay({
|
|
isFlashDelivery: true,
|
|
deliveryCharge: 0,
|
|
cartItems: [line(1, 8, 1, 0)],
|
|
selectedSlots: {},
|
|
})
|
|
expect(flash.getByTestId('bill-delivery-strike')).toHaveTextContent('₹25')
|
|
expect(flash.getByTestId('bill-delivery-amount')).toHaveTextContent('Free')
|
|
})
|
|
|
|
it('PAY-24: below the threshold the nudge shows the exact remaining amount', async () => {
|
|
const { getByTestId } = await mountPay({
|
|
totalPrice: 200,
|
|
finalTotal: 200,
|
|
finalTotalWithDelivery: 215,
|
|
deliveryCharge: 15,
|
|
})
|
|
expect(
|
|
within(getByTestId('bill-nudge')).getByText('Add products worth ₹49 for free delivery')
|
|
).toBeTruthy()
|
|
})
|
|
|
|
it('PAY-25: total savings above ₹1 shows the Total Savings row', async () => {
|
|
const shown = await mountPay({ totalSavings: 10 })
|
|
expect(shown.getByTestId('bill-total-savings-amount')).toHaveTextContent('₹10')
|
|
shown.unmount()
|
|
|
|
const hidden = await mountPay({ totalSavings: 1 })
|
|
expect(hidden.queryByTestId('bill-total-savings-amount')).toBeNull()
|
|
})
|
|
|
|
it('PAY-26: a discount above 0 shows the Product Discount row', async () => {
|
|
const shown = await mountPay({
|
|
discountAmount: 43,
|
|
finalTotal: 387,
|
|
finalTotalWithDelivery: 387,
|
|
})
|
|
expect(shown.getByTestId('bill-product-discount-amount')).toHaveTextContent('-₹43')
|
|
shown.unmount()
|
|
|
|
const hidden = await mountPay({ discountAmount: 0 })
|
|
expect(hidden.queryByTestId('bill-product-discount-amount')).toBeNull()
|
|
})
|
|
|
|
it('PAY-27: the savings banner includes coupon, market savings and free delivery', async () => {
|
|
const { getByTestId } = await mountPay({
|
|
discountAmount: 43,
|
|
totalSavings: 10,
|
|
deliveryCharge: 0,
|
|
finalTotal: 387,
|
|
finalTotalWithDelivery: 387,
|
|
})
|
|
// 43 + 10 + ₹15 waived delivery.
|
|
expect(getByTestId('bill-savings-text')).toHaveTextContent('You saved ₹68 on this order')
|
|
})
|
|
|
|
it('PAY-28: an empty orders array does not navigate (current)', async () => {
|
|
setProcedure('user.order.placeOrder', { data: { data: [] } })
|
|
const { getByTestId } = await mountPay()
|
|
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(4)
|
|
|
|
// orders[0].id reads from undefined; the mutation wrapper swallows the throw.
|
|
expect(router.replace).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('PAY-29: a failing cart clear is not awaited; navigation still runs (current gap)', async () => {
|
|
__set(CART_KEY, JSON.stringify([line(1, 2, 2, 1849)]))
|
|
setProcedure('user.order.placeOrder', { data: { data: [O1] } })
|
|
const original = StorageServiceCasual.setItem.bind(StorageServiceCasual)
|
|
jest.spyOn(StorageServiceCasual, 'setItem').mockImplementation(((key: string, value: string) => {
|
|
// A clear that never completes. The component calls it without awaiting,
|
|
// so navigation must still run — the promise (and, with a rejection, an
|
|
// unhandled rejection) is simply dropped.
|
|
if (key === CART_KEY) return new Promise<void>(() => {})
|
|
return original(key, value)
|
|
}) as any)
|
|
const { getByTestId } = await mountPay()
|
|
fireEvent.press(getByTestId('place-order-button'))
|
|
await flush(5)
|
|
|
|
expect(router.replace).toHaveBeenCalledWith(
|
|
'./order-success?orderId=1001&totalAmount=445'
|
|
)
|
|
})
|
|
})
|