/** * Coupons list screen (app/(drawer)/dashboard/coupons/index.tsx) — the two * TabView tabs (General / Reserved), infinite pagination, search, delete and * navigation to create/edit. * * HARNESS BUG WORKAROUND: tests/mocks/native.ts `tabViewMock` is internally * inconsistent — its `SceneMap` returns the scenes object while `TabView` * invokes `renderScene({ route })` as a function, so rendering this screen * throws `TypeError: renderScene is not a function`. Its tab press also * hardcodes `onIndexChange(0)`. We override the module locally with a corrected * copy (the harness file itself is untouched). See the final report. */ jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) jest.mock('react-native-tab-view', () => { const React = require('react') const { View, Text } = require('react-native') const TabView = ({ navigationState, renderScene, onIndexChange, }: { navigationState: { index: number; routes: { key: string }[] } renderScene: (info: { route: { key: string } }) => React.ReactNode onIndexChange?: (index: number) => void }) => { const route = navigationState.routes[navigationState.index] return React.createElement( View, { testID: 'mock-tab-view' }, navigationState.routes.map((r, i) => React.createElement( Text, { key: r.key, testID: `tab-${r.key}`, onPress: () => onIndexChange?.(i) }, r.key ) ), route ? renderScene({ route }) : null ) } return { __esModule: true, TabView, SceneMap: (scenes: Record) => ({ route }: { route: { key: string } }) => { const Scene = scenes[route.key] return React.createElement(Scene) }, TabBar: () => null, } }) import React from 'react' import { Alert, FlatList } from 'react-native' import { act, fireEvent, screen, waitFor } from '@testing-library/react-native' import Coupons from '@/app/(drawer)/dashboard/coupons/index' import { setupApiMocks } from '../mocks/api' import { lastProcedureInput, expectProcedureCalled, procCount } from '../mocks/procedures' import { resetStaffAuthMock } from '../mocks/staff-auth' import { searchParamsMock, routerMock } from '../mocks/router' import { renderWithProviders } from '../helpers/render' const activeCoupon = { id: 1, couponCode: 'SAVE10', isUserBased: false, discountPercent: '10', flatDiscount: null, minOrder: null, skuIds: null, maxValue: null, isApplyForAll: true, validTill: '2099-01-01T00:00:00.000Z', maxLimitForUser: null, exclusiveApply: false, isFirstOrderOnly: false, isInvalidated: false, createdBy: 1, applicableUsers: [], applicableProducts: [], } const expiredCoupon = { ...activeCoupon, id: 2, couponCode: 'OLDCODE', flatDiscount: '50', discountPercent: null, validTill: '2000-01-01T00:00:00.000Z', } const reservedCoupon = { id: 9, secretCode: 'SECRET9', couponCode: 'SECRET9', discountPercent: '20', flatDiscount: null, minOrder: null, maxValue: null, validTill: '2099-01-01T00:00:00.000Z', isRedeemed: false, redeemedUser: null, redeemedAt: null, creator: { id: 1, name: 'shafi' }, } 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 }[] const button = buttons.find((b) => b.text === label) act(() => button?.onPress?.()) } describe('Coupons index', () => { beforeEach(() => { resetStaffAuthMock() searchParamsMock.current = {} jest.spyOn(Alert, 'alert').mockImplementation(() => {}) routerMock.push.mockClear() }) it('shows a loading state while the list query is pending', () => { setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } }) renderWithProviders() expect(screen.getByText('Loading Coupons...')).toBeVisible() }) it('renders coupon rows from the getAll infinite query', async () => { setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon, expiredCoupon] } }, }) renderWithProviders() expect(await screen.findByText('SAVE10')).toBeVisible() expect(screen.getByText('OLDCODE')).toBeVisible() expect(screen.getByText('Discount: 10% off')).toBeVisible() expect(screen.getByText('Discount: ₹50 off')).toBeVisible() expect(screen.getAllByText('Expired').length).toBeGreaterThan(0) }) it('renders the empty state when there are no coupons', async () => { setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [] } } }) renderWithProviders() expect(await screen.findByText('No Coupons Found')).toBeVisible() }) it('renders the error state and retries on press', async () => { const { fetchMock } = setupApiMocks({ procedures: { 'admin.coupon.getAll': () => { throw new Error('boom') }, }, }) renderWithProviders() expect(await screen.findByText('Failed to load coupons')).toBeVisible() const before = procCount(fetchMock, 'admin.coupon.getAll') fireEvent.press(screen.getByText('Retry')) await waitFor(() => expect(procCount(fetchMock, 'admin.coupon.getAll')).toBeGreaterThan(before) ) }) it('fetches the next page when the list end is reached', async () => { const { fetchMock } = setupApiMocks({ procedures: { 'admin.coupon.getAll': (input: any) => input?.cursor ? { coupons: [{ ...activeCoupon, id: 3, couponCode: 'PAGE2' }] } : { coupons: [activeCoupon], nextCursor: 100 }, }, }) renderWithProviders() await screen.findByText('SAVE10') const list = screen.UNSAFE_getByType(FlatList as any) act(() => list.props.onEndReached()) expect(await screen.findByText('PAGE2')).toBeVisible() expect(lastProcedureInput(fetchMock, 'admin.coupon.getAll')).toMatchObject({ limit: 20, cursor: 100, }) }) it('sends the search term to getAll', async () => { const { fetchMock } = setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } }, }) renderWithProviders() await screen.findByText('SAVE10') fireEvent.changeText(screen.getByPlaceholderText('Search coupons...'), 'SAVE') await waitFor(() => expect(lastProcedureInput(fetchMock, 'admin.coupon.getAll')).toMatchObject({ limit: 20, search: 'SAVE', }) ) }) it('navigates to the create screen from the floating action button', async () => { setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } }) renderWithProviders() await screen.findByText('SAVE10') fireEvent.press(screen.getByTestId('mock-linear-gradient')) expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/create') }) it('navigates to the edit screen for the pressed coupon', async () => { setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] } } }) renderWithProviders() await screen.findByText('SAVE10') fireEvent.press(screen.getByText('Edit')) expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/dashboard/coupons/edit/1') }) it('deletes a coupon after confirming the alert', async () => { const { fetchMock } = setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] }, 'admin.coupon.delete': { message: 'Coupon invalidated successfully' }, }, }) renderWithProviders() await screen.findByText('SAVE10') fireEvent.press(screen.getByText('Delete')) expect(Alert.alert).toHaveBeenCalledWith( 'Delete Coupon', 'Are you sure you want to delete this coupon?', expect.any(Array) ) pressLastAlertButton('Delete') await waitFor(() => expectProcedureCalled(fetchMock, 'admin.coupon.delete')) expect(lastProcedureInput(fetchMock, 'admin.coupon.delete')).toEqual({ id: 1 }) await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith('Success', 'Coupon deleted successfully') ) }) it('switches to the Reserved tab and lists reserved coupons', async () => { setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] }, 'admin.coupon.getReservedCoupons': { coupons: [reservedCoupon] }, }, }) renderWithProviders() await screen.findByText('SAVE10') fireEvent.press(screen.getByTestId('tab-reserved')) expect(await screen.findByText('SECRET9')).toBeVisible() expect(screen.getByTestId('tab-reserved')).toBeVisible() }) it('shows the reserved empty state', async () => { setupApiMocks({ procedures: { 'admin.coupon.getAll': { coupons: [activeCoupon] }, 'admin.coupon.getReservedCoupons': { coupons: [] }, }, }) renderWithProviders() fireEvent.press(screen.getByTestId('tab-reserved')) expect(await screen.findByText('No Reserved Coupons Found')).toBeVisible() }) })