freshyo/apps/admin-ui/tests/lib/upload-hook.test.tsx
2026-10-20 00:31:05 +05:30

214 lines
6.6 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 17.2 — useUploadToObjectStorage
* (`tests/lib/upload-hook.test.tsx`).
*
* The hook is exercised through a probe component so React state
* (`isUploading`) can be observed while the upload is in flight.
*/
import React from 'react'
import { Text } from 'react-native'
import { act, render } from '@testing-library/react-native'
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
import { resetAllMocks } from '../helpers/reset'
import { lastMutationInput, procedureMutationCalls, setProcedure } from '../mocks/trpc-client'
import { flush } from '../helpers/test-utils'
import { UPLOAD_URLS_RESPONSE } from '../fixtures'
type HookApi = ReturnType<typeof useUploadToObjectStorage>
let hook: HookApi | null = null
function Probe() {
const api = useUploadToObjectStorage()
hook = api
return (
<>
<Text testID="uploading">{api.isUploading ? 'uploading' : 'idle'}</Text>
<Text testID="error">{api.error?.message ?? 'none'}</Text>
<Text testID="progress">
{api.progress ? `${api.progress.completed}/${api.progress.total}` : 'none'}
</Text>
</>
)
}
function renderProbe() {
const view = render(<Probe />)
return view
}
const blob = {} as any
const OK_RESPONSE = {
ok: true,
status: 200,
text: async () => '',
json: async () => ({}),
}
describe('useUploadToObjectStorage (AUPL-01..06)', () => {
beforeEach(() => {
resetAllMocks()
hook = null
;(global as any).fetch = jest.fn(async () => ({ ...OK_RESPONSE }))
})
afterEach(() => {
jest.restoreAllMocks()
})
it('AUPL-01: uploads a single image via the presigned PUT and returns key/url', async () => {
const view = renderProbe()
let result: any
await act(async () => {
result = await hook!.uploadSingle(blob, 'image/jpeg', 'product_info')
})
expect(lastMutationInput('common.generateUploadUrls')).toEqual({
contextString: 'product_info',
mimeTypes: ['image/jpeg'],
})
expect((global as any).fetch).toHaveBeenCalledTimes(1)
const [url, options] = ((global as any).fetch as jest.Mock).mock.calls[0]
expect(url).toBe(UPLOAD_URLS_RESPONSE.uploadUrls[0])
expect(options).toMatchObject({
method: 'PUT',
body: blob,
headers: { 'Content-Type': 'image/jpeg' },
})
expect(result).toEqual({
key: 'product-images/img-1.jpg',
presignedUrl: UPLOAD_URLS_RESPONSE.uploadUrls[0],
})
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-02: uploads every image and requests one URL per mime type', async () => {
const urls = [
'https://upload.test/meatfarmer/review-images/a.jpg',
'https://upload.test/meatfarmer/review-images/b.png',
]
setProcedure('common.generateUploadUrls', { data: { uploadUrls: urls } })
const view = renderProbe()
let result: any
await act(async () => {
result = await hook!.upload({
images: [
{ blob, mimeType: 'image/jpeg' },
{ blob, mimeType: 'image/png' },
],
contextString: 'review',
})
})
expect(lastMutationInput('common.generateUploadUrls')).toEqual({
contextString: 'review',
mimeTypes: ['image/jpeg', 'image/png'],
})
expect((global as any).fetch).toHaveBeenCalledTimes(2)
expect(((global as any).fetch as jest.Mock).mock.calls.map((call: any[]) => call[0])).toEqual(urls)
expect(result).toEqual({
keys: ['review-images/a.jpg', 'review-images/b.png'],
presignedUrls: urls,
})
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-03: an empty image list makes no URL or PUT request', async () => {
const view = renderProbe()
let result: any
await act(async () => {
result = await hook!.upload({ images: [], contextString: 'product_info' })
})
expect(result).toEqual({ keys: [], presignedUrls: [] })
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(0)
expect((global as any).fetch).not.toHaveBeenCalled()
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-04: rejects when the URL count does not match the image count', async () => {
const view = renderProbe()
let error: any
await act(async () => {
try {
await hook!.upload({
images: [
{ blob, mimeType: 'image/jpeg' },
{ blob, mimeType: 'image/jpeg' },
],
contextString: 'product_info',
})
} catch (err) {
error = err
}
})
expect(error).toBeInstanceOf(Error)
expect(error.message).toBe('Expected 2 URLs, got 1')
expect((global as any).fetch).not.toHaveBeenCalled()
await flush()
expect(view.getByTestId('error').props.children).toBe('Expected 2 URLs, got 1')
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-05: rejects when the presigned PUT fails', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined)
;(global as any).fetch = jest.fn(async () => ({
ok: false,
status: 500,
text: async () => '<Error><Code>InternalError</Code></Error>',
json: async () => ({}),
}))
const view = renderProbe()
let error: any
await act(async () => {
try {
await hook!.uploadSingle(blob, 'image/jpeg', 'product_info')
} catch (err) {
error = err
}
})
expect(error).toBeInstanceOf(Error)
expect(error.message).toBe('Upload 1 failed with status 500')
await flush()
expect(view.getByTestId('error').props.children).toBe('Upload 1 failed with status 500')
expect(view.getByTestId('uploading').props.children).toBe('idle')
})
it('AUPL-06: isUploading is true while the PUT is in flight and false afterwards', async () => {
let resolvePut: (value: any) => void = () => undefined
const pendingPut = new Promise((resolve) => {
resolvePut = resolve
})
;(global as any).fetch = jest.fn(() => pendingPut)
const view = renderProbe()
expect(view.getByTestId('uploading').props.children).toBe('idle')
let uploadPromise: Promise<any> = Promise.resolve()
act(() => {
uploadPromise = hook!.uploadSingle(blob, 'image/jpeg', 'product_info')
})
await flush()
expect(view.getByTestId('uploading').props.children).toBe('uploading')
expect(view.getByTestId('progress').props.children).toBe('0/1')
await act(async () => {
resolvePut({ ...OK_RESPONSE })
await uploadPromise
})
expect(view.getByTestId('uploading').props.children).toBe('idle')
expect(view.getByTestId('progress').props.children).toBe('none')
})
})