freshyo/apps/user-ui/tests/pages/coupons.test.tsx
2026-10-20 11:19:25 +05:30

373 lines
14 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 18 — Coupons (`tests/pages/coupons.test.tsx`, COUPON-01..26).
*
* The page is driven by `user.coupon.getMyCoupons` + `redeemReservedCoupon`.
* `coupon-code-input` / `coupon-add` / `coupon-card-<id>` / `coupon-status-<id>`
* / `coupon-usage-<id>` / `coupon-validity-<id>` / `coupon-apply-<id>` /
* `coupon-back` testIDs were added to the screen for these assertions.
*
* COUPON-24 needs a *second* focus, which the shared navigation mock cannot
* produce, so this file narrows `useFocusEffect` with a focus emitter (same
* approach as `offers.test.tsx`). Refetches are observed through the procedure
* registry: the real client sends a new `getMyCoupons` request for every
* `refetch()`.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native'
import Coupons from '@/app/(drawer)/(tabs)/me/coupons/index'
import { useAppStore } from '@/src/store/appStore'
import { tw } from 'common-ui'
import { flush, renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
procedureInvalidations,
procedureQueryCalls,
setProcedure,
} from '../mocks/trpc-client'
import { router, __setParams } from '../mocks/expo-router-mock'
/** Focus listeners registered through the narrowed navigation mock. */
const mockFocusEntries = new Set<{ callback: () => any; cleanup?: () => void }>()
jest.mock('@react-navigation/native', () => {
const React = require('react')
const actual = jest.requireActual(__dirname + '/../mocks/react-navigation-mock')
return {
...actual,
useFocusEffect: (callback: () => void | (() => void)) => {
React.useEffect(() => {
const entry: { callback: () => any; cleanup?: () => void } = { callback }
const cleanup = callback()
entry.cleanup = typeof cleanup === 'function' ? cleanup : undefined
mockFocusEntries.add(entry)
return () => {
mockFocusEntries.delete(entry)
entry.cleanup?.()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
},
}
})
/** Simulate the screen being focused again (what `useMarkDataFetchers` reacts to). */
async function emitFocus() {
await act(async () => {
Array.from(mockFocusEntries).forEach((entry) => entry.callback())
})
}
/** Simulate the screen losing focus (runs every registered cleanup). */
async function blurFocus() {
await act(async () => {
Array.from(mockFocusEntries).forEach((entry) => entry.cleanup?.())
})
}
const baseCoupon = {
id: 21,
code: 'SAVE10',
discountType: 'percentage' as const,
discountValue: 10,
description: '10% off on all orders',
usageCount: 0,
isExpired: false,
isUsedUp: false,
}
function couponsResponse(personal: any[] = [], general: any[] = []) {
return { data: { personal, general } }
}
function renderCoupons(data: any = couponsResponse([], [baseCoupon])) {
setProcedure('user.coupon.getMyCoupons', { data })
return renderWithProviders(<Coupons />, { auth: 'in' })
}
async function renderCouponsAndSettle(data?: any) {
const view = renderCoupons(data)
await flush(2)
return view
}
/** Deep-merge a (possibly nested) RN style prop. */
function flatStyle(style: any): Record<string, any> {
if (!style) return {}
if (Array.isArray(style)) return Object.assign({}, ...style.map(flatStyle))
if (typeof style === 'object') return style
return {}
}
describe('Coupons (COUPON-01..COUPON-26)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
mockFocusEntries.clear()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => {
alertSpy.mockRestore()
})
it('COUPON-01: while the query is pending it shows the loading copy', () => {
setProcedure('user.coupon.getMyCoupons', { mode: 'pending' })
const view = renderWithProviders(<Coupons />, { auth: 'in' })
expect(view.getByText('Loading coupons...')).toBeTruthy()
})
it('COUPON-02: a failed query shows the error copy', async () => {
setProcedure('user.coupon.getMyCoupons', { mode: 'error' })
const view = renderWithProviders(<Coupons />, { auth: 'in' })
expect(await view.findByText('Failed to load coupons. Please try again.')).toBeTruthy()
})
it('COUPON-03: personal and general coupons are split into their sections', async () => {
const view = await renderCouponsAndSettle(
couponsResponse([baseCoupon], [{ ...baseCoupon, id: 22, code: 'FLAT100' }])
)
expect(view.getByText('Only for Me')).toBeTruthy()
expect(view.getByText('Apply to All')).toBeTruthy()
expect(view.getByText('SAVE10')).toBeTruthy()
expect(view.getByText('FLAT100')).toBeTruthy()
})
it('COUPON-04: with no personal coupons the personal empty message is shown', async () => {
const view = await renderCouponsAndSettle(couponsResponse([], [baseCoupon]))
expect(view.getByText('No personal coupons available')).toBeTruthy()
})
it('COUPON-05: with no general coupons the general empty message is shown', async () => {
const view = await renderCouponsAndSettle(couponsResponse([baseCoupon], []))
expect(view.getByText('No general coupons available')).toBeTruthy()
})
it('COUPON-06: an available coupon shows the green Available label and an enabled Apply', async () => {
const view = await renderCouponsAndSettle()
const status = view.getByTestId('coupon-status-21')
expect(status).toHaveTextContent('Available')
expect(flatStyle(status.props.style).color).toBe(flatStyle(tw`text-green-600`).color)
const apply = view.getByTestId('coupon-apply-21')
expect(apply).toHaveTextContent('Apply')
expect(apply.props.accessibilityState?.disabled).toBe(false)
})
it('COUPON-07: an expired coupon shows red Expired and a disabled Unavailable', async () => {
const view = await renderCouponsAndSettle(
couponsResponse([], [{ ...baseCoupon, isExpired: true }])
)
const status = view.getByTestId('coupon-status-21')
expect(status).toHaveTextContent('Expired')
expect(flatStyle(status.props.style).color).toBe(flatStyle(tw`text-red-500`).color)
const apply = view.getByTestId('coupon-apply-21')
expect(apply).toHaveTextContent('Unavailable')
expect(apply.props.accessibilityState?.disabled).toBe(true)
})
it('COUPON-08: a used-up coupon shows orange Used and a disabled Unavailable', async () => {
const view = await renderCouponsAndSettle(
couponsResponse([], [{ ...baseCoupon, isUsedUp: true }])
)
const status = view.getByTestId('coupon-status-21')
expect(status).toHaveTextContent('Used')
expect(flatStyle(status.props.style).color).toBe(flatStyle(tw`text-orange-500`).color)
const apply = view.getByTestId('coupon-apply-21')
expect(apply).toHaveTextContent('Unavailable')
expect(apply.props.accessibilityState?.disabled).toBe(true)
})
it('COUPON-09: expired wins when a coupon is both expired and used up', async () => {
const view = await renderCouponsAndSettle(
couponsResponse([], [{ ...baseCoupon, isExpired: true, isUsedUp: true }])
)
expect(view.getByTestId('coupon-status-21')).toHaveTextContent('Expired')
})
it('COUPON-10: a per-user limit renders the usage counter', async () => {
const view = await renderCouponsAndSettle(
couponsResponse([], [{ ...baseCoupon, maxLimitForUser: 3, usageCount: 1 }])
)
expect(view.getByTestId('coupon-usage-21')).toHaveTextContent('Used: 1/3')
})
it('COUPON-11: without a per-user limit no usage line is rendered', async () => {
const view = await renderCouponsAndSettle()
expect(view.queryByTestId('coupon-usage-21')).toBeNull()
})
it('COUPON-12: validTill is rendered as a formatted date', async () => {
const view = await renderCouponsAndSettle(
couponsResponse([], [{ ...baseCoupon, validTill: '2026-12-31' }])
)
expect(view.getByTestId('coupon-validity-21')).toHaveTextContent('Valid till: 31 Dec 2026')
})
it('COUPON-13: without validTill the card says No expiry', async () => {
const view = await renderCouponsAndSettle()
expect(view.getByTestId('coupon-validity-21')).toHaveTextContent('Valid till: No expiry')
})
it('COUPON-14: pressing Apply has no handler and neither navigates nor mutates', async () => {
const view = await renderCouponsAndSettle()
fireEvent.press(view.getByTestId('coupon-apply-21'))
await flush(1)
expect(router.push).not.toHaveBeenCalled()
expect(router.navigate).not.toHaveBeenCalled()
expect(lastMutationInput('user.coupon.redeemReservedCoupon')).toBeUndefined()
})
it('COUPON-15: a code shorter than four characters keeps Add disabled', async () => {
const view = await renderCouponsAndSettle()
fireEvent.changeText(view.getByTestId('coupon-code-input'), 'ABC')
expect(view.getByTestId('coupon-add').props.accessibilityState?.disabled).toBe(true)
})
it('COUPON-16: a four-character code enables Add', async () => {
const view = await renderCouponsAndSettle()
fireEvent.changeText(view.getByTestId('coupon-code-input'), 'ABCD')
expect(view.getByTestId('coupon-add').props.accessibilityState?.disabled).toBe(false)
})
it('COUPON-17: redeeming trims and uppercases the secret code', async () => {
const view = await renderCouponsAndSettle()
fireEvent.changeText(view.getByTestId('coupon-code-input'), ' save10 ')
fireEvent.press(view.getByTestId('coupon-add'))
await waitFor(() =>
expect(lastMutationInput('user.coupon.redeemReservedCoupon')).toEqual({
secretCode: 'SAVE10',
})
)
})
it('COUPON-18: a successful redeem clears the input, refetches, invalidates and alerts', async () => {
const view = await renderCouponsAndSettle()
const before = procedureQueryCalls('user.coupon.getMyCoupons').length
fireEvent.changeText(view.getByTestId('coupon-code-input'), 'SAVE10')
fireEvent.press(view.getByTestId('coupon-add'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Coupon added successfully!'))
await waitFor(() =>
expect(procedureQueryCalls('user.coupon.getMyCoupons').length).toBeGreaterThan(before)
)
expect(view.getByTestId('coupon-code-input').props.value).toBe('')
expect(procedureInvalidations('user.coupon.getEligible').length).toBeGreaterThan(0)
})
it('COUPON-19: a failed redeem shows the backend message and keeps the input', async () => {
setProcedure('user.coupon.redeemReservedCoupon', {
mode: 'error',
error: new Error('Invalid code'),
})
const view = await renderCouponsAndSettle()
fireEvent.changeText(view.getByTestId('coupon-code-input'), 'BADCODE')
fireEvent.press(view.getByTestId('coupon-add'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Invalid code'))
expect(view.getByTestId('coupon-code-input').props.value).toBe('BADCODE')
})
it('COUPON-20: a pending redeem shows Adding... and disables the button', async () => {
setProcedure('user.coupon.redeemReservedCoupon', { mode: 'pending' })
const view = await renderCouponsAndSettle()
fireEvent.changeText(view.getByTestId('coupon-code-input'), 'SAVE10')
await act(async () => {
fireEvent.press(view.getByTestId('coupon-add'))
})
// Let React Query flush its batched `isPending` notification.
await flush(1)
expect(view.getByTestId('coupon-add')).toHaveTextContent('Adding...')
expect(view.getByTestId('coupon-add').props.accessibilityState?.disabled).toBe(true)
})
it('COUPON-21: opened from the cart it hides the tab bar and restores it on blur', async () => {
__setParams({ from: 'cart' })
const view = await renderCouponsAndSettle()
expect(view.getByTestId('coupon-back')).toBeTruthy()
expect(useAppStore.getState().hideTabsNav['coupons-from-cart']).toBe(true)
await blurFocus()
expect(useAppStore.getState().hideTabsNav['coupons-from-cart']).toBe(false)
})
it('COUPON-22: opened from the cart the in-page back button navigates to the cart', async () => {
__setParams({ from: 'cart' })
const view = await renderCouponsAndSettle()
fireEvent.press(view.getByTestId('coupon-back'))
expect(router.navigate).toHaveBeenCalledWith('/(drawer)/(tabs)/home/cart')
})
it('COUPON-23: without a from param there is no in-page back button', async () => {
__setParams({})
const view = await renderCouponsAndSettle()
expect(view.queryByTestId('coupon-back')).toBeNull()
})
it('COUPON-24: a re-focus through useMarkDataFetchers refetches the coupons', async () => {
await renderCouponsAndSettle()
const before = procedureQueryCalls('user.coupon.getMyCoupons').length
await emitFocus()
await waitFor(() =>
expect(procedureQueryCalls('user.coupon.getMyCoupons').length).toBeGreaterThan(before)
)
})
it('COUPON-25: a long code and description render without crashing', async () => {
const code = 'LONGCODE'.repeat(15)
const description = 'A very long coupon description. '.repeat(20)
const view = await renderCouponsAndSettle(
couponsResponse([], [{ ...baseCoupon, code, description }])
)
expect(view.getByTestId('coupon-card-21')).toBeTruthy()
expect(view.getByText(code)).toBeTruthy()
expect(view.getByText(description)).toBeTruthy()
})
it('COUPON-26: a whitespace-only code keeps Add disabled', async () => {
const view = await renderCouponsAndSettle()
fireEvent.changeText(view.getByTestId('coupon-code-input'), ' ')
expect(view.getByTestId('coupon-add').props.accessibilityState?.disabled).toBe(true)
})
})