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

384 lines
13 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 15 — Vendor snippets page
* (`tests/pages/vendor-snippets.test.tsx`).
*/
import React from 'react'
import { Alert, DeviceEventEmitter, Share } from 'react-native'
import { fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs'
jest.mock('@/components/context/staff-auth-context', () =>
require('../mocks/staff-auth-context')
)
import VendorSnippets from '@/app/(drawer)/dashboard/vendor-snippets/index'
import { __setStaffState } from '../mocks/staff-auth-context'
import { renderAndFlush, renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
lastProcedureInput,
procedureMutationCalls,
setProcedure,
} from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock'
import {
SLOT_1,
SNIPPET_1,
SNIPPET_ORDERS,
SNIPPETS,
STAFF,
} from '../fixtures'
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
async function renderPage() {
const view = await renderAndFlush(<VendorSnippets />, { auth: false })
await flush(2)
return view
}
type View = Awaited<ReturnType<typeof renderPage>>
function pressIcon(view: View, name: string, index = 0) {
fireEvent.press(view.UNSAFE_getAllByProps({ name })[index])
}
function openMenu(view: View) {
pressIcon(view, 'dots-three-vertical')
}
function confirmDelete(alertSpy: jest.SpyInstance) {
const buttons = alertSpy.mock.calls[0][2] as any[]
buttons.find((button: any) => button.text === 'Delete')?.onPress?.()
}
describe('Vendor snippets page (AVENDUI-01..20)', () => {
beforeEach(() => {
resetAllMocks()
__setStaffState({ isLoggedIn: true, isLoading: false, staff: STAFF })
// The backend returns a bare array; the harness default is `{ snippets, count }`.
setProcedure('admin.vendorSnippets.getAll', { data: SNIPPETS })
})
afterEach(() => {
jest.restoreAllMocks()
})
it('AVENDUI-01: shows the loading copy', () => {
setProcedure('admin.vendorSnippets.getAll', { mode: 'pending' })
const view = renderWithProviders(<VendorSnippets />, { auth: false })
expect(view.getByText('Loading vendor snippets...')).toBeTruthy()
})
it('AVENDUI-02: a failed query shows the error copy', async () => {
setProcedure('admin.vendorSnippets.getAll', { mode: 'error', error: new Error('boom') })
const view = await renderPage()
expect(view.getByText('Error loading snippets')).toBeTruthy()
})
it('AVENDUI-03: an empty result shows the empty state and the add action', async () => {
setProcedure('admin.vendorSnippets.getAll', { data: [] })
const view = await renderPage()
expect(view.getByText('No Snippets Yet')).toBeTruthy()
expect(
view.getByText(
'Start by creating your first vendor identifier using the button below.'
)
).toBeTruthy()
pressIcon(view, 'add')
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
})
it('AVENDUI-04: a snippet card shows code, slot, validity, products and share', async () => {
const view = await renderPage()
expect(view.getByText('Identifier')).toBeTruthy()
expect(view.getByText('ABC123')).toBeTruthy()
expect(view.getByText('Active')).toBeTruthy()
expect(view.getByText(dayjs(SLOT_1.deliveryTime).format('ddd, MMM DD'))).toBeTruthy()
expect(
view.getByText(`Time: ${dayjs(SLOT_1.deliveryTime).format('hh:mm A')}`)
).toBeTruthy()
expect(view.getByText('Expires')).toBeTruthy()
expect(view.getByText(dayjs(SNIPPET_1.validTill).format('MMM DD'))).toBeTruthy()
expect(view.getByText('1 Items')).toBeTruthy()
expect(view.getByText('Share')).toBeTruthy()
expect(view.getByText('View Slot')).toBeTruthy()
})
it('AVENDUI-05: an expired snippet is badged as expired', async () => {
const expired = {
...SNIPPET_1,
validTill: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
}
setProcedure('admin.vendorSnippets.getAll', {
data: [expired],
})
const view = await renderPage()
expect(view.getByText('Expired')).toBeTruthy()
expect(view.queryByText('Active')).toBeNull()
})
it('AVENDUI-06: sharing a snippet without an access URL alerts', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'dismissedAction' } as any)
setProcedure('admin.vendorSnippets.getAll', {
data: [{ ...SNIPPET_1, accessUrl: null }],
})
const view = await renderPage()
fireEvent.press(view.getByText('Share'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'No link available')
expect(shareSpy).not.toHaveBeenCalled()
})
it('AVENDUI-07: sharing a snippet hands the access URL to the share sheet', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' } as any)
const view = await renderPage()
fireEvent.press(view.getByText('Share'))
await waitFor(() => {
expect(shareSpy).toHaveBeenCalledWith({ message: 'https://access.test/ABC123' })
})
expect(alertSpy).not.toHaveBeenCalled()
})
it('AVENDUI-08: the products count opens the product list dialog', async () => {
const view = await renderPage()
fireEvent.press(view.getByText('1 Items'))
expect(view.getByText('Products (1)')).toBeTruthy()
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
})
it('AVENDUI-09: the View Slot action is currently inert', async () => {
const view = await renderPage()
fireEvent.press(view.getByText('View Slot'))
// Catalogue gap #10: the slot navigation handler is `onPress={() => {}}`.
expect(router.push).not.toHaveBeenCalled()
expect(router.navigate).not.toHaveBeenCalled()
})
it('AVENDUI-10: the add button creates a snippet and refetches', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = await renderPage()
pressIcon(view, 'add')
await flush(2)
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE')
fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByText('Select products'))
fireEvent.press(view.getByText('Chicken Breast - 500g'))
fireEvent.press(view.getByText('Done'))
fireEvent.press(view.getByTestId('snippet-submit-button'))
await waitFor(() => {
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
snippetCode: 'NEWCODE',
slotId: undefined,
isPermanent: true,
skuIds: [11],
validTill: undefined,
})
})
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
// onSuccess closes the form and returns to the list.
await waitFor(() => {
expect(view.queryByText('Create Vendor Snippet')).toBeNull()
})
expect(view.getByText('ABC123')).toBeTruthy()
})
it('AVENDUI-11: Edit opens a prefilled form and updates the snippet', async () => {
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = await renderPage()
openMenu(view)
fireEvent.press(view.getByText('Edit'))
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
expect(view.getByDisplayValue('ABC123')).toBeTruthy()
fireEvent.press(view.getByTestId('snippet-submit-button'))
await waitFor(() => {
expect(lastMutationInput('admin.vendorSnippets.update')).toEqual({
id: 1,
updates: {
snippetCode: 'ABC123',
slotId: 1849,
isPermanent: false,
skuIds: [11],
validTill: SNIPPET_1.validTill,
},
})
})
})
it('AVENDUI-12: Delete confirms then deletes and refetches', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = await renderPage()
openMenu(view)
fireEvent.press(view.getByText('Delete'))
expect(alertSpy).toHaveBeenCalledWith(
'Delete Snippet',
'Are you sure you want to delete this vendor snippet?',
expect.any(Array)
)
expect(procedureMutationCalls('admin.vendorSnippets.delete')).toHaveLength(0)
confirmDelete(alertSpy)
await waitFor(() => {
expect(lastMutationInput('admin.vendorSnippets.delete')).toEqual({ id: 1 })
})
})
it('AVENDUI-13: a failing create/update/delete surfaces an alert', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
setProcedure('admin.vendorSnippets.create', { mode: 'error', error: new Error('save failed') })
setProcedure('admin.vendorSnippets.update', { mode: 'error', error: new Error('update failed') })
const view = await renderPage()
pressIcon(view, 'add')
await flush(2)
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE')
fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByText('Select products'))
fireEvent.press(view.getByText('Chicken Breast - 500g'))
fireEvent.press(view.getByText('Done'))
fireEvent.press(view.getByTestId('snippet-submit-button'))
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'save failed')
})
// The failed create keeps the form open; close it and fail an update too.
fireEvent.press(view.getByText('✕'))
await flush()
openMenu(view)
fireEvent.press(view.getByText('Edit'))
fireEvent.press(view.getByTestId('snippet-submit-button'))
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'update failed')
})
})
it('AVENDUI-14: View Orders fetches by snippet code and opens the orders view', async () => {
setProcedure('admin.vendorSnippets.getOrdersBySnippet', { data: SNIPPET_ORDERS })
const view = await renderPage()
openMenu(view)
fireEvent.press(view.getByText('View Orders'))
await flush(2)
expect(lastProcedureInput('admin.vendorSnippets.getOrdersBySnippet')).toEqual({
snippetCode: 'ABC123',
})
await waitFor(() => {
expect(view.getByText('Orders for "ABC123"')).toBeTruthy()
})
expect(view.getByText('ORD-1011')).toBeTruthy()
})
it('AVENDUI-15: a failed orders fetch alerts and stays on the list', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
setProcedure('admin.vendorSnippets.getOrdersBySnippet', {
mode: 'error',
error: new Error('orders boom'),
})
const view = await renderPage()
openMenu(view)
fireEvent.press(view.getByText('View Orders'))
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'orders boom')
})
expect(view.getByText('ABC123')).toBeTruthy()
})
it('AVENDUI-16: no matching orders shows the empty orders view', async () => {
setProcedure('admin.vendorSnippets.getOrdersBySnippet', {
data: { ...SNIPPET_ORDERS, data: [] },
})
const view = await renderPage()
openMenu(view)
fireEvent.press(view.getByText('View Orders'))
await waitFor(() => {
expect(view.getByText('No matching orders')).toBeTruthy()
})
})
it('AVENDUI-17: a snippet without an access URL/slot renders without crashing', async () => {
setProcedure('admin.vendorSnippets.getAll', {
data: [{ ...SNIPPET_1, slot: null, validTill: null, isPermanent: true }],
})
const view = await renderPage()
expect(view.getByText('ABC123')).toBeTruthy()
expect(view.getByText('Permanent')).toBeTruthy()
expect(view.getByText('Always Active')).toBeTruthy()
expect(view.getByText('View Slot')).toBeTruthy()
expect(view.queryByText('Expires')).toBeNull()
})
it('AVENDUI-18: the refresh shortcut is wired to refetch the list', async () => {
const addListener = jest.spyOn(DeviceEventEmitter, 'addListener')
const view = await renderPage()
// useManualRefresh subscribes the query refetch to REFRESH_EVENT.
const refreshSubscriptions = addListener.mock.calls.filter(
([eventName]) => eventName === REFRESH_EVENT
)
expect(refreshSubscriptions.length).toBeGreaterThanOrEqual(1)
// A manual refresh re-renders from the latest query payload without crashing.
setProcedure('admin.vendorSnippets.getAll', {
data: [{ ...SNIPPET_1, snippetCode: 'REFRESHED' }],
})
DeviceEventEmitter.emit(REFRESH_EVENT)
await waitFor(() => {
expect(view.getByText('REFRESHED')).toBeTruthy()
})
})
it('AVENDUI-19: the snippet menu exposes copy/edit/view/delete', async () => {
const view = await renderPage()
openMenu(view)
expect(view.getByText('Snippet Options')).toBeTruthy()
expect(view.getByText('View Orders')).toBeTruthy()
expect(view.getByText('Edit')).toBeTruthy()
expect(view.getByText('Copy URL')).toBeTruthy()
expect(view.getByText('Delete')).toBeTruthy()
})
it('AVENDUI-20: with no snippets the add action still creates one', async () => {
setProcedure('admin.vendorSnippets.getAll', { data: [] })
const view = await renderPage()
expect(view.getByText('No Snippets Yet')).toBeTruthy()
pressIcon(view, 'add')
expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
expect(view.getByText('Snippet Code')).toBeTruthy()
})
})