freshyo/apps/admin-ui/tests/screens/coupons-create.test.tsx
2026-10-01 00:33:03 +05:30

199 lines
7 KiB
TypeScript

/**
* 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'
)
)
})
})