/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 24 — "ComplaintForm" (`tests/components/complaint-form.test.tsx`). * * Uploads run through `useUploadToObjectStorage`, so an image path needs: * - `common.generateUploadUrls` (tRPC mock) to hand back a presigned URL * - `expo-image-picker` to return an asset so `ImageUploaderNeo` calls `onImageAdd` * - a `global.fetch` spy (blob read + PUT) * The raise call itself is asserted through `lastProcedureInput('user.complaint.raise')`. */ import * as React from 'react' import { Alert } from 'react-native' import * as ImagePicker from 'expo-image-picker' import { fireEvent, waitFor } from '@testing-library/react-native' import { resetAllMocks } from '../helpers/reset' import { renderWithProviders, flush } from '../helpers/test-utils' import { expectNoProcedureCall, lastProcedureInput, procedureCallCount, setProcedure, setRawFetchHandler, } from '../mocks/trpc-client' import ComplaintForm from '@/components/ComplaintForm' const IMAGE_URL = 'https://cdn.test/photo.jpg' const PRESIGNED_URL = 'https://upload.test/complaint/abc.jpg' const UPLOADED_KEY = 'abc.jpg' /** * Serve the object-store calls (blob read + presigned PUT) through the harness' * non-tRPC fetch hook. Replacing `global.fetch` outright would bypass the tRPC * network mock. */ function installFetch() { const fetchSpy = jest.fn(async () => ({ ok: true, status: 200, blob: async () => ({}), })) setRawFetchHandler(fetchSpy as any) return fetchSpy } function queueImageAsset(uri = IMAGE_URL, mimeType = 'image/jpeg') { ;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValueOnce({ canceled: false, assets: [{ uri, mimeType, fileName: 'photo.jpg' }], }) } async function addImage(getByTestId: (id: string) => any) { queueImageAsset() fireEvent.press(getByTestId('complaint-images')) await waitFor(() => expect(getByTestId('complaint-images-remove')).toBeTruthy()) } function renderForm(overrides: { open?: boolean; onClose?: jest.Mock; orderId?: number } = {}) { const onClose = overrides.onClose ?? jest.fn() const result = renderWithProviders( , { auth: false } ) return { ...result, onClose } } describe('ComplaintForm', () => { let alertSpy: jest.SpyInstance beforeEach(() => { resetAllMocks() alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) }) it('CF-01: renders nothing while closed', () => { const { toJSON, queryByTestId } = renderForm({ open: false }) expect(toJSON()).toBeNull() expect(queryByTestId('complaint-body')).toBeNull() expect(queryByTestId('complaint-submit')).toBeNull() }) it('CF-02: a blank body alerts and raises nothing', async () => { const { getByTestId } = renderForm() fireEvent.press(getByTestId('complaint-submit')) expect(alertSpy).toHaveBeenCalledWith('Error', 'Please enter complaint details') expectNoProcedureCall('user.complaint.raise') fireEvent.changeText(getByTestId('complaint-body'), ' ') fireEvent.press(getByTestId('complaint-submit')) expect(procedureCallCount('user.complaint.raise')).toBe(0) expectNoProcedureCall('common.generateUploadUrls') }) it('CF-03: submits a body-only complaint, then resets and closes', async () => { const { getByTestId, onClose } = renderForm({ orderId: 42 }) fireEvent.changeText(getByTestId('complaint-body'), 'Cold items were delivered') fireEvent.press(getByTestId('complaint-submit')) await waitFor(() => expect(lastProcedureInput('user.complaint.raise')).toEqual({ orderId: '42', complaintBody: 'Cold items were delivered', imageUrls: [], }) ) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint raised successfully') ) expect(getByTestId('complaint-body').props.value).toBe('') await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1)) expectNoProcedureCall('common.generateUploadUrls') }) it('CF-04: uploads attached images and passes the returned keys', async () => { const fetchSpy = installFetch() setProcedure('common.generateUploadUrls', { data: { uploadUrls: [PRESIGNED_URL] } }) const { getByTestId, onClose } = renderForm({ orderId: 7 }) await addImage(getByTestId) fireEvent.changeText(getByTestId('complaint-body'), 'Wrong item delivered') fireEvent.press(getByTestId('complaint-submit')) await waitFor(() => expect(lastProcedureInput('user.complaint.raise')).toEqual({ orderId: '7', complaintBody: 'Wrong item delivered', imageUrls: [UPLOADED_KEY], }) ) // The upload URL request carries the picked mime type and complaint context. expect(lastProcedureInput('common.generateUploadUrls')).toEqual({ contextString: 'complaint', mimeTypes: ['image/jpeg'], }) // The blob is read from the picked uri and PUT to the presigned url. // (The harness' fetch calls the non-tRPC handler with `(url, init)`, so // match the read call by URL rather than by an exact argument list.) expect(fetchSpy.mock.calls.map(([url]: any[]) => url)).toContain(IMAGE_URL) expect(fetchSpy).toHaveBeenCalledWith( PRESIGNED_URL, expect.objectContaining({ method: 'PUT', headers: { 'Content-Type': 'image/jpeg' } }) ) await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1)) }) it('CF-05: alerts and does not raise when the upload fails', async () => { installFetch() setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('upload url boom'), }) const { getByTestId, onClose } = renderForm() await addImage(getByTestId) fireEvent.changeText(getByTestId('complaint-body'), 'Damaged meat') fireEvent.press(getByTestId('complaint-submit')) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'upload url boom')) expectNoProcedureCall('user.complaint.raise') expect(onClose).not.toHaveBeenCalled() }) it('CF-06: alerts and keeps the form open when raise fails', async () => { setProcedure('user.complaint.raise', { mode: 'error', error: new Error('raise boom') }) const { getByTestId, onClose } = renderForm() fireEvent.changeText(getByTestId('complaint-body'), 'Still cold') fireEvent.press(getByTestId('complaint-submit')) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'raise boom')) expect(getByTestId('complaint-body').props.value).toBe('Still cold') expect(onClose).not.toHaveBeenCalled() }) it('CF-07: disables the button and shows a spinner while pending/uploading', async () => { setProcedure('user.complaint.raise', { mode: 'pending' }) const pendingRaise = renderForm() fireEvent.changeText(pendingRaise.getByTestId('complaint-body'), 'Pending raise') fireEvent.press(pendingRaise.getByTestId('complaint-submit')) await waitFor(() => expect(pendingRaise.getByTestId('complaint-submit-spinner')).toBeTruthy()) expect(pendingRaise.queryByText('Submit Complaint')).toBeNull() expect( pendingRaise.getByTestId('complaint-submit').props.accessibilityState?.disabled ).toBe(true) pendingRaise.unmount() // Uploading state (presigned URL request never settles). installFetch() setProcedure('user.complaint.raise', { data: { success: true } }) setProcedure('common.generateUploadUrls', { mode: 'pending' }) const uploading = renderForm() await addImage(uploading.getByTestId) fireEvent.changeText(uploading.getByTestId('complaint-body'), 'Uploading') fireEvent.press(uploading.getByTestId('complaint-submit')) await waitFor(() => expect(uploading.getByTestId('complaint-submit-spinner')).toBeTruthy()) expect(uploading.queryByText('Submit Complaint')).toBeNull() expect( uploading.getByTestId('complaint-submit').props.accessibilityState?.disabled ).toBe(true) }) it('CF-08: removes an attached image from the list', async () => { const { getByTestId, queryByTestId } = renderForm() await addImage(getByTestId) expect(queryByTestId('complaint-images-remove')).toBeTruthy() fireEvent.press(getByTestId('complaint-images-remove')) await flush() expect(queryByTestId('complaint-images-remove')).toBeNull() // A subsequent raise therefore carries no image keys. fireEvent.changeText(getByTestId('complaint-body'), 'No images now') fireEvent.press(getByTestId('complaint-submit')) await waitFor(() => expect(lastProcedureInput('user.complaint.raise')).toEqual({ orderId: '42', complaintBody: 'No images now', imageUrls: [], }) ) }) it('CF-09: closes without touching the API', () => { const { getByTestId, onClose } = renderForm() fireEvent.press(getByTestId('complaint-close')) expect(onClose).toHaveBeenCalledTimes(1) expectNoProcedureCall('user.complaint.raise') expectNoProcedureCall('common.generateUploadUrls') }) })