388 lines
13 KiB
TypeScript
388 lines
13 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
/**
|
|
* Catalogue section 4.4 — Edit product (`app/(drawer)/dashboard/products/edit.tsx`).
|
|
*/
|
|
import React from 'react'
|
|
import { Alert, DeviceEventEmitter } from 'react-native'
|
|
import { act, fireEvent, waitFor } from '@testing-library/react-native'
|
|
import * as ImagePicker from 'expo-image-picker'
|
|
|
|
import EditProduct from '@/app/(drawer)/dashboard/products/edit'
|
|
import { renderAndFlush, flush } from '../helpers/test-utils'
|
|
import { resetAllMocks } from '../helpers/reset'
|
|
import {
|
|
lastMutationInput,
|
|
procedureMutationCalls,
|
|
procedureQueryCalls,
|
|
setProcedure,
|
|
setRawFetchHandler,
|
|
} from '../mocks/trpc-client'
|
|
import { __setParams } from '../mocks/expo-router-mock'
|
|
import { P_CHICKEN, P_GLOBAL } from '../fixtures'
|
|
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
|
|
|
|
const regularProduct = (over: Record<string, any> = {}) => ({
|
|
...P_CHICKEN,
|
|
deals: [],
|
|
tags: [],
|
|
...over,
|
|
})
|
|
|
|
const globalProduct = (over: Record<string, any> = {}) => ({
|
|
...P_GLOBAL,
|
|
deals: [],
|
|
tags: [],
|
|
...over,
|
|
})
|
|
|
|
async function renderEdit() {
|
|
const view = await renderAndFlush(<EditProduct />, { auth: false })
|
|
await flush(2)
|
|
return view
|
|
}
|
|
|
|
async function submit(view: Awaited<ReturnType<typeof renderEdit>>) {
|
|
fireEvent.press(view.getByTestId('create-product-button'))
|
|
await flush(3)
|
|
}
|
|
|
|
async function submitGlobal(view: Awaited<ReturnType<typeof renderEdit>>) {
|
|
fireEvent.press(view.getByTestId('global-save-button'))
|
|
await flush(3)
|
|
}
|
|
|
|
/** Wait for the update mutation to land, then return its input. */
|
|
async function updatedPayload() {
|
|
await waitFor(() =>
|
|
expect(lastMutationInput('admin.product.updateProduct')).toBeDefined()
|
|
)
|
|
return lastMutationInput('admin.product.updateProduct')
|
|
}
|
|
|
|
function mockSuccessfulUploads() {
|
|
setRawFetchHandler(async (_url, init) => {
|
|
if (init?.method === 'PUT') {
|
|
return { ok: true, status: 200, text: async () => '' } as any
|
|
}
|
|
return { ok: true, status: 200, blob: async () => ({ size: 1 }) } as any
|
|
})
|
|
}
|
|
|
|
describe('Edit product (APEDIT-01..20)', () => {
|
|
let alertSpy: jest.SpyInstance
|
|
|
|
beforeEach(() => {
|
|
resetAllMocks()
|
|
__setParams({ id: '2' })
|
|
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
|
mockSuccessfulUploads()
|
|
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({
|
|
canceled: false,
|
|
assets: [{ uri: 'file:///picked.jpg', mimeType: 'image/jpeg', fileName: 'picked.jpg' }],
|
|
})
|
|
})
|
|
|
|
afterEach(() => alertSpy?.mockRestore())
|
|
|
|
it('APEDIT-01: a missing/invalid id disables the query and shows not found', async () => {
|
|
__setParams({})
|
|
const view = await renderEdit()
|
|
|
|
expect(view.getByText('Product not found')).toBeTruthy()
|
|
expect(procedureQueryCalls('admin.product.getProductById')).toHaveLength(0)
|
|
|
|
view.unmount()
|
|
__setParams({ id: 'abc' })
|
|
const second = await renderEdit()
|
|
expect(second.getByText('Product not found')).toBeTruthy()
|
|
expect(procedureQueryCalls('admin.product.getProductById')).toHaveLength(0)
|
|
})
|
|
|
|
it('APEDIT-02: shows the loading copy while the product is fetching', async () => {
|
|
setProcedure('admin.product.getProductById', { mode: 'pending' })
|
|
const view = await renderEdit()
|
|
|
|
expect(view.getByText('Loading product...')).toBeTruthy()
|
|
})
|
|
|
|
it('APEDIT-03: a regular product prefills the ProductForm', async () => {
|
|
const view = await renderEdit()
|
|
|
|
expect(view.getByTestId('product-name-input').props.value).toBe('Chicken Breast')
|
|
expect(view.getByTestId('variant-0-price').props.value).toBe('215')
|
|
expect(view.getByText('Variant 1')).toBeTruthy()
|
|
})
|
|
|
|
it('APEDIT-04: a global product renders GlobalProductForm with read-only structure', async () => {
|
|
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
|
|
const view = await renderEdit()
|
|
|
|
expect(view.getByText('Global product')).toBeTruthy()
|
|
expect(view.queryByTestId('product-name-input')).toBeNull()
|
|
expect(view.getAllByText('Global Paneer').length).toBeGreaterThanOrEqual(1)
|
|
})
|
|
|
|
it('APEDIT-05: the global suspend toggle starts from the regional flag', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: {
|
|
product: globalProduct({
|
|
skus: [{ ...P_GLOBAL.skus[0], isSuspended: false, isSuspendedInRegion: true }],
|
|
}),
|
|
},
|
|
})
|
|
const view = await renderEdit()
|
|
|
|
expect(view.getByTestId('global-sku-91-suspend').props.accessibilityState.checked).toBe(true)
|
|
})
|
|
|
|
it('APEDIT-06: saving a regular product keeps existing images', async () => {
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken Updated')
|
|
await submit(view)
|
|
|
|
const payload = await updatedPayload()
|
|
expect(payload).toEqual(
|
|
expect.objectContaining({
|
|
id: 2,
|
|
name: 'Chicken Updated',
|
|
storeId: 1,
|
|
productType: 'item',
|
|
incrementStep: 1,
|
|
deletedImageKeys: [],
|
|
newImageUrls: [],
|
|
})
|
|
)
|
|
expect(payload.skus).toHaveLength(2)
|
|
expect(payload.skus[0].images).toEqual(['chicken.jpg'])
|
|
})
|
|
|
|
it('APEDIT-07: removing an existing image records its key as deleted', async () => {
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.press(view.getByTestId('variant-0-image-add-remove'))
|
|
await submit(view)
|
|
|
|
const payload = await updatedPayload()
|
|
expect(payload.deletedImageKeys).toEqual(['product-images/chicken.jpg'])
|
|
expect(payload.skus[0].images).toEqual([])
|
|
})
|
|
|
|
it('APEDIT-08: new images are uploaded and appended as keys', async () => {
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.press(view.getByTestId('variant-0-image-add'))
|
|
await flush()
|
|
await submit(view)
|
|
|
|
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(1)
|
|
const payload = await updatedPayload()
|
|
expect(payload.newImageUrls).toEqual(['https://upload.test/meatfarmer/product-images/img-1.jpg'])
|
|
expect(payload.skus[0].images).toEqual(['chicken.jpg', 'product-images/img-1.jpg'])
|
|
})
|
|
|
|
it('APEDIT-09: submitting without changes still sends the product', async () => {
|
|
const view = await renderEdit()
|
|
|
|
await submit(view)
|
|
|
|
const payload = await updatedPayload()
|
|
expect(payload.id).toBe(2)
|
|
expect(payload.name).toBe('Chicken Breast')
|
|
})
|
|
|
|
it('APEDIT-10: a failed update alerts and stays on the page', async () => {
|
|
setProcedure('admin.product.updateProduct', { mode: 'error', error: new Error('nope') })
|
|
const view = await renderEdit()
|
|
|
|
await submit(view)
|
|
|
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
|
|
expect(view.getByTestId('product-name-input').props.value).toBe('Chicken Breast')
|
|
})
|
|
|
|
it('APEDIT-11: update pending shows "Saving..."', async () => {
|
|
setProcedure('admin.product.updateProduct', { mode: 'pending' })
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.press(view.getByTestId('create-product-button'))
|
|
await flush(2)
|
|
|
|
expect(view.getByText('Saving...')).toBeTruthy()
|
|
})
|
|
|
|
it('APEDIT-12: success alerts, refetches and clears uploaded images', async () => {
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.press(view.getByTestId('variant-0-image-add'))
|
|
await flush()
|
|
|
|
await submit(view)
|
|
|
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Product updated successfully!'))
|
|
expect(view.queryByTestId('variant-0-image-add-remove')).toBeNull()
|
|
})
|
|
|
|
it('APEDIT-13: saving a global product sends market fields', async () => {
|
|
__setParams({ id: '9' })
|
|
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.changeText(view.getByTestId('global-sku-91-price'), '95')
|
|
await submitGlobal(view)
|
|
|
|
const payload = await updatedPayload()
|
|
expect(payload).toEqual(
|
|
expect.objectContaining({
|
|
id: 9,
|
|
name: 'Global Paneer',
|
|
storeId: 2,
|
|
productType: 'item',
|
|
incrementStep: 1,
|
|
deletedImageKeys: [],
|
|
newImageUrls: [],
|
|
})
|
|
)
|
|
expect(payload.skus[0].price).toBe(95)
|
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Market data updated for your region'))
|
|
})
|
|
|
|
it('APEDIT-14: a global product with storeId 0 sends storeId 0', async () => {
|
|
setProcedure('admin.product.getProductById', { data: { product: globalProduct({ storeId: 0 }) } })
|
|
const view = await renderEdit()
|
|
|
|
await submitGlobal(view)
|
|
|
|
expect((await updatedPayload()).storeId).toBe(0)
|
|
})
|
|
|
|
it('APEDIT-15: an empty global price is sent as 0', async () => {
|
|
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.changeText(view.getByTestId('global-sku-91-price'), '')
|
|
await submitGlobal(view)
|
|
|
|
expect((await updatedPayload()).skus[0].price).toBe(0)
|
|
})
|
|
|
|
it('APEDIT-16: turning flash off sends a null flash price', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: {
|
|
product: globalProduct({
|
|
skus: [{ ...P_GLOBAL.skus[0], isFlashAvailable: true, flashPrice: '80' }],
|
|
}),
|
|
},
|
|
})
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.press(view.getByTestId('global-sku-91-flash'))
|
|
await submitGlobal(view)
|
|
|
|
const sku = (await updatedPayload()).skus[0]
|
|
expect(sku.isFlashAvailable).toBe(false)
|
|
expect(sku.flashPrice).toBeNull()
|
|
})
|
|
|
|
it('APEDIT-17: suspending a global SKU sends the regional flag', async () => {
|
|
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
|
|
const view = await renderEdit()
|
|
|
|
fireEvent.press(view.getByTestId('global-sku-91-suspend'))
|
|
await submitGlobal(view)
|
|
|
|
const sku = (await updatedPayload()).skus[0]
|
|
expect(sku.isSuspendedInRegion).toBe(true)
|
|
expect(sku.isSuspended).toBe(false)
|
|
})
|
|
|
|
it('APEDIT-18: a failed global save alerts', async () => {
|
|
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
|
|
setProcedure('admin.product.updateProduct', { mode: 'error', error: new Error('no market') })
|
|
const view = await renderEdit()
|
|
|
|
await submitGlobal(view)
|
|
|
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'no market'))
|
|
})
|
|
|
|
it('APEDIT-19: the manual refresh event refetches the product', async () => {
|
|
const addListener = jest.spyOn(DeviceEventEmitter, 'addListener')
|
|
const view = await renderEdit()
|
|
|
|
const refreshListener = addListener.mock.calls.find(([event]) => event === REFRESH_EVENT)?.[1] as
|
|
| ((...args: any[]) => any)
|
|
| undefined
|
|
expect(typeof refreshListener).toBe('function')
|
|
|
|
await act(async () => {
|
|
await refreshListener?.()
|
|
})
|
|
|
|
expect(view.getByTestId('product-name-input')).toBeTruthy()
|
|
addListener.mockRestore()
|
|
})
|
|
|
|
it('APEDIT-20: existing image URLs are converted to bucket-relative keys', async () => {
|
|
const fullUrl =
|
|
'https://acct.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1.jpg?X-Amz-Signature=abc'
|
|
setProcedure('admin.product.getProductById', {
|
|
data: {
|
|
product: regularProduct({
|
|
skus: [
|
|
{
|
|
...P_CHICKEN.skus[0],
|
|
images: [fullUrl],
|
|
imageKeys: ['product-images/1.jpg'],
|
|
},
|
|
P_CHICKEN.skus[1],
|
|
],
|
|
}),
|
|
},
|
|
})
|
|
const view = await renderEdit()
|
|
|
|
await submit(view)
|
|
|
|
const payload = await updatedPayload()
|
|
expect(payload.skus[0].images).toEqual(['product-images/1.jpg'])
|
|
})
|
|
|
|
it('APEDIT-21: the regional suspend toggle sends the region flag', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: {
|
|
product: regularProduct({
|
|
skus: [{ ...P_CHICKEN.skus[0], isSuspended: false, isSuspendedInRegion: true }],
|
|
}),
|
|
},
|
|
})
|
|
const view = await renderEdit()
|
|
|
|
expect(view.getByTestId('variant-0-suspend').props.accessibilityState.checked).toBe(true)
|
|
|
|
fireEvent.press(view.getByTestId('variant-0-suspend'))
|
|
await submit(view)
|
|
|
|
const sku = (await updatedPayload()).skus[0]
|
|
// The regional form writes the region's flag and never the global switch.
|
|
expect(sku.isSuspendedInRegion).toBe(false)
|
|
expect(sku.isSuspended).toBeUndefined()
|
|
})
|
|
|
|
it('APEDIT-22: a legacy structural suspension shows as the regional toggle', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: {
|
|
product: regularProduct({
|
|
skus: [{ ...P_CHICKEN.skus[0], isSuspended: true, isSuspendedInRegion: false }],
|
|
}),
|
|
},
|
|
})
|
|
const view = await renderEdit()
|
|
|
|
expect(view.getByTestId('variant-0-suspend').props.accessibilityState.checked).toBe(true)
|
|
|
|
await submit(view)
|
|
|
|
expect((await updatedPayload()).skus[0].isSuspendedInRegion).toBe(true)
|
|
})
|
|
})
|