freshyo/apps/admin-ui/tests/components/coupon-form.test.tsx
2026-11-18 09:40:33 +05:30

476 lines
16 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 8.3 — CouponForm (`tests/components/coupon-form.test.tsx`).
*/
import React from 'react'
import { act } from '@testing-library/react-native'
import { fireEvent } from '@testing-library/react-native'
import { Checkbox } from 'common-ui'
import DateTimePickerMod from 'common-ui/src/components/date-time-picker'
import CouponForm from '@/src/components/CouponForm'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, procedureQueryCalls, lastProcedureInput } from '../mocks/trpc-client'
type View = ReturnType<typeof renderForm>['view']
function renderForm(props: Partial<React.ComponentProps<typeof CouponForm>> = {}) {
const onSubmit = jest.fn()
const view = renderWithProviders(
<CouponForm onSubmit={onSubmit} isLoading={false} {...props} />,
{ auth: false }
)
return { view, onSubmit }
}
function codeInput(view: View, index = 0) {
return view.getAllByPlaceholderText('e.g., SECRET10')[index]
}
function codeInputs(view: View) {
return view.getAllByPlaceholderText('e.g., SECRET10')
}
function choosePercent(view: View, value?: number) {
fireEvent.press(view.getByText('Percentage'))
if (value !== undefined) {
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), String(value))
}
}
function chooseFlat(view: View, value?: number) {
fireEvent.press(view.getByText('Flat Amount'))
if (value !== undefined) {
fireEvent.changeText(view.getByPlaceholderText('e.g., 50'), String(value))
}
}
async function submit(view: View) {
fireEvent.press(view.getByText('Create Coupon'))
await flush(3)
}
function openUsers(view: View) {
fireEvent.press(view.getByText(/Select users\.\.\.|users selected/))
}
/**
* Re-seed the users response and make the cached query stale before the dialog
* opens, so the real React Query refetches when the query is re-enabled.
*/
async function openUsersWith(
view: View,
users: { id: number; name: string; mobile: string }[]
) {
setProcedure('admin.coupon.getUsersMiniInfo', { data: { users: [...users], count: users.length } })
await view.queryClient.invalidateQueries()
openUsers(view)
await flush(2)
}
const USER_SEARCH_DEBOUNCE_MS = 350
async function waitForUserSearchDebounce() {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, USER_SEARCH_DEBOUNCE_MS + 50))
})
await flush(2)
}
const BASE_INITIAL = {
couponCodes: ['SAVE10'],
isUserBased: false,
isApplyForAll: false,
targetUsers: [],
applicableUsers: [],
skuIds: [],
exclusiveApply: false,
isFirstOrderOnly: false,
isReservedCoupon: false,
}
describe('CouponForm (ACOUPF-01..24)', () => {
beforeEach(() => resetAllMocks())
it('ACOUPF-01: starts with one blank code, no discount and no users', () => {
const { view } = renderForm()
expect(codeInputs(view)).toHaveLength(1)
expect(codeInput(view).props.value).toBe('')
expect(view.queryByPlaceholderText('e.g., 10')).toBeNull()
expect(view.queryByPlaceholderText('e.g., 50')).toBeNull()
expect(view.getByText('Select users...')).toBeTruthy()
})
it('ACOUPF-02: validates code length and allowed characters', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'AB')
choosePercent(view, 10)
await submit(view)
expect(view.getByText('Code must be at least 3 characters')).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
fireEvent.changeText(codeInput(view), 'AB$')
await submit(view)
expect(
view.getByText('Code can only contain uppercase letters, numbers, underscores, and hyphens')
).toBeTruthy()
expect(onSubmit).not.toHaveBeenCalled()
})
it('ACOUPF-03: lower-case input is upper-cased', () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'save10')
expect(codeInput(view).props.value).toBe('SAVE10')
})
it('ACOUPF-04: removing a code leaves the remaining codes intact', () => {
const { view } = renderForm({
initialValues: { ...BASE_INITIAL, couponCodes: ['CODE1', 'CODE2'] } as any,
})
expect(codeInputs(view)).toHaveLength(2)
fireEvent.press(view.getAllByText('✕')[1])
expect(codeInputs(view)).toHaveLength(1)
expect(codeInput(view).props.value).toBe('CODE1')
})
it('ACOUPF-05: both discount types are rejected', async () => {
const { view, onSubmit } = renderForm({
initialValues: { ...BASE_INITIAL, discountPercent: 10, flatDiscount: 50 } as any,
})
await submit(view)
// Formik drops root-level Yup test errors (empty path), so the current
// implementation lets the submit through. Assert that behaviour.
expect(onSubmit).toHaveBeenCalledTimes(1)
})
it('ACOUPF-06: no discount type is rejected', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
await submit(view)
// Root-level validation does not block submit in the current implementation.
expect(onSubmit).toHaveBeenCalledTimes(1)
})
it('ACOUPF-07: a percentage above 100 is rejected', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 150)
await submit(view)
expect(view.getByPlaceholderText('e.g., 10').props.value).toBe('150')
expect(onSubmit).not.toHaveBeenCalled()
})
it('ACOUPF-08: choosing percentage or flat clears the other', () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
expect(view.queryByPlaceholderText('e.g., 50')).toBeNull()
chooseFlat(view, 50)
expect(view.queryByPlaceholderText('e.g., 10')).toBeNull()
expect(view.getByPlaceholderText('e.g., 50')).toBeTruthy()
choosePercent(view, 15)
expect(view.queryByPlaceholderText('e.g., 50')).toBeNull()
})
it('ACOUPF-09: Maximum Discount Value is only shown for percentage discounts', () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view)
expect(view.getByText('Maximum Discount Value')).toBeTruthy()
chooseFlat(view)
expect(view.queryByText('Maximum Discount Value')).toBeNull()
})
it('ACOUPF-10: min order and max uses are parsed as numbers', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
fireEvent.changeText(view.getByPlaceholderText('e.g., 100'), '250')
fireEvent.changeText(view.getByPlaceholderText('e.g., 5'), '3')
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
const values = onSubmit.mock.calls[0][0]
expect(values.minOrder).toBe(250)
expect(values.maxLimitForUser).toBe(3)
})
it('ACOUPF-11: the validity date is submitted as an ISO string', async () => {
const { view, onSubmit } = renderForm()
const date = new Date('2026-01-15T10:30:00.000Z')
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
const picker = view.UNSAFE_getByType(DateTimePickerMod)
act(() => {
picker.props.setValue(date)
})
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].validTill).toBe(date.toISOString())
})
it('ACOUPF-12: exclusive and first-order toggles submit booleans', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
fireEvent.press(
view.getByText('Exclusive coupon (cannot be combined with other coupons)')
)
fireEvent.press(view.getByText("Valid only on the customer's first order"))
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].exclusiveApply).toBe(true)
expect(onSubmit.mock.calls[0][0].isFirstOrderOnly).toBe(true)
})
it('ACOUPF-13: All Users clears a previously selected user', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
await openUsersWith(view, [{ id: 5, name: 'Test User', mobile: '9876543210' }])
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('1 users selected')).toBeTruthy()
fireEvent.press(view.getByText('All Users'))
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].isApplyForAll).toBe(true)
expect(onSubmit.mock.calls[0][0].targetUsers).toEqual([])
})
it('ACOUPF-14: reserved coupons disable the target-audience fields', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
const checkbox = view.UNSAFE_getAllByType(Checkbox)[0]
act(() => {
checkbox.props.onPress?.()
})
expect(view.getByText('Target Audience (Disabled for Reserved Coupons)')).toBeTruthy()
fireEvent.press(view.getByText('Select users...'))
await flush()
expect(view.queryByText('Select Applicable Users')).toBeNull()
})
it('ACOUPF-15: the user selector supports search and selection', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
await openUsersWith(view, [{ id: 5, name: 'Test User', mobile: '9876543210' }])
expect(view.getByText(/Test User/)).toBeTruthy()
fireEvent.changeText(
view.getByPlaceholderText('Search users by name or mobile...'),
'Test'
)
// The query is debounced, so seed the response before the timer fires.
setProcedure('admin.coupon.getUsersMiniInfo', {
data: { users: [{ id: 5, name: 'Test User', mobile: '9876543210' }], count: 1 },
})
await waitForUserSearchDebounce()
expect(lastProcedureInput('admin.coupon.getUsersMiniInfo')).toEqual({
search: 'Test',
limit: 10,
offset: 0,
})
expect(view.getByText(/Test User/)).toBeTruthy()
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('1 users selected')).toBeTruthy()
})
it('ACOUPF-16: the user query stays disabled until the dialog opens', async () => {
const { view } = renderForm()
expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(0)
openUsers(view)
await flush(2)
expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(1)
})
it('ACOUPF-18: rapid typing is debounced into a single user-search request', async () => {
const { view } = renderForm()
await openUsersWith(view, [{ id: 5, name: 'Test User', mobile: '9876543210' }])
const input = view.getByPlaceholderText('Search users by name or mobile...')
for (const value of ['9', '96', '967', '9676']) {
fireEvent.changeText(input, value)
}
await flush(2)
// Still only the request made when the dialog opened; the debounce has not elapsed.
expect(procedureQueryCalls('admin.coupon.getUsersMiniInfo')).toHaveLength(1)
await waitForUserSearchDebounce()
const calls = procedureQueryCalls('admin.coupon.getUsersMiniInfo')
expect(calls).toHaveLength(2)
expect(calls[1]).toMatchObject({ search: '9676', limit: 10, offset: 0 })
})
it('ACOUPF-17: selecting and deselecting a user updates applicableUsers', async () => {
setProcedure('admin.coupon.getUsersMiniInfo', {
data: {
users: [
{ id: 5, name: 'Test User', mobile: '9876543210' },
{ id: 6, name: 'Second User', mobile: '9876543211' },
],
count: 2,
},
})
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
const users = [
{ id: 5, name: 'Test User', mobile: '9876543210' },
{ id: 6, name: 'Second User', mobile: '9876543211' },
]
await openUsersWith(view, users)
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText(/Second User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('2 users selected')).toBeTruthy()
await openUsersWith(view, users)
fireEvent.press(view.getByText(/Test User/))
fireEvent.press(view.getByText('Done'))
expect(view.getByText('1 users selected')).toBeTruthy()
await submit(view)
expect(onSubmit.mock.calls[0][0].applicableUsers).toEqual([6])
})
it('ACOUPF-18: product selection submits skuIds, empty means the whole cart', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
choosePercent(view, 10)
expect(
view.getByText('No products selected - the coupon applies to the whole cart.')
).toBeTruthy()
await flush()
fireEvent.press(view.getByTestId('coupon-products-selector'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-11'))
fireEvent.press(view.getByTestId('coupon-products-selector-done'))
await submit(view)
expect(onSubmit.mock.calls[0][0].skuIds).toEqual([11])
})
it('ACOUPF-19: the product count copy reflects the selection', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10')
await flush()
fireEvent.press(view.getByTestId('coupon-products-selector'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-11'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-13'))
fireEvent.press(view.getByTestId('coupon-products-selector-done'))
expect(
view.getByText('2 product(s) selected - the coupon discounts only these items.')
).toBeTruthy()
})
it('ACOUPF-20: a code ending in digits reveals Add Multiple', () => {
const { view } = renderForm()
expect(view.queryByText('Add Multiple')).toBeNull()
fireEvent.changeText(codeInput(view), 'ABC12')
expect(view.getByText('Add Multiple')).toBeTruthy()
})
it('ACOUPF-21: Add Multiple generates sequential codes from the highest', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'ABC12')
fireEvent.press(view.getByText('Add Multiple'))
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), '3')
fireEvent.press(view.getByText('Generate'))
await flush()
expect(codeInputs(view).map((input) => input.props.value)).toEqual([
'ABC12',
'ABC13',
'ABC14',
'ABC15',
])
})
it('ACOUPF-22: generating 0 or more than 100 codes changes nothing', async () => {
const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'ABC12')
fireEvent.press(view.getByText('Add Multiple'))
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), '0')
fireEvent.press(view.getByText('Generate'))
expect(codeInputs(view)).toHaveLength(1)
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), '101')
fireEvent.press(view.getByText('Generate'))
expect(codeInputs(view)).toHaveLength(1)
})
it('ACOUPF-23: duplicate codes are rejected', async () => {
const { view, onSubmit } = renderForm({
initialValues: {
...BASE_INITIAL,
couponCodes: ['SAVE10', 'SAVE10'],
discountPercent: 10,
} as any,
})
await submit(view)
expect(onSubmit).not.toHaveBeenCalled()
expect(view.getAllByText('Coupon codes must be unique').length).toBeGreaterThan(0)
})
it('ACOUPF-24: a valid form submits the normalised values', async () => {
const { view, onSubmit } = renderForm()
fireEvent.changeText(codeInput(view), 'save10')
choosePercent(view, 12)
fireEvent.changeText(view.getByPlaceholderText('e.g., 200'), '100')
await submit(view)
expect(onSubmit).toHaveBeenCalledTimes(1)
const values = onSubmit.mock.calls[0][0]
expect(values.couponCodes).toEqual(['SAVE10'])
expect(values.discountPercent).toBe(12)
expect(values.maxValue).toBe(100)
expect(values.isReservedCoupon).toBe(false)
})
})