/* eslint-disable @typescript-eslint/no-explicit-any */ /** * REG-06 .. REG-37 — shared registration / edit-profile form. * * The form is rendered directly (no page wrapper) so the `onSubmit` spy and the * `user.auth.updatePassword` mutation are the only things that observe the * payload. Network is limited to the object-store upload path: procedure mocks * for `common.generateUploadUrls` and a `global.fetch` PUT spy. */ import React from 'react' import { Alert } from 'react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native' import * as ImagePicker from 'expo-image-picker' import RegistrationForm from '@/components/registration-form' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { setProcedure, lastProcedureInput, procedureCallCount, setRawFetchHandler, } from '../mocks/trpc-client' 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 /** * Serve the blob read + presigned PUT through the harness' non-tRPC fetch hook. * Replacing `global.fetch` outright would bypass the tRPC network mock. */ 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 }) setRawFetchHandler(fn as any) return fn } function mockPickerOnce(asset: any) { picker.mockResolvedValueOnce({ canceled: false, assets: [asset] }) } function renderForm(onSubmit: jest.Mock, extra: Record = {}) { return renderWithProviders(, { auth: false, }) } type Get = (id: string) => any /** Fill every field the register-mode form validates, with per-field overrides. */ function fillAllValid(get: Get, overrides: Record = {}) { const values = { name: 'Alice', email: 'alice@example.com', mobile: '9876543210', password: 'secret1', confirmPassword: 'secret1', terms: true, ...overrides, } fireEvent.changeText(get('registration-name-input'), values.name) fireEvent.changeText(get('registration-email-input'), values.email) fireEvent.changeText(get('registration-mobile-input'), values.mobile) fireEvent.changeText(get('registration-password-input'), values.password) fireEvent.changeText(get('registration-confirm-password-input'), values.confirmPassword) if (values.terms) fireEvent.press(get('registration-terms-toggle')) } async function submitForm(get: Get) { fireEvent.press(get('registration-submit-button')) await flush() } async function pickImage(get: Get, asset: any) { mockPickerOnce(asset) fireEvent.press(get('profile-image-picker')) await flush() } async function openPasswordDialog(get: Get) { fireEvent.press(get('registration-update-password-button')) await flush() } const EDIT_VALUES = { name: 'Bob', email: 'bob@example.com', mobile: '9876543210', profileImageUri: 'https://cdn.test/avatar.png', } describe('RegistrationForm (REG-06..REG-37)', () => { beforeEach(() => { resetAllMocks() picker.mockReset() picker.mockResolvedValue({ canceled: true, assets: null }) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) }) /* ---------------- name ---------------- */ it('REG-06: empty name shows "Name is required" and does not submit', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) await submitForm(getByTestId) expect(getByText('Name is required')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-07: one-character name shows the minimum-length error', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { name: 'A' }) await submitForm(getByTestId) expect(getByText('Name must be at least 2 characters')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-08: name surrounded by spaces is trimmed before validation and payload', async () => { const onSubmit = jest.fn() const { getByTestId } = renderForm(onSubmit) fillAllValid(getByTestId, { name: ' Alice ' }) await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) expect(onSubmit.mock.calls[0][0].name).toBe('Alice') }) /* ---------------- email ---------------- */ it('REG-09: empty email in registration shows "Email is required"', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { email: '' }) await submitForm(getByTestId) expect(getByText('Email is required')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-10: invalid email a@b shows the format error', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { email: 'a@b' }) await submitForm(getByTestId) expect(getByText('Please enter a valid email address')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-11: uppercase email is lowercased in the payload', async () => { const onSubmit = jest.fn() const { getByTestId } = renderForm(onSubmit) fillAllValid(getByTestId, { email: 'ALICE@EXAMPLE.COM' }) await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) expect(onSubmit.mock.calls[0][0].email).toBe('alice@example.com') }) it('REG-12: empty email in edit mode (catalogue: accepted — see report)', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit, { isEdit: true, initialValues: { name: 'Bob', email: '', mobile: '9876543210' }, }) await submitForm(getByTestId) // Current implementation: the Controller's unconditional `required` rule // still blocks submission, even though the manual guard skips email in // edit mode. Asserted as-is (documented as a catalogue/implementation gap). expect(getByText('Email is required')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) /* ---------------- mobile ---------------- */ it('REG-13: empty mobile shows "Mobile number is required"', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { mobile: '' }) await submitForm(getByTestId) expect(getByText('Mobile number is required')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-14: ten digits not starting 6-9 shows the format error', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { mobile: '1234567890' }) await submitForm(getByTestId) expect(getByText('Please enter a valid 10-digit mobile number')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-15: mobile input keeps digits only and never exceeds 10 digits', () => { const { getByTestId } = renderForm(jest.fn()) const input = getByTestId('registration-mobile-input') fireEvent.changeText(input, '98 76-54 32 10') expect(getByTestId('registration-mobile-input').props.value).toBe('9876543210') // 11 digits: the change is rejected, so the value stays at 10 digits. fireEvent.changeText(input, '98765432109') expect(getByTestId('registration-mobile-input').props.value).toBe('9876543210') }) /* ---------------- password + terms (register mode) ---------------- */ it('REG-16: empty password shows "Password is required"', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { password: '', confirmPassword: '' }) await submitForm(getByTestId) expect(getByText('Password is required')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-17: password shorter than 6 shows the minimum-length error', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { password: '123', confirmPassword: '123' }) await submitForm(getByTestId) expect(getByText('Password must be at least 6 characters')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-18: mismatched confirm password shows "Passwords do not match"', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { password: 'secret1', confirmPassword: 'nope123' }) await submitForm(getByTestId) expect(getByText('Passwords do not match')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-19: unaccepted terms show the terms error and do not submit', async () => { const onSubmit = jest.fn() const { getByTestId, getByText } = renderForm(onSubmit) fillAllValid(getByTestId, { terms: false }) await submitForm(getByTestId) expect(getByText('You must accept the terms and conditions')).toBeTruthy() expect(onSubmit).not.toHaveBeenCalled() }) /* ---------------- happy registration ---------------- */ it('REG-20: valid registration submits the normalized payload', async () => { const onSubmit = jest.fn() const { getByTestId } = renderForm(onSubmit) fillAllValid(getByTestId, { name: ' Alice ', email: 'Alice@Example.COM', mobile: '98765 43210', }) await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) expect(onSubmit).toHaveBeenCalledWith({ name: 'Alice', email: 'alice@example.com', mobile: '9876543210', password: 'secret1', }) }) /* ---------------- profile image upload ---------------- */ it('REG-21: selected image is uploaded and the payload carries profileImageUrl', async () => { const onSubmit = jest.fn() const fetchMock = mockFetch() setProcedure('common.generateUploadUrls', { data: { uploadUrls: [UPLOAD_URL] } }) const { getByTestId } = renderForm(onSubmit) await pickImage(getByTestId, { uri: 'file:///avatar.png', mimeType: 'image/png', fileName: 'avatar.png', }) fillAllValid(getByTestId) await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) expect(lastProcedureInput('common.generateUploadUrls')).toEqual({ contextString: 'profile', mimeTypes: ['image/png'], }) const putCall = fetchMock.mock.calls.find(([, init]: any) => init?.method === 'PUT') expect(putCall?.[0]).toBe(UPLOAD_URL) expect(putCall?.[1]).toEqual({ method: 'PUT', body: expect.anything(), headers: { 'Content-Type': 'image/png' }, }) expect(onSubmit.mock.calls[0][0]).toEqual({ name: 'Alice', email: 'alice@example.com', mobile: '9876543210', password: 'secret1', profileImageUrl: UPLOAD_KEY, }) }) it('REG-22: cancelled picker means no upload and no profileImageUrl key', async () => { const onSubmit = jest.fn() mockFetch() const { getByTestId } = renderForm(onSubmit) fireEvent.press(getByTestId('profile-image-picker')) await flush() fillAllValid(getByTestId) await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) expect(procedureCallCount('common.generateUploadUrls')).toBe(0) expect('profileImageUrl' in onSubmit.mock.calls[0][0]).toBe(false) }) it('REG-23: missing mime type falls back to image/jpeg', async () => { const onSubmit = jest.fn() const fetchMock = mockFetch() setProcedure('common.generateUploadUrls', { data: { uploadUrls: [UPLOAD_URL] } }) const { getByTestId } = renderForm(onSubmit) await pickImage(getByTestId, { uri: 'file:///avatar.png', fileName: 'avatar.png' }) fillAllValid(getByTestId) await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) expect(lastProcedureInput('common.generateUploadUrls')).toEqual({ contextString: 'profile', mimeTypes: ['image/jpeg'], }) const putCall = fetchMock.mock.calls.find(([, init]: any) => init?.method === 'PUT') expect(putCall?.[1].headers).toEqual({ 'Content-Type': 'image/jpeg' }) }) it('REG-24: a rejected upload rejects the submit and never calls onSubmit', async () => { const onSubmit = jest.fn() mockFetch() setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('upload boom'), }) const { getByTestId } = renderForm(onSubmit) await pickImage(getByTestId, { uri: 'file:///avatar.png', mimeType: 'image/png', fileName: 'avatar.png', }) fillAllValid(getByTestId) const submission = fireEvent.press(getByTestId('registration-submit-button')) await act(async () => { await expect(Promise.resolve(submission)).rejects.toThrow('upload boom') }) await flush() // No Alert is raised for upload failures in the current implementation. expect(alertSpy).not.toHaveBeenCalled() expect(onSubmit).not.toHaveBeenCalled() }) it('REG-25: pending upload shows "Uploading..." on a disabled button', async () => { const onSubmit = jest.fn() mockFetch() setProcedure('common.generateUploadUrls', { mode: 'pending' }) const { getByTestId, getByText } = renderForm(onSubmit) await pickImage(getByTestId, { uri: 'file:///avatar.png', mimeType: 'image/png', fileName: 'avatar.png', }) fillAllValid(getByTestId) fireEvent.press(getByTestId('registration-submit-button')) await flush() expect(getByText('Uploading...')).toBeTruthy() expect(getByTestId('registration-submit-button')).toBeDisabled() expect(onSubmit).not.toHaveBeenCalled() }) /* ---------------- edit mode ---------------- */ it('REG-26: edit mode hides register fields and swaps the actions', () => { const { getByTestId, getByText, queryByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES, }) expect(queryByTestId('registration-password-input')).toBeNull() expect(queryByTestId('registration-confirm-password-input')).toBeNull() expect(queryByTestId('registration-terms-toggle')).toBeNull() expect(getByText('Update Profile')).toBeTruthy() expect(getByTestId('registration-update-password-button')).toBeTruthy() expect(getByText('Update Password')).toBeTruthy() }) it('REG-27: edit mode prefills name, email, mobile and profile image', async () => { const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES }) expect(getByTestId('registration-name-input').props.value).toBe('Bob') expect(getByTestId('registration-email-input').props.value).toBe('bob@example.com') expect(getByTestId('registration-mobile-input').props.value).toBe('9876543210') await waitFor(() => expect(getByTestId('expo-image').props.accessibilityLabel).toBe( EDIT_VALUES.profileImageUri ) ) }) it('REG-28: edit submit sends name/email/mobile and omits password', async () => { const onSubmit = jest.fn() const { getByTestId } = renderForm(onSubmit, { isEdit: true, initialValues: EDIT_VALUES }) await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) const payload = onSubmit.mock.calls[0][0] expect(payload.name).toBe('Bob') expect(payload.email).toBe('bob@example.com') expect(payload.mobile).toBe('9876543210') expect(payload.password).toBeUndefined() }) it('REG-29: edit mode never renders password fields and the payload omits password', async () => { const onSubmit = jest.fn() const { getByTestId, queryByTestId } = renderForm(onSubmit, { isEdit: true, initialValues: EDIT_VALUES, }) expect(queryByTestId('registration-password-input')).toBeNull() expect(queryByTestId('registration-confirm-password-input')).toBeNull() await submitForm(getByTestId) await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1)) expect('password' in onSubmit.mock.calls[0][0]).toBe(false) }) it('REG-36: edit loading shows "Updating..." on a disabled button', () => { const { getByTestId, getByText } = renderForm(jest.fn(), { isEdit: true, isLoading: true, initialValues: EDIT_VALUES, }) expect(getByText('Updating...')).toBeTruthy() expect(getByTestId('registration-submit-button')).toBeDisabled() }) it('REG-37: ProfileImage receives the initial profile image URI', async () => { const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES }) await waitFor(() => expect(getByTestId('expo-image').props.accessibilityLabel).toBe( EDIT_VALUES.profileImageUri ) ) }) /* ---------------- password dialog ---------------- */ it('REG-30: mismatched dialog passwords alert and skip the mutation', async () => { const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES }) await openPasswordDialog(getByTestId) 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(procedureCallCount('user.auth.updatePassword')).toBe(0) }) it('REG-31: a short dialog password alerts and skips the mutation', async () => { const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES }) await openPasswordDialog(getByTestId) fireEvent.changeText(getByTestId('password-dialog-password-input'), '123') fireEvent.changeText(getByTestId('password-dialog-confirm-password-input'), '123') fireEvent.press(getByTestId('password-dialog-update-button')) await flush() expect(alertSpy).toHaveBeenCalledWith('Error', 'Password must be at least 6 characters') expect(procedureCallCount('user.auth.updatePassword')).toBe(0) }) it('REG-32: a valid dialog password mutates, alerts, closes and resets', async () => { const { getByTestId, queryByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES, }) 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() await waitFor(() => expect(lastProcedureInput('user.auth.updatePassword')).toEqual({ password: 'secret1' }) ) expect(alertSpy).toHaveBeenCalledWith('Success', 'Password updated successfully') expect(queryByTestId('password-dialog-password-input')).toBeNull() await openPasswordDialog(getByTestId) expect(getByTestId('password-dialog-password-input').props.value).toBe('') expect(getByTestId('password-dialog-confirm-password-input').props.value).toBe('') }) it('REG-33: a rejected password mutation alerts and keeps the dialog open', async () => { setProcedure('user.auth.updatePassword', { mode: 'error', error: new Error('nope') }) const { getByTestId, queryByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES, }) 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() await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope')) expect(queryByTestId('password-dialog-password-input')).not.toBeNull() }) it('REG-34: a pending password mutation disables the Update button', async () => { setProcedure('user.auth.updatePassword', { mode: 'pending' }) const { getByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES }) 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(getByTestId('password-dialog-update-button')).toBeDisabled() }) it('REG-35: cancelling the dialog closes it, calls no API and keeps the values', async () => { const { getByTestId, queryByTestId } = renderForm(jest.fn(), { isEdit: true, initialValues: EDIT_VALUES, }) 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-cancel-button')) await flush() expect(queryByTestId('password-dialog-password-input')).toBeNull() expect(procedureCallCount('user.auth.updatePassword')).toBe(0) // Current behaviour: closing does not reset the local dialog state. await openPasswordDialog(getByTestId) expect(getByTestId('password-dialog-password-input').props.value).toBe('secret1') expect(getByTestId('password-dialog-confirm-password-input').props.value).toBe('secret1') }) })