freshyo/apps/admin-ui/tests/components/slot-form.test.tsx
2026-10-20 11:19:25 +05:30

314 lines
11 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 7.3 — SlotForm and VendorSnippetForm
* (`tests/components/slot-form.test.tsx`).
*/
import React from 'react'
import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native'
import SlotForm from '@/components/SlotForm'
import VendorSnippetForm from '@/components/VendorSnippetForm'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
const HOUR = 60 * 60 * 1000
type View = ReturnType<typeof renderWithProviders>
function renderSlotForm(props: Partial<React.ComponentProps<typeof SlotForm>> = {}) {
return renderWithProviders(<SlotForm {...props} />, { auth: 'in' })
}
function chooseDate(view: View, field: 'delivery' | 'freeze', date: Date) {
fireEvent.press(view.getByTestId(`${field}-date-picker`))
fireEvent(view.getByTestId('dateTimePicker'), 'change', { type: 'set' }, date)
}
function setDates(view: View, deliveryOffset = 3, freezeOffset = 2) {
const delivery = new Date(Date.now() + deliveryOffset * HOUR)
const freeze = new Date(Date.now() + freezeOffset * HOUR)
chooseDate(view, 'delivery', delivery)
chooseDate(view, 'freeze', freeze)
return { delivery, freeze }
}
function selectSku(view: View, testId: string, skuId: number) {
fireEvent.press(view.getByTestId(testId))
fireEvent.press(view.getByTestId(`${testId}-option-${skuId}`))
fireEvent.press(view.getByTestId(`${testId}-done`))
}
describe('SlotForm (ASLOTF-01..10)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => alertSpy?.mockRestore())
it('ASLOTF-01: renders the create fields', () => {
const view = renderSlotForm()
expect(view.getByText('Create New Slot')).toBeTruthy()
expect(view.getByText('Delivery Date & Time')).toBeTruthy()
expect(view.getByText('Freeze Date & Time')).toBeTruthy()
expect(view.getByText('Vendor Snippets')).toBeTruthy()
expect(view.getByText('Create Slot')).toBeTruthy()
})
it('ASLOTF-02: missing delivery/freeze times are rejected', async () => {
const view = renderSlotForm()
fireEvent.press(view.getByTestId('create-slot-button'))
await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Please fill all fields')
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(0)
})
it('ASLOTF-03: freeze after delivery is rejected', async () => {
const view = renderSlotForm()
// Freeze is later than delivery.
setDates(view, 1, 4)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush()
expect(alertSpy).toHaveBeenCalledWith(
'Error',
'Freeze time must be before or equal to delivery time'
)
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(0)
})
it('ASLOTF-04: selecting products sends the SKU ids', async () => {
const view = renderSlotForm()
await flush()
selectSku(view, 'slot-products-selector', 13)
const { delivery, freeze } = setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
expect(lastMutationInput('admin.slots.createSlot')).toEqual(
expect.objectContaining({
deliveryTime: delivery.toISOString(),
freezeTime: freeze.toISOString(),
skuIds: [13],
})
)
})
it('ASLOTF-05: adding a vendor snippet includes name, SKUs and no expiry', async () => {
const view = renderSlotForm()
await flush()
selectSku(view, 'slot-products-selector', 13)
fireEvent.press(view.getByText('Add Vendor Snippet'))
fireEvent.changeText(view.getByPlaceholderText('Enter snippet name'), 'Snippet A')
selectSku(view, 'snippet-products-selector', 13)
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
const input = lastMutationInput('admin.slots.createSlot')
expect(input.vendorSnippets).toEqual([
{ name: 'Snippet A', skuIds: [13], validTill: '' },
])
})
it('ASLOTF-06: removing a vendor snippet drops it from the list', () => {
const view = renderSlotForm()
fireEvent.press(view.getByText('Add Vendor Snippet'))
expect(view.getByText('Snippet Name *')).toBeTruthy()
fireEvent.press(view.getByText('Remove Snippet'))
expect(view.queryByText('Snippet Name *')).toBeNull()
})
it('ASLOTF-07: a snippet without SKUs is submitted as-is (no validation)', async () => {
const view = renderSlotForm()
fireEvent.press(view.getByText('Add Vendor Snippet'))
fireEvent.changeText(view.getByPlaceholderText('Enter snippet name'), 'Empty Snippet')
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
const input = lastMutationInput('admin.slots.createSlot')
expect(input.vendorSnippets).toEqual([
{ name: 'Empty Snippet', skuIds: [], validTill: '' },
])
})
it('ASLOTF-08: group selection is sent as group ids', async () => {
const view = renderSlotForm()
await flush()
fireEvent.press(view.getByTestId('product-groups-dropdown'))
fireEvent.press(view.getByTestId('product-groups-dropdown-option-1'))
fireEvent.press(view.getByTestId('product-groups-dropdown-done'))
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
expect(lastMutationInput('admin.slots.createSlot')).toEqual(
expect.objectContaining({ groupIds: [1] })
)
})
it('ASLOTF-09: create and edit titles/buttons', () => {
const create = renderSlotForm()
expect(create.getByText('Create New Slot')).toBeTruthy()
expect(create.getByText('Create Slot')).toBeTruthy()
create.unmount()
const edit = renderSlotForm({ slotId: 1849 })
expect(edit.getByText('Edit Slot')).toBeTruthy()
expect(edit.getByText('Update Slot')).toBeTruthy()
})
it('ASLOTF-10: a pending submit shows "Creating..." and ignores further presses', async () => {
setProcedure('admin.slots.createSlot', { mode: 'pending' })
const view = renderSlotForm()
setDates(view)
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
expect(view.getByText('Creating...')).toBeTruthy()
fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(1)
})
})
describe('VendorSnippetForm (AVSF-01..08)', () => {
let alertSpy: jest.SpyInstance
let onClose: jest.Mock
let onSuccess: jest.Mock
beforeEach(() => {
resetAllMocks()
onClose = jest.fn()
onSuccess = jest.fn()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => alertSpy?.mockRestore())
function renderSnippetForm(snippet?: any) {
return renderWithProviders(
<VendorSnippetForm snippet={snippet} onClose={onClose} onSuccess={onSuccess} />,
{ auth: 'in' }
)
}
it('AVSF-01: renders code, slot, products, expiry and permanent fields', () => {
const view = renderSnippetForm()
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
expect(view.getByTestId('snippet-code-input').props.value).toMatch(/^VS_/)
expect(view.getByText('Is Permanent?')).toBeTruthy()
expect(view.getByText('Delivery Slot')).toBeTruthy()
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
expect(view.getByTestId('snippet-form-products-selector')).toBeTruthy()
expect(view.getByText('Create Snippet')).toBeTruthy()
})
it('AVSF-02: an empty code is rejected', async () => {
const view = renderSnippetForm()
fireEvent.changeText(view.getByTestId('snippet-code-input'), '')
fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush(2)
expect(view.getByText('Snippet code is required')).toBeTruthy()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
it('AVSF-03: submitting without products is rejected', async () => {
const view = renderSnippetForm()
fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1')
fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush(2)
expect(view.getByText('At least one product must be selected')).toBeTruthy()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
it('AVSF-04: permanent hides the slot selector', () => {
const view = renderSnippetForm()
expect(view.getByText('Delivery Slot')).toBeTruthy()
fireEvent.press(view.getByText('Is Permanent?'))
expect(view.queryByText('Delivery Slot')).toBeNull()
// Current behaviour: the expiry field stays visible for permanent snippets.
expect(view.getByText('Valid Till (Optional)')).toBeTruthy()
})
it('AVSF-05: editing prefills the saved values', () => {
const validTill = new Date(Date.now() + 24 * HOUR)
const view = renderSnippetForm({
id: 1,
snippetCode: 'ABC123',
slotId: 1849,
isPermanent: false,
skuIds: [11],
validTill,
})
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
expect(view.getByTestId('snippet-code-input').props.value).toBe('ABC123')
expect(view.getByText('Update Snippet')).toBeTruthy()
expect(view.getAllByText(validTill.toLocaleDateString()).length).toBeGreaterThanOrEqual(1)
})
it('AVSF-06: the product selector updates the selection', async () => {
const view = renderSnippetForm()
await flush()
selectSku(view, 'snippet-form-products-selector', 11)
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
})
it('AVSF-07: submit sends the complete snippet payload', async () => {
const view = renderSnippetForm()
await flush()
fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1')
fireEvent.press(view.getByText('Is Permanent?'))
selectSku(view, 'snippet-form-products-selector', 11)
fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush(2)
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
snippetCode: 'TEST_1',
slotId: undefined,
isPermanent: true,
skuIds: [11],
validTill: undefined,
})
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
expect(onSuccess).toHaveBeenCalled()
expect(onClose).toHaveBeenCalled()
})
it('AVSF-08: cancel calls onClose', () => {
const view = renderSnippetForm()
fireEvent.press(view.getByText('✕'))
expect(onClose).toHaveBeenCalled()
expect(procedureMutationCalls('admin.vendorSnippets.create')).toHaveLength(0)
})
})