/** * useUploadToObjectStorage (hooks/useUploadToObjectStore.ts) — requests * presigned URLs from `common.generateUploadUrls`, then PUTs each image in * parallel and extracts the object key from the presigned URL. * * Fake timers: mutations are driven with act() + waitFor(), never awaited * directly (see tests/screens/login.test.tsx for the pattern). */ jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) import React from 'react' import { act, renderHook, waitFor } from '@testing-library/react-native' import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore' import { resetStorage, setupApiMocks } from '../mocks/api' import { expectProcedureCalled, lastProcedureInput, procCount, } from '../mocks/procedures' import { Providers } from '../helpers/render' const wrapper = ({ children }: { children?: React.ReactNode }) => ( {children} ) const presigned = (key: string) => `https://meatfarmer.s3.amazonaws.com/meatfarmer/${key}` const blob = {} as Blob const jpeg = { blob, mimeType: 'image/jpeg' } const png = { blob, mimeType: 'image/png' } /** Kick off `upload` without awaiting it (fake timers would deadlock). */ const startUpload = ( result: { current: ReturnType }, input: Parameters['upload']>[0] ) => { let promise: Promise = Promise.resolve() act(() => { promise = result.current.upload(input) promise.catch(() => {}) }) return promise } describe('useUploadToObjectStorage', () => { beforeEach(async () => { await resetStorage() }) it('requests one presigned URL per image and uploads them in parallel', async () => { const { fetchMock } = setupApiMocks({ procedures: { 'common.generateUploadUrls': { uploadUrls: [ presigned('product-images/a.jpg'), presigned('product-images/b.png'), ], }, }, }) const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) const promise = startUpload(result, { images: [jpeg, png], contextString: 'product_info', }) await waitFor(() => expect(result.current.isUploading).toBe(false)) const uploaded = await promise expectProcedureCalled(fetchMock, 'common.generateUploadUrls', { times: 1 }) expect(lastProcedureInput(fetchMock, 'common.generateUploadUrls')).toEqual({ contextString: 'product_info', mimeTypes: ['image/jpeg', 'image/png'], }) expect(uploaded).toEqual({ keys: ['product-images/a.jpg', 'product-images/b.png'], presignedUrls: [ presigned('product-images/a.jpg'), presigned('product-images/b.png'), ], }) const putCalls = fetchMock.mock.calls.filter( ([, options]) => (options as { method?: string } | undefined)?.method === 'PUT' ) expect(putCalls).toHaveLength(2) expect(result.current.error).toBeNull() }) it('resolves an empty batch without calling the backend', async () => { const { fetchMock } = setupApiMocks() const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) let resolved: unknown await act(async () => { resolved = await result.current.upload({ images: [], contextString: 'store' }) }) expect(resolved).toEqual({ keys: [], presignedUrls: [] }) expect(procCount(fetchMock, 'common.generateUploadUrls')).toBe(0) }) it('fails when the backend returns a URL count that does not match', async () => { setupApiMocks({ procedures: { 'common.generateUploadUrls': { uploadUrls: [presigned('tags/only.jpg')] }, }, }) const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) const promise = startUpload(result, { images: [jpeg, png], contextString: 'tags', }) await waitFor(() => expect(result.current.error?.message).toBe('Expected 2 URLs, got 1') ) await expect(promise).rejects.toThrow('Expected 2 URLs, got 1') }) it('surfaces the failed PUT status and stops uploading', async () => { const { fetchMock } = setupApiMocks({ procedures: { 'common.generateUploadUrls': { uploadUrls: [presigned('store-images/x.jpg')], }, }, }) const trpcFetch = global.fetch ;(global as unknown as { fetch: unknown }).fetch = jest.fn( async (url: string, options?: { method?: string }) => { if (options?.method === 'PUT') { return { ok: false, status: 500, statusText: 'Server Error', headers: new Map(), url: String(url), text: async (): Promise => 'AccessDenied', json: async () => ({}), } } return trpcFetch(url, options) } ) const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}) const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) const promise = startUpload(result, { images: [jpeg], contextString: 'store', }) await waitFor(() => expect(result.current.error?.message).toBe('Upload 1 failed with status 500') ) await expect(promise).rejects.toThrow('Upload 1 failed with status 500') expect(result.current.isUploading).toBe(false) expect(result.current.progress).toBeNull() expectProcedureCalled(fetchMock, 'common.generateUploadUrls', { times: 1 }) consoleError.mockRestore() }) it('reports progress as each upload settles', async () => { setupApiMocks({ procedures: { 'common.generateUploadUrls': { uploadUrls: [ presigned('product-images/a.jpg'), presigned('product-images/b.jpg'), ], }, }, }) const trpcFetch = global.fetch const resolvers: Array<(value: unknown) => void> = [] ;(global as unknown as { fetch: unknown }).fetch = jest.fn( (url: string, options?: { method?: string }) => { if (options?.method === 'PUT') { return new Promise((resolve) => resolvers.push(resolve)) } return trpcFetch(url, options) } ) const okResponse = { ok: true, status: 200, statusText: 'OK', headers: new Map(), url: '', text: async () => '', json: async () => ({}), } const { result } = renderHook(() => useUploadToObjectStorage(), { wrapper }) const promise = startUpload(result, { images: [jpeg, png], contextString: 'product_info', }) await waitFor(() => expect(resolvers).toHaveLength(2)) expect(result.current.progress).toEqual({ completed: 0, total: 2 }) act(() => resolvers[0](okResponse)) await waitFor(() => expect(result.current.progress).toEqual({ completed: 1, total: 2 })) act(() => resolvers[1](okResponse)) await waitFor(() => expect(result.current.progress).toBeNull()) const uploaded = await promise expect(uploaded).toEqual({ keys: ['product-images/a.jpg', 'product-images/b.jpg'], presignedUrls: [ presigned('product-images/a.jpg'), presigned('product-images/b.jpg'), ], }) }) })