/** * All items order editor * (app/(drawer)/dashboard/customize-app/all-items-order.tsx) — sorts the * catalogue by the `allItemsOrder` constant, supports drag reordering and saves * the full ordered id list back to the constant. */ jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) import React from 'react' import { Alert } from 'react-native' import { act, fireEvent, screen, waitFor } from '@testing-library/react-native' import AllItemsOrder from '@/app/(drawer)/dashboard/customize-app/all-items-order' import { resetStorage, setupApiMocks } from '../mocks/api' import { expectProcedureCalled, lastProcedureInput, procCount, } from '../mocks/procedures' import { routerMock } from '../mocks/router' import { createQueryClient, renderWithProviders } from '../helpers/render' const productsResponse = { products: [ { id: 1, name: 'Chicken', images: ['chicken.jpg'], isOutOfStock: false }, { id: 2, name: 'Mutton', images: ['mutton.jpg'], isOutOfStock: true }, { id: 3, name: 'Fish', images: [], isOutOfStock: false }, ], count: 3, } describe('All items order editor', () => { beforeEach(async () => { await resetStorage() setupApiMocks() jest.spyOn(Alert, 'alert').mockImplementation(() => {}) }) it('shows the loading state while constants load', () => { setupApiMocks({ procedures: { 'admin.region.getRegionConstants': () => new Promise(() => {}), 'common.product.getAllProductsSummary': productsResponse, }, }) renderWithProviders() expect(screen.getByText('Loading order...')).toBeVisible() }) it('shows the error state when constants fail', async () => { setupApiMocks({ procedures: { 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'common.product.getAllProductsSummary': productsResponse, }, }) renderWithProviders() await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible()) }) it('sorts products by the constant and appends the rest', async () => { setupApiMocks({ procedures: { 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [2, 1] }], 'common.product.getAllProductsSummary': productsResponse, }, }) const result = renderWithProviders() await waitFor(() => expect(screen.getByText('Mutton')).toBeVisible()) const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default) expect(list.props.data.map((p: { id: number }) => p.id)).toEqual([2, 1, 3]) expect(screen.getByText(/3 items/)).toBeVisible() }) it('accepts a comma-separated order string', async () => { setupApiMocks({ procedures: { 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: '3' }], 'common.product.getAllProductsSummary': productsResponse, }, }) const result = renderWithProviders() await waitFor(() => expect(screen.getByText('Fish')).toBeVisible()) const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default) expect(list.props.data.map((p: { id: number }) => p.id)).toEqual([3, 1, 2]) }) it('shows the empty state when there are no products', async () => { setupApiMocks({ procedures: { 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [] }], 'common.product.getAllProductsSummary': { products: [], count: 0 }, }, }) renderWithProviders() await waitFor(() => expect(screen.getByText('No products available')).toBeVisible()) }) it('disables Save until the order changes, then saves the full list', async () => { const api = setupApiMocks({ procedures: { 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], 'common.product.getAllProductsSummary': productsResponse, 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] }, }, }) const result = renderWithProviders() await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible()) fireEvent.press(screen.getByText('Save')) expect(procCount(api.fetchMock, 'admin.region.updateRegionConstants')).toBe(0) const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default) act(() => { list.props.onDragEnd({ data: [list.props.data[2], list.props.data[0], list.props.data[1]] }) }) fireEvent.press(screen.getByText('Save')) await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.region.updateRegionConstants')) expect(lastProcedureInput(api.fetchMock, 'admin.region.updateRegionConstants')).toEqual({ constants: [{ key: 'allItemsOrder', value: [3, 1, 2] }], }) await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith( 'Success', 'All items order updated successfully!' ) ) }) it('refetches the constants after saving', async () => { const api = setupApiMocks({ procedures: { 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], 'common.product.getAllProductsSummary': productsResponse, 'admin.region.updateRegionConstants': { success: true, updatedCount: 1, keys: ['allItemsOrder'] }, }, }) const client = createQueryClient() const invalidateSpy = jest.spyOn(client, 'invalidateQueries') const result = renderWithProviders(, { queryClient: client }) await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible()) const before = procCount(api.fetchMock, 'admin.region.getRegionConstants') // Delta, not an absolute: the suite shares one httpBatchLink client, so a prior test's // request can land in this test's fetchMock. expect(before).toBeGreaterThan(0) const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default) act(() => { list.props.onDragEnd({ data: [list.props.data[2], list.props.data[0], list.props.data[1]] }) }) fireEvent.press(screen.getByText('Save')) await waitFor(() => expect(procCount(api.fetchMock, 'admin.region.getRegionConstants')).toBeGreaterThan(before) ) // The refetch is driven by the path-based invalidation, not by updateConstants itself. // Asserting the ARRAY path is the point: the old dotted string matched no query at all. await waitFor(() => expect(invalidateSpy).toHaveBeenCalled()) expect( invalidateSpy.mock.calls .map((call) => (call[0] as { queryKey?: unknown[] } | undefined)?.queryKey) .map((key) => (Array.isArray(key) ? key[0] : null)) ).toContainEqual(['admin', 'const', 'getConstants']) // Same client, same cache: the array path matches the live query, the dotted form matches none. expect( client.getQueryCache().findAll({ queryKey: [['admin', 'const', 'getConstants']] }).length ).toBeGreaterThan(0) expect( client.getQueryCache().findAll({ queryKey: ['admin.region.getRegionConstants'] }) ).toHaveLength(0) }) it('shows the saving label while the update is pending', async () => { setupApiMocks({ procedures: { 'admin.region.getRegionConstants': [{ key: 'allItemsOrder', value: [1, 2, 3] }], 'common.product.getAllProductsSummary': productsResponse, 'admin.region.updateRegionConstants': () => new Promise(() => {}), }, }) const result = renderWithProviders() await waitFor(() => expect(screen.getByText('Chicken')).toBeVisible()) const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default) act(() => { list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0], list.props.data[2]] }) }) fireEvent.press(screen.getByText('Save')) await waitFor(() => expect(screen.getByText('Saving...')).toBeVisible()) }) it('goes back from the header and the error state', async () => { setupApiMocks({ procedures: { 'admin.region.getRegionConstants': () => { throw new Error('boom') }, 'common.product.getAllProductsSummary': productsResponse, }, }) renderWithProviders() await waitFor(() => expect(screen.getByText('Failed to load order')).toBeVisible()) fireEvent.press(screen.getByText('Go Back')) expect(routerMock.back).toHaveBeenCalled() }) })