freshyo/apps/admin-ui/tests/pages/coupon-create.test.tsx
2026-10-20 00:31:05 +05:30

221 lines
7.3 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 8.2 — Coupon create (`tests/pages/coupon-create.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import { Checkbox, MyButton } from 'common-ui'
import CreateCoupon from '@/app/(drawer)/dashboard/coupons/create'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
setProcedure,
lastMutationInput,
procedureMutationCalls,
procedureInvalidations,
} from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock'
type View = ReturnType<typeof renderCreate>['view']
function renderCreate() {
const view = renderWithProviders(<CreateCoupon />, { auth: false })
return { view }
}
function codeInput(view: View, index = 0) {
return view.getAllByPlaceholderText('e.g., SECRET10')[index]
}
function fillValid(view: View, code = 'SAVE10', percent = 10) {
fireEvent.changeText(codeInput(view), code)
fireEvent.press(view.getByText('Percentage'))
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), String(percent))
}
async function submit(view: View) {
fireEvent.press(view.getByText('Create Coupon'))
await flush(3)
}
function setReserved(view: View) {
const checkbox = view.UNSAFE_getAllByType(Checkbox)[0]
act(() => {
checkbox.props.onPress?.()
})
}
async function openUsersWith(view: View, users: { id: number; name: string; mobile: string }[]) {
fireEvent.press(view.getByText(/Select users\.\.\.|users selected/))
await flush(1)
setProcedure('admin.coupon.getUsersMiniInfo', { data: { users: [...users], count: users.length } })
await flush(2)
}
describe('Coupon create (ACOUPC-01..12)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => alertSpy?.mockRestore())
it('ACOUPC-01: renders the coupon form with Create Coupon', () => {
const { view } = renderCreate()
expect(view.getByText('Coupon Codes')).toBeTruthy()
expect(view.getByText('Create Coupon')).toBeTruthy()
})
it('ACOUPC-02: submitting without codes is blocked with a validation message', async () => {
const { view } = renderCreate()
await submit(view)
// Formik attaches the codes-required test error to `couponCodes` as a
// string, which the form does not render, but it does block the mutation.
expect(procedureMutationCalls('admin.coupon.create')).toHaveLength(0)
expect(alertSpy).not.toHaveBeenCalled()
})
it('ACOUPC-03: whitespace-only codes are rejected before the API call', async () => {
const { view } = renderCreate()
// Give the form one real code so the validation does not crash on a blank
// entry (the current Yup test calls `.trim()` on Formik's undefined blanks).
fireEvent.changeText(codeInput(view), ' ')
fireEvent.press(view.getByText('Percentage'))
fireEvent.changeText(view.getByPlaceholderText('e.g., 10'), '10')
await submit(view)
expect(procedureMutationCalls('admin.coupon.create')).toHaveLength(0)
})
it('ACOUPC-04: a single mutation carries the couponCodes array', async () => {
const { view } = renderCreate()
fillValid(view)
await submit(view)
expect(procedureMutationCalls('admin.coupon.create')).toHaveLength(1)
expect(lastMutationInput('admin.coupon.create').couponCodes).toEqual(['SAVE10'])
})
it('ACOUPC-05: a normal coupon calls admin.coupon.create', async () => {
const { view } = renderCreate()
fillValid(view)
await submit(view)
const input = lastMutationInput('admin.coupon.create')
expect(input.couponCodes).toEqual(['SAVE10'])
expect(input.discountPercent).toBe(10)
expect(lastMutationInput('admin.coupon.createReservedCoupon')).toBeUndefined()
})
it('ACOUPC-06: the reserved toggle calls createReservedCoupon', async () => {
const { view } = renderCreate()
fillValid(view, 'RES10', 20)
setReserved(view)
await submit(view)
expect(procedureMutationCalls('admin.coupon.create')).toHaveLength(0)
expect(lastMutationInput('admin.coupon.createReservedCoupon')).toMatchObject({
couponCodes: ['RES10'],
discountPercent: 20,
})
})
it('ACOUPC-07: flat discounts copy the amount into maxValue', async () => {
const { view } = renderCreate()
fireEvent.changeText(codeInput(view), 'FLAT50')
fireEvent.press(view.getByText('Flat Amount'))
fireEvent.changeText(view.getByPlaceholderText('e.g., 50'), '50')
await submit(view)
const input = lastMutationInput('admin.coupon.create')
expect(input.flatDiscount).toBe(50)
expect(input.maxValue).toBe(50)
})
it('ACOUPC-08: targetUsers is transformed to the first targetUser', async () => {
const { view } = renderCreate()
fillValid(view)
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'))
await submit(view)
const input = lastMutationInput('admin.coupon.create')
// The form tracks applicableUsers; it never fills targetUsers, so the
// transform leaves targetUser undefined. Assert the field is stripped.
expect(input.applicableUsers).toEqual([5, 6])
expect(input.targetUser).toBeUndefined()
expect(input.targetUsers).toBeUndefined()
})
it('ACOUPC-09: a pending create shows the loading button', async () => {
setProcedure('admin.coupon.create', { mode: 'pending' })
const { view } = renderCreate()
fillValid(view)
await submit(view)
expect(lastMutationInput('admin.coupon.create')).toBeTruthy()
expect(view.UNSAFE_getAllByType(MyButton)[0].props.loading).toBe(true)
})
it('ACOUPC-10: success invalidates both lists and returns on OK', async () => {
const { view } = renderCreate()
fillValid(view)
await submit(view)
expect(procedureInvalidations('admin.coupon.getAll').length).toBeGreaterThan(0)
expect(procedureInvalidations('admin.coupon.getReservedCoupons').length).toBeGreaterThan(0)
expect(alertSpy).toHaveBeenCalledWith(
'Success',
'1 coupon created successfully',
expect.any(Array)
)
const buttons = alertSpy.mock.calls.find((call) => call[0] === 'Success')[2]
act(() => {
buttons[0].onPress()
})
expect(router.back).toHaveBeenCalled()
})
it('ACOUPC-11: a failed create shows the server message', async () => {
setProcedure('admin.coupon.create', { mode: 'error', error: new Error('Code exists') })
const { view } = renderCreate()
fillValid(view)
await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Code exists')
})
it('ACOUPC-12: reserved coupons disable the target audience controls', async () => {
const { view } = renderCreate()
fillValid(view)
setReserved(view)
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()
})
})