freshyo/apps/admin-ui/tests/pages/product-add.test.tsx
2026-10-20 11:19:25 +05:30

355 lines
13 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 4.3 — Add product (`app/(drawer)/dashboard/products/add.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker'
import AddProduct from '@/app/(drawer)/dashboard/products/add'
import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
procedureMutationCalls,
setProcedure,
setRawFetchHandler,
} from '../mocks/trpc-client'
import { STORE_GLOBAL } from '../fixtures'
async function renderAdd() {
const view = await renderAndFlush(<AddProduct />, { auth: false })
await flush(2)
return view
}
function fillVariant(
view: Awaited<ReturnType<typeof renderAdd>>,
index: number,
{ price, quantity }: { price: string; quantity: string }
) {
fireEvent.changeText(view.getByTestId(`variant-${index}-price`), price)
fireEvent.changeText(view.getByTestId(`variant-${index}-attr-0-value`), quantity)
}
async function submit(view: Awaited<ReturnType<typeof renderAdd>>) {
fireEvent.press(view.getByTestId('create-product-button'))
await flush(3)
}
/** Wait for the create mutation to land, then return its input. */
async function createdPayload() {
await waitFor(() =>
expect(lastMutationInput('admin.product.createProduct')).toBeDefined()
)
return lastMutationInput('admin.product.createProduct')
}
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('Add product (APADD-01..19)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
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('APADD-01: renders the create form with an empty name and one quantity variant', async () => {
const view = await renderAdd()
expect(view.getByTestId('product-name-input').props.value).toBe('')
expect(view.getByText('Variant 1')).toBeTruthy()
expect(view.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
expect(view.getByText('Create Product')).toBeTruthy()
})
it('APADD-02: a zero/missing price is rejected before the request', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '0', quantity: '1kg' })
await submit(view)
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Price must be a positive number'))
expect(lastMutationInput('admin.product.createProduct')).toBeUndefined()
})
it('APADD-03: duplicate variant signatures are rejected', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.press(view.getByTestId('add-variant-button'))
fillVariant(view, 1, { price: '120', quantity: '1kg' })
await submit(view)
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Two variants have the same attributes'))
expect(lastMutationInput('admin.product.createProduct')).toBeUndefined()
})
it('APADD-04: every SKU is guaranteed a quantity feature', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
// The form prepends and locks the quantity feature, so a SKU without one
// cannot be assembled through the UI; the quantity input is always present.
expect(view.getByTestId('variant-0-attr-0-name').props.value).toBe('quantity')
expect(view.getByTestId('variant-0-attr-0-name').props.editable).toBe(false)
await submit(view)
expect((await createdPayload()).skus[0].features).toEqual([
{ featureName: 'quantity', featureValue: '1kg' },
])
})
it('APADD-05: submits a product without images', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view)
const payload = await createdPayload()
expect(payload).toEqual(
expect.objectContaining({
name: 'Chicken',
storeId: 1,
productType: 'item',
incrementStep: 1,
})
)
expect(payload.skus[0].images).toEqual([])
expect(payload.skus[0].price).toBe(100)
})
it('APADD-06: uploads images and stores bucket-relative keys', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.press(view.getByTestId('variant-0-image-add'))
await flush()
await submit(view)
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(1)
const payload = await createdPayload()
expect(payload.skus[0].images).toEqual(['product-images/img-1.jpg'])
})
it('APADD-07: upload keys are mapped to the correct variants', async () => {
setProcedure('common.generateUploadUrls', {
data: {
uploadUrls: [
'https://upload.test/meatfarmer/product-images/a.jpg',
'https://upload.test/meatfarmer/product-images/b.jpg',
],
},
})
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '500g' })
fireEvent.press(view.getByTestId('add-variant-button'))
fillVariant(view, 1, { price: '200', quantity: '1kg' })
fireEvent.press(view.getByTestId('variant-0-image-add'))
await flush()
fireEvent.press(view.getByTestId('variant-1-image-add'))
await flush()
await submit(view)
const payload = await createdPayload()
expect(payload.skus[0].images).toEqual(['product-images/a.jpg'])
expect(payload.skus[1].images).toEqual(['product-images/b.jpg'])
})
it('APADD-08: feature names are trimmed and quantity is normalized', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.press(view.getByTestId('variant-0-add-attr-footer'))
fireEvent.changeText(view.getByTestId('variant-0-attr-1-name'), ' Size ')
fireEvent.changeText(view.getByTestId('variant-0-attr-1-value'), 'Large')
await submit(view)
const payload = await createdPayload()
expect(payload.skus[0].features).toEqual([
{ featureName: 'quantity', featureValue: '1kg' },
{ featureName: 'Size', featureValue: 'Large' },
])
})
it('APADD-09: market/flash price strings become numbers', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.changeText(view.getByTestId('variant-0-market-price'), '250')
fireEvent.press(view.getByTestId('variant-0-flash'))
fireEvent.changeText(view.getByTestId('variant-0-flash-price'), '199')
await submit(view)
const sku = (await createdPayload()).skus[0]
expect(sku.marketPrice).toBe(250)
expect(sku.flashPrice).toBe(199)
expect(sku.isFlashAvailable).toBe(true)
})
it('APADD-10: create pending shows "Creating..."', async () => {
setProcedure('admin.product.createProduct', { mode: 'pending' })
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.press(view.getByTestId('create-product-button'))
await flush(2)
expect(view.getByText('Creating...')).toBeTruthy()
})
it('APADD-11: success alerts and refreshes the product list', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view)
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Product created successfully!'))
// The list query is mounted disabled purely as a refetch handle.
expect(procedureMutationCalls('admin.product.createProduct')).toHaveLength(1)
})
it('APADD-12: API failure alerts the error message', async () => {
setProcedure('admin.product.createProduct', { mode: 'error', error: new Error('bad request') })
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view)
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'bad request'))
})
it('APADD-13: upload failure alerts and never creates the product', async () => {
setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('storage down') })
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.press(view.getByTestId('variant-0-image-add'))
await flush()
await submit(view)
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'storage down'))
expect(lastMutationInput('admin.product.createProduct')).toBeUndefined()
})
it('APADD-14: a create form with no store defaults to the regional store', async () => {
const view = await renderAdd()
expect(view.getAllByText('The Freshyo Meat House').length).toBeGreaterThanOrEqual(1)
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view)
expect((await createdPayload()).storeId).toBe(1)
})
it('APADD-15: combo products send their combo items', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Combo Box')
fillVariant(view, 0, { price: '100', quantity: '1 box' })
fireEvent.press(view.getByTestId('product-type-dropdown'))
fireEvent.press(view.getByTestId('product-type-dropdown-option-combo'))
fireEvent.press(view.getByTestId('variant-0-combo-add'))
fireEvent.press(view.getByTestId('variant-0-combo-0-dropdown'))
fireEvent.press(view.getByTestId('variant-0-combo-0-dropdown-option-11'))
await submit(view)
const payload = await createdPayload()
expect(payload.productType).toBe('combo')
expect(payload.skus[0].comboItems).toEqual([{ skuId: 11 }])
})
it('APADD-16: a global-only store list is allowed and labeled global', async () => {
setProcedure('common.getStoresSummary', { data: { stores: [STORE_GLOBAL] } })
const view = await renderAdd()
expect(view.getByText('Freshyo Central (global)')).toBeTruthy()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view)
expect((await createdPayload()).storeId).toBe(2)
})
it('APADD-17: an empty image list does not call the uploader', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view)
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(0)
})
it('APADD-18: two variants with the same feature and different values are allowed', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '500g' })
fireEvent.press(view.getByTestId('add-variant-button'))
fillVariant(view, 1, { price: '200', quantity: '1kg' })
await submit(view)
expect(alertSpy).not.toHaveBeenCalledWith(
'Check your form',
'Two variants have the same attributes'
)
const payload = await createdPayload()
expect(payload.skus).toHaveLength(2)
expect(payload.skus[0].features[0].featureValue).toBe('500g')
expect(payload.skus[1].features[0].featureValue).toBe('1kg')
})
it('APADD-19: duplicate signatures are detected regardless of feature order', async () => {
const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.press(view.getByTestId('add-variant-button'))
fillVariant(view, 1, { price: '120', quantity: '1kg' })
await submit(view)
// variantSignature sorts features, so equivalent attribute sets collide.
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Two variants have the same attributes'))
})
})