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

218 lines
6.7 KiB
TypeScript

/**
* Edit coupon screen (app/(drawer)/dashboard/coupons/edit/[id].tsx) — hydrates
* CouponForm from getById and dispatches the update mutation.
*/
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 EditCoupon from '@/app/(drawer)/dashboard/coupons/edit/[id]'
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 coupon = {
id: 5,
couponCode: 'EDIT10',
isUserBased: false,
discountPercent: '10',
flatDiscount: null,
minOrder: '100',
skuIds: [],
maxValue: '50',
isApplyForAll: true,
validTill: '2099-01-01T00:00:00.000Z',
maxLimitForUser: 2,
exclusiveApply: false,
isFirstOrderOnly: false,
isInvalidated: false,
createdBy: 1,
targetUser: { id: 3, name: 'shafi', mobile: '9999999999' },
applicableUsers: [],
applicableProducts: [],
}
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?.())
}
describe('Edit coupon', () => {
beforeEach(() => {
resetStaffAuthMock()
searchParamsMock.current = { id: '5' }
routerMock.back.mockClear()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('shows loading while getById is pending', () => {
setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
renderWithProviders(<EditCoupon />)
expect(screen.getByText('Loading...')).toBeVisible()
})
it('requests the coupon by the route id', async () => {
const { fetchMock } = setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
renderWithProviders(<EditCoupon />)
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.getById'))
expect(lastProcedureInput(fetchMock, 'admin.coupon.getById')).toEqual({ id: 5 })
})
it('prefills the form from the fetched coupon', async () => {
setupApiMocks({ procedures: { 'admin.coupon.getById': coupon } })
renderWithProviders(<EditCoupon />)
expect(await screen.findByDisplayValue('EDIT10')).toBeVisible()
expect(screen.getByDisplayValue('10')).toBeVisible()
expect(screen.getByDisplayValue('100')).toBeVisible()
})
it('shows a not-found state when the coupon does not exist', async () => {
setupApiMocks({ procedures: { 'admin.coupon.getById': null } })
renderWithProviders(<EditCoupon />)
expect(await screen.findByText('Coupon not found')).toBeVisible()
})
it('dispatches update with the transformed payload', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': { ...coupon },
},
})
renderWithProviders(<EditCoupon />)
await screen.findByDisplayValue('EDIT10')
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.update'))
const input = lastProcedureInput(fetchMock, 'admin.coupon.update') as {
id: number
updates: Record<string, unknown>
}
expect(input.id).toBe(5)
expect(input.updates).toMatchObject({
couponCodes: ['EDIT10'],
discountPercent: 10,
minOrder: 100,
maxValue: 50,
isApplyForAll: true,
isUserBased: false,
targetUser: 3,
isReservedCoupon: false,
})
expect(input.updates.targetUsers).toBeUndefined()
})
it('does not call update before the coupon loads', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getById': () => new Promise(() => {}),
},
})
renderWithProviders(<EditCoupon />)
expect(procCount(fetchMock, 'admin.coupon.update')).toBe(0)
})
it('alerts the update error message', async () => {
setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': () => {
throw new Error('Cannot have both discountPercent and flatDiscount')
},
},
})
renderWithProviders(<EditCoupon />)
await screen.findByDisplayValue('EDIT10')
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Error',
'Cannot have both discountPercent and flatDiscount'
)
)
})
it('alerts success and navigates back after update', async () => {
setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': { ...coupon },
},
})
renderWithProviders(<EditCoupon />)
await screen.findByDisplayValue('EDIT10')
fireEvent.press(screen.getByText('Create Coupon'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith(
'Success',
'Coupon updated successfully',
expect.any(Array)
)
)
pressLastAlertButton('OK')
expect(routerMock.back).toHaveBeenCalled()
})
it('refetches the mounted coupon and invalidates both coupon lists by path after update', async () => {
const { fetchMock } = setupApiMocks({
procedures: {
'admin.coupon.getById': coupon,
'admin.coupon.update': { ...coupon },
},
})
const client = createQueryClient()
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
renderWithProviders(<EditCoupon />, { queryClient: client })
await screen.findByDisplayValue('EDIT10')
// These suites share a module-singleton tRPC client, so baseline the count
// right before the interaction and assert a delta, never an absolute number.
const before = procCount(fetchMock, 'admin.coupon.getById')
fireEvent.press(screen.getByText('Create Coupon'))
// (a) the mounted getById query really refetches.
await waitFor(() =>
expect(procCount(fetchMock, 'admin.coupon.getById')).toBeGreaterThan(before)
)
// (b) the two list invalidations used the ARRAY path, not a dotted string.
const invalidatedPaths = () =>
invalidateSpy.mock.calls.map((call) => {
const key = (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey
return Array.isArray(key) ? key[0] : null
})
await waitFor(() =>
expect(invalidatedPaths()).toContainEqual(['admin', 'coupon', 'getAll'])
)
expect(invalidatedPaths()).toContainEqual([
'admin',
'coupon',
'getReservedCoupons',
])
})
})