/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 20 — edit profile * (`app/(drawer)/(tabs)/me/edit-profile/index.tsx`, PROFILE-01..20). * * Profile updates go through `useUpdateProfile` (and therefore * `user.auth.updateProfile`); the password and delete flows are separate * dialogs. The auth context is replaced by the deterministic harness mock so * `updateUserDetails` and `logout` can be asserted. */ import React from 'react' import { Alert, Modal } from 'react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native' import { MyButton } from 'common-ui' import * as ImagePicker from 'expo-image-picker' import EditProfile from '@/app/(drawer)/(tabs)/me/edit-profile/index' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { setProcedure, lastMutationInput, procedureMutationCalls, } from '../mocks/trpc-client' import { __setAuthState, logout, updateUserDetails } from '../mocks/auth-context' import { router } from '../mocks/expo-router-mock' import { AUTH_USER, AUTH_USER_FULL } from '../fixtures' jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) const UPLOAD_URL = 'https://bucket.test/profile/upload-1.jpg' // extractKeyFromPresignedUrl drops the bucket segment: bucket/profile/. const UPLOAD_KEY = 'upload-1.jpg' const picker = ImagePicker.launchImageLibraryAsync as unknown as jest.Mock let alertSpy: jest.SpyInstance function signIn(userDetails: any = AUTH_USER_FULL) { __setAuthState({ isAuthenticated: true, isLoading: false, user: userDetails, userDetails, }) } function renderPage() { return renderWithProviders(, { auth: 'in' }) } async function submit(get: (id: string) => any) { fireEvent.press(get('registration-submit-button')) await flush() } function mockFetch() { const fn = jest.fn(async (_url: string, init?: any) => { if (init?.method === 'PUT') { return { ok: true, status: 200 } as any } return { ok: true, status: 200, blob: async () => ({ size: 4 }) } as any }) ;(global as any).fetch = fn return fn } function mockPickerOnce(asset: any) { picker.mockResolvedValueOnce({ canceled: false, assets: [asset] }) } async function pickImage(get: (id: string) => any) { mockPickerOnce({ uri: 'file:///avatar.png', mimeType: 'image/png', fileName: 'avatar.png' }) fireEvent.press(get('profile-image-picker')) await flush() } async function openDeleteDialog(get: (id: string) => any) { fireEvent.press(get('delete-account-button')) await flush() } async function openPasswordDialog(get: (id: string) => any) { fireEvent.press(get('registration-update-password-button')) await flush() } function alertButtons(callIndex = -1) { const calls = alertSpy.mock.calls return calls[calls.length + callIndex]?.[2] ?? [] } describe('Edit profile (PROFILE-01..PROFILE-20)', () => { beforeEach(() => { resetAllMocks() picker.mockReset() picker.mockResolvedValue({ canceled: true, assets: null }) signIn() alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) }) it('PROFILE-01: the signed-in user details are prefilled', async () => { const { getByTestId } = renderPage() expect(getByTestId('registration-name-input').props.value).toBe(AUTH_USER_FULL.name) expect(getByTestId('registration-email-input').props.value).toBe(AUTH_USER_FULL.email) expect(getByTestId('registration-mobile-input').props.value).toBe(AUTH_USER_FULL.mobile) await waitFor(() => expect(getByTestId('expo-image').props.accessibilityLabel).toBe( AUTH_USER_FULL.profileImage ) ) }) it('PROFILE-02: without user details the form fields are empty', () => { signIn(null) const { getByTestId } = renderPage() expect(getByTestId('registration-name-input').props.value).toBe('') expect(getByTestId('registration-email-input').props.value).toBe('') expect(getByTestId('registration-mobile-input').props.value).toBe('') }) it('PROFILE-03: updating calls updateProfile, updates the context and replaces to me', async () => { const { getByTestId } = renderPage() fireEvent.changeText(getByTestId('registration-name-input'), 'Updated Name') await submit(getByTestId) expect(lastMutationInput('user.auth.updateProfile')).toEqual({ name: 'Updated Name', email: AUTH_USER_FULL.email, mobile: AUTH_USER_FULL.mobile, }) expect(updateUserDetails).toHaveBeenCalledWith(AUTH_USER) expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/me') }) it('PROFILE-04: a failed update keeps the form and does not navigate or log out', async () => { setProcedure('user.auth.updateProfile', { mode: 'error', error: new Error('update boom') }) const { getByTestId } = renderPage() fireEvent.changeText(getByTestId('registration-name-input'), 'Broken') const submission = fireEvent.press(getByTestId('registration-submit-button')) await act(async () => { await Promise.resolve(submission).catch(() => undefined) }) await flush() expect(getByTestId('registration-name-input')).toBeTruthy() expect(router.replace).not.toHaveBeenCalled() expect(logout).not.toHaveBeenCalled() // Current gap: the page does not alert on a rejected update. expect(alertSpy).not.toHaveBeenCalled() }) it('PROFILE-05: a pending update shows Updating... on a disabled button', async () => { setProcedure('user.auth.updateProfile', { mode: 'pending' }) const { getByTestId, getByText } = renderPage() fireEvent.press(getByTestId('registration-submit-button')) await flush() expect(getByText('Updating...')).toBeTruthy() expect(getByTestId('registration-submit-button')).toBeDisabled() }) it('PROFILE-06: an empty email is blocked by the form (catalogue: accepted)', async () => { const { getByTestId, getByText } = renderPage() fireEvent.changeText(getByTestId('registration-email-input'), '') await flush() await submit(getByTestId) // Current implementation gap: the Controller still carries the // unconditional `required` rule, so an empty email never reaches the // update mutation even though the manual guard skips it in edit mode. expect(getByText('Email is required')).toBeTruthy() expect(procedureMutationCalls('user.auth.updateProfile')).toHaveLength(0) }) it('PROFILE-07: the update payload never contains a password field', async () => { const { getByTestId } = renderPage() await submit(getByTestId) expect('password' in lastMutationInput('user.auth.updateProfile')).toBe(false) }) it('PROFILE-08: password changes use updatePassword, not updateProfile', async () => { const { getByTestId } = renderPage() await openPasswordDialog(getByTestId) fireEvent.changeText(getByTestId('password-dialog-password-input'), 'secret1') fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), 'secret1') fireEvent.press(getByTestId('password-dialog-update-button')) await flush() expect(lastMutationInput('user.auth.updatePassword')).toEqual({ password: 'secret1' }) expect(procedureMutationCalls('user.auth.updateProfile')).toHaveLength(0) }) it('PROFILE-09: a picked profile image is uploaded and its key is sent', async () => { setProcedure('common.generateUploadUrls', { data: { uploadUrls: [UPLOAD_URL] } }) mockFetch() const { getByTestId } = renderPage() await pickImage(getByTestId) await submit(getByTestId) await waitFor(() => expect(procedureMutationCalls('user.auth.updateProfile')).toHaveLength(1)) expect(lastMutationInput('common.generateUploadUrls')).toEqual({ contextString: 'profile', mimeTypes: ['image/png'], }) expect(lastMutationInput('user.auth.updateProfile')).toEqual({ name: AUTH_USER_FULL.name, email: AUTH_USER_FULL.email, mobile: AUTH_USER_FULL.mobile, profileImageUrl: UPLOAD_KEY, }) }) it('PROFILE-10: Logout calls the auth logout', () => { const { getByTestId } = renderPage() fireEvent.press(getByTestId('edit-profile-logout-button')) expect(logout).toHaveBeenCalledTimes(1) }) it('PROFILE-11: Delete Me and My Data opens the delete dialog', async () => { const { getByTestId } = renderPage() await openDeleteDialog(getByTestId) expect(getByTestId('delete-account-dialog')).toBeTruthy() expect(getByTestId('delete-account-mobile-input')).toBeTruthy() }) it('PROFILE-12: the delete dialog cannot be dismissed by its backdrop', async () => { const view = renderPage() await openDeleteDialog(view.getByTestId) const visibleModal = view.UNSAFE_getAllByType(Modal).find((modal) => modal.props.visible) expect(visibleModal).toBeTruthy() expect(visibleModal?.props.onRequestClose).toBeUndefined() }) it('PROFILE-13: an empty mobile alerts and skips deleteAccount', async () => { const { getByTestId } = renderPage() await openDeleteDialog(getByTestId) fireEvent.press(getByTestId('delete-account-confirm-button')) await flush() expect(alertSpy).toHaveBeenCalledWith('Error', 'Please enter your mobile number') expect(procedureMutationCalls('user.auth.deleteAccount')).toHaveLength(0) }) it('PROFILE-14: confirming delete sends the entered mobile', async () => { const { getByTestId } = renderPage() await openDeleteDialog(getByTestId) fireEvent.changeText(getByTestId('delete-account-mobile-input'), '9876543210') fireEvent.press(getByTestId('delete-account-confirm-button')) await flush() expect(lastMutationInput('user.auth.deleteAccount')).toEqual({ mobile: '9876543210' }) }) it('PROFILE-15: a pending delete puts Delete Forever into its loading state', async () => { setProcedure('user.auth.deleteAccount', { mode: 'pending' }) const view = renderPage() await openDeleteDialog(view.getByTestId) fireEvent.changeText(view.getByTestId('delete-account-mobile-input'), '9876543210') fireEvent.press(view.getByTestId('delete-account-confirm-button')) await flush() expect(procedureMutationCalls('user.auth.deleteAccount')).toHaveLength(1) // Current implementation passes `loading` but not `disabled`; Paper renders // the indicator while the underlying button stays pressable. const confirm = view .UNSAFE_getAllByType(MyButton) .find((button) => button.props.testID === 'delete-account-confirm-button') expect(confirm?.props.loading).toBe(true) }) it('PROFILE-16: a rejected delete alerts and keeps the dialog open', async () => { setProcedure('user.auth.deleteAccount', { mode: 'error', error: new Error('No such mobile'), }) const { getByTestId, queryByTestId } = renderPage() await openDeleteDialog(getByTestId) fireEvent.changeText(getByTestId('delete-account-mobile-input'), '9876543210') fireEvent.press(getByTestId('delete-account-confirm-button')) await flush() expect(alertSpy).toHaveBeenCalledWith('Verification Failed', 'No such mobile') expect(queryByTestId('delete-account-dialog')).not.toBeNull() }) it('PROFILE-17: a successful delete alerts, closes the dialog and logs out on OK', async () => { const { getByTestId, queryByTestId } = renderPage() await openDeleteDialog(getByTestId) fireEvent.changeText(getByTestId('delete-account-mobile-input'), '9876543210') fireEvent.press(getByTestId('delete-account-confirm-button')) await flush() expect(alertSpy).toHaveBeenCalledWith( 'Account Deleted', 'Your account and all data have been successfully deleted.', expect.any(Array) ) const ok = alertButtons().find((button: any) => button.text === 'OK') await act(async () => { ok?.onPress?.() }) await flush() expect(logout).toHaveBeenCalledTimes(1) expect(queryByTestId('delete-account-dialog')).toBeNull() }) it('PROFILE-18: the delete mobile input enforces a max length of 15', async () => { const { getByTestId } = renderPage() await openDeleteDialog(getByTestId) expect(getByTestId('delete-account-mobile-input').props.maxLength).toBe(15) }) it('PROFILE-19: cancelling delete closes the dialog without an API call', async () => { const { getByTestId, queryByTestId } = renderPage() await openDeleteDialog(getByTestId) fireEvent.press(getByTestId('delete-account-cancel-button')) await flush() expect(queryByTestId('delete-account-dialog')).toBeNull() expect(procedureMutationCalls('user.auth.deleteAccount')).toHaveLength(0) }) it('PROFILE-20: the password dialog opens and validates like REG-30..35', async () => { const { getByTestId, queryByTestId } = renderPage() await openPasswordDialog(getByTestId) expect(getByTestId('password-dialog-password-input')).toBeTruthy() expect(getByTestId('password-dialog-confirm-password-input')).toBeTruthy() fireEvent.changeText(getByTestId('password-dialog-password-input'), 'secret1') fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), 'other12') fireEvent.press(getByTestId('password-dialog-update-button')) await flush() expect(alertSpy).toHaveBeenCalledWith('Error', 'Passwords do not match') expect(procedureMutationCalls('user.auth.updatePassword')).toHaveLength(0) fireEvent.press(getByTestId('password-dialog-cancel-button')) await flush() expect(queryByTestId('password-dialog-password-input')).toBeNull() }) })