298 lines
10 KiB
TypeScript
298 lines
10 KiB
TypeScript
/**
|
|
* Popular items editor
|
|
* (app/(drawer)/dashboard/customize-app/popular-items.tsx) — resolves the
|
|
* `popularItems` constant against the product catalogue, supports removing /
|
|
* adding items and saves the ordered product ids 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 MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
|
|
|
import PopularItems from '@/app/(drawer)/dashboard/customize-app/popular-items'
|
|
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 product = (id: number, name: string, price: number) => ({
|
|
id,
|
|
name,
|
|
price,
|
|
marketPrice: null,
|
|
images: [`${name}.jpg`],
|
|
storeId: null,
|
|
nextDeliveryDate: null,
|
|
isOutOfStock: false,
|
|
})
|
|
|
|
const productsResponse = {
|
|
products: [product(1, 'Chicken', 100), product(2, 'Mutton', 200), product(3, 'Fish', 50)],
|
|
count: 3,
|
|
}
|
|
|
|
// SKU ids intentionally match product ids so the selector's ids resolve against
|
|
// the product catalogue (see the reported popular-items add-flow bug).
|
|
const skusResponse = {
|
|
skus: [
|
|
{ id: 3, productId: 3, productName: 'Fish', label: 'Fish 1kg' },
|
|
],
|
|
}
|
|
|
|
const constants = [{ key: 'popularItems', value: [1, 2] }]
|
|
|
|
const pressLastAlertButton = (label: string) => {
|
|
const calls = (Alert.alert as jest.Mock).mock.calls
|
|
const call = calls[calls.length - 1]
|
|
const buttons = (call?.[2] ?? []) as { text: string; onPress?: () => void }[]
|
|
act(() => buttons.find((b) => b.text === label)?.onPress?.())
|
|
}
|
|
|
|
const pressIcon = (result: ReturnType<typeof renderWithProviders>, name: string, index = 0) => {
|
|
const icons = result.UNSAFE_getAllByType(MaterialIcons).filter((n) => n.props.name === name)
|
|
fireEvent.press(icons[index])
|
|
}
|
|
|
|
describe('Popular items editor', () => {
|
|
beforeEach(async () => {
|
|
await resetStorage()
|
|
setupApiMocks()
|
|
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
|
})
|
|
|
|
it('shows the loading state while constants load', () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': () => new Promise(() => {}),
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
},
|
|
})
|
|
renderWithProviders(<PopularItems />)
|
|
|
|
expect(screen.getByText('Loading constants...')).toBeVisible()
|
|
})
|
|
|
|
it('shows the error state when constants fail', async () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': () => {
|
|
throw new Error('boom')
|
|
},
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
},
|
|
})
|
|
renderWithProviders(<PopularItems />)
|
|
|
|
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
|
|
})
|
|
|
|
it('renders the popular items resolved from the constant', async () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': constants,
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
},
|
|
})
|
|
renderWithProviders(<PopularItems />)
|
|
|
|
expect(await screen.findByText('Chicken')).toBeVisible()
|
|
expect(screen.getByText('Mutton')).toBeVisible()
|
|
expect(screen.getByText('₹100')).toBeVisible()
|
|
expect(screen.queryByText('Fish')).toBeNull()
|
|
})
|
|
|
|
it('shows the empty state when nothing is configured', async () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': [{ key: 'popularItems', value: [] }],
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
},
|
|
})
|
|
renderWithProviders(<PopularItems />)
|
|
|
|
await waitFor(() =>
|
|
expect(screen.getByText('No popular items configured')).toBeVisible()
|
|
)
|
|
})
|
|
|
|
it('removes a product and saves the remaining ids', async () => {
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': constants,
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
|
},
|
|
})
|
|
const result = renderWithProviders(<PopularItems />)
|
|
|
|
await screen.findByText('Chicken')
|
|
pressIcon(result, 'delete', 0)
|
|
pressLastAlertButton('Remove')
|
|
await waitFor(() => expect(screen.queryByText('Chicken')).toBeNull())
|
|
|
|
fireEvent.press(screen.getByText('Save'))
|
|
|
|
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
|
|
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
|
|
constants: [{ key: 'popularItems', value: [2] }],
|
|
})
|
|
await waitFor(() =>
|
|
expect(Alert.alert).toHaveBeenCalledWith(
|
|
'Success',
|
|
'Popular items updated successfully!'
|
|
)
|
|
)
|
|
})
|
|
|
|
it('saves a reordered list', async () => {
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': constants,
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
|
},
|
|
})
|
|
const result = renderWithProviders(<PopularItems />)
|
|
|
|
await screen.findByText('Chicken')
|
|
const list = result.UNSAFE_getByType(require('react-native-draggable-flatlist').default)
|
|
act(() => {
|
|
list.props.onDragEnd({ data: [list.props.data[1], list.props.data[0]] })
|
|
})
|
|
fireEvent.press(screen.getByText('Save'))
|
|
|
|
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
|
|
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
|
|
constants: [{ key: 'popularItems', value: [2, 1] }],
|
|
})
|
|
})
|
|
|
|
it('refetches the constants after saving', async () => {
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': constants,
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
|
},
|
|
})
|
|
const client = createQueryClient()
|
|
const invalidateSpy = jest.spyOn(client, 'invalidateQueries')
|
|
const result = renderWithProviders(<PopularItems />, { queryClient: client })
|
|
|
|
await screen.findByText('Chicken')
|
|
const before = procCount(api.fetchMock, 'admin.const.getConstants')
|
|
// 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[1], list.props.data[0]] })
|
|
})
|
|
fireEvent.press(screen.getByText('Save'))
|
|
|
|
await waitFor(() =>
|
|
expect(procCount(api.fetchMock, 'admin.const.getConstants')).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.const.getConstants'] })
|
|
).toHaveLength(0)
|
|
})
|
|
|
|
it('does not save while nothing changed', async () => {
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': constants,
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
},
|
|
})
|
|
renderWithProviders(<PopularItems />)
|
|
|
|
await screen.findByText('Chicken')
|
|
fireEvent.press(screen.getByText('Save'))
|
|
|
|
expect(procCount(api.fetchMock, 'admin.const.updateConstants')).toBe(0)
|
|
})
|
|
|
|
it('adds a product through the add dialog and saves it', async () => {
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': constants,
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
'common.product.getAllSkusSummary': skusResponse,
|
|
'admin.const.updateConstants': { success: true, updatedCount: 1, keys: ['popularItems'] },
|
|
},
|
|
})
|
|
const result = renderWithProviders(<PopularItems />)
|
|
|
|
await screen.findByText('Chicken')
|
|
pressIcon(result, 'add')
|
|
expect(await screen.findByText('Add Popular Items')).toBeVisible()
|
|
|
|
fireEvent.press(screen.getByText('Choose products...'))
|
|
fireEvent.press(await screen.findByTestId('undefined-option-3'))
|
|
fireEvent.press(screen.getByText('Done'))
|
|
fireEvent.press(await screen.findByText('Add 1 Product'))
|
|
|
|
await waitFor(() => expect(screen.getByText('Fish')).toBeVisible())
|
|
|
|
fireEvent.press(screen.getByText('Save'))
|
|
await waitFor(() => expectProcedureCalled(api.fetchMock, 'admin.const.updateConstants'))
|
|
expect(lastProcedureInput(api.fetchMock, 'admin.const.updateConstants')).toEqual({
|
|
constants: [{ key: 'popularItems', value: [1, 2, 3] }],
|
|
})
|
|
})
|
|
|
|
it('shows the saving label while the update is pending', async () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'admin.const.getConstants': constants,
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
'admin.const.updateConstants': () => new Promise(() => {}),
|
|
},
|
|
})
|
|
const result = renderWithProviders(<PopularItems />)
|
|
|
|
await screen.findByText('Chicken')
|
|
pressIcon(result, 'delete', 0)
|
|
pressLastAlertButton('Remove')
|
|
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.const.getConstants': () => {
|
|
throw new Error('boom')
|
|
},
|
|
'common.product.getAllProductsSummary': productsResponse,
|
|
},
|
|
})
|
|
renderWithProviders(<PopularItems />)
|
|
|
|
await waitFor(() => expect(screen.getByText('Failed to load constants')).toBeVisible())
|
|
fireEvent.press(screen.getByText('Go Back'))
|
|
expect(routerMock.back).toHaveBeenCalled()
|
|
})
|
|
})
|