235 lines
7.1 KiB
TypeScript
235 lines
7.1 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.
|
|
*
|
|
* The real tRPC client + React Query run, so the probe needs the same providers
|
|
* as a page. Presigned PUTs go to a non-tRPC URL and are answered by
|
|
* `setRawFetchHandler` (never by replacing `global.fetch`, which would take the
|
|
* harness' tRPC network mock with it).
|
|
*/
|
|
import React from 'react'
|
|
import { Text } from 'react-native'
|
|
import { act } from '@testing-library/react-native'
|
|
|
|
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
|
|
import { resetAllMocks } from '../helpers/reset'
|
|
import {
|
|
lastMutationInput,
|
|
procedureMutationCalls,
|
|
setProcedure,
|
|
setRawFetchHandler,
|
|
} from '../mocks/trpc-client'
|
|
import { renderWithProviders, 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() {
|
|
return renderWithProviders(<Probe />, { auth: false })
|
|
}
|
|
|
|
const blob = {} as any
|
|
const OK_RESPONSE = {
|
|
ok: true,
|
|
status: 200,
|
|
text: async () => '',
|
|
json: async () => ({}),
|
|
}
|
|
const ERROR_RESPONSE = {
|
|
ok: false,
|
|
status: 500,
|
|
text: async () => '<Error><Code>InternalError</Code></Error>',
|
|
json: async () => ({}),
|
|
}
|
|
|
|
/** Records the presigned PUTs the hook makes (non-tRPC requests). */
|
|
function stubPut(response: any = OK_RESPONSE) {
|
|
const put = jest.fn(async (_url: string, _init?: any) => ({ ...response }))
|
|
setRawFetchHandler(put as any)
|
|
return put
|
|
}
|
|
|
|
describe('useUploadToObjectStorage (AUPL-01..06)', () => {
|
|
beforeEach(() => {
|
|
resetAllMocks()
|
|
hook = null
|
|
})
|
|
|
|
afterEach(() => {
|
|
jest.restoreAllMocks()
|
|
})
|
|
|
|
it('AUPL-01: uploads a single image via the presigned PUT and returns key/url', async () => {
|
|
const put = stubPut()
|
|
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(put).toHaveBeenCalledTimes(1)
|
|
const [url, options] = put.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 put = stubPut()
|
|
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(put).toHaveBeenCalledTimes(2)
|
|
expect(put.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 put = stubPut()
|
|
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(put).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 put = stubPut()
|
|
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(put).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)
|
|
const put = stubPut(ERROR_RESPONSE)
|
|
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')
|
|
expect(put).toHaveBeenCalledTimes(1)
|
|
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
|
|
})
|
|
setRawFetchHandler((() => pendingPut) as any)
|
|
|
|
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')
|
|
})
|
|
})
|