freshyo/apps/user-ui/tests/pages/search-results.test.tsx
2026-11-16 01:28:18 +05:30

352 lines
11 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 7 — Search results (`tests/pages/search-results.test.tsx`,
* SEARCH-01..22).
*
* Products come from the versioned CDN documents (`seedBoot`); the search itself
* is a client-side Fuse.js filter behind a 300ms debounce, so the debounce cases
* switch to fake timers *after* the initial data load has settled.
*
* `useMarkDataFetchers` (SEARCH-17) deliberately skips the mount focus and the
* shared `@react-navigation/native` mock only runs the focus effect on mount, so
* this file narrows that mock with a focus emitter to drive a second focus.
*/
import * as React from 'react'
import { RefreshControl } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native'
import SearchResults from '@/app/(drawer)/(tabs)/home/search-results/index'
import { useCartStore } from '@/src/store/cartStore'
import { flush, renderWithProviders, seedBoot, seedEmptyCatalogue } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { router, __setParams } from '../mocks/expo-router-mock'
import { jsonCallsFor, setJsonError, setJsonPending } from '../mocks/fetch-json'
import { __set as setSecureItem } from '../mocks/secure-store-mock'
import { CART_REG, productsCacheUrl } from '../fixtures'
/** Focus listeners registered through the (narrowed) navigation mock. */
const mockFocusCallbacks = new Set<() => void>()
jest.mock('@react-navigation/native', () => {
const React = require('react')
const actual = jest.requireActual(__dirname + '/../mocks/react-navigation-mock')
return {
...actual,
useFocusEffect: (callback: () => void | (() => void)) => {
React.useEffect(() => {
mockFocusCallbacks.add(callback)
const cleanup = callback()
return () => {
mockFocusCallbacks.delete(callback)
if (typeof cleanup === 'function') cleanup()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
},
}
})
/** Simulate the screen being focused again (what `useMarkDataFetchers` reacts to). */
async function emitFocus() {
await act(async () => {
Array.from(mockFocusCallbacks).forEach((callback) => callback())
})
}
const SEARCH_INPUT = 'search-input-input'
const SEARCH_DEBOUNCE_MS = 300
const ALL_NAMES = [
'Chicken Breast',
'Cucumber',
'Mutton',
'Offer Chicken',
'Paneer',
'No Image Item',
'No Slot Item',
'Family Combo',
]
function renderPage(params: Record<string, any> = {}) {
__setParams(params)
return renderWithProviders(<SearchResults />, { auth: false, withProductStore: true })
}
/**
* The catalogue only renders once the regional consts have hydrated (the
* products query stays disabled before that), so every assertion runs after a
* few macrotask flushes.
*/
async function loadCatalogue() {
await flush(3)
}
/** Advance fake timers inside `act`. */
async function advance(ms: number) {
await act(async () => {
jest.advanceTimersByTime(ms)
})
}
describe('Search results (SEARCH)', () => {
beforeEach(() => {
resetAllMocks()
mockFocusCallbacks.clear()
seedBoot()
})
it('SEARCH-01: without a q param the page shows every merged product', async () => {
const { getByText, getAllByTestId } = renderPage()
await loadCatalogue()
expect(getByText('All Products')).toBeTruthy()
expect(getAllByTestId('product-card')).toHaveLength(ALL_NAMES.length)
ALL_NAMES.forEach((name) => expect(getByText(name)).toBeTruthy())
})
it('SEARCH-02: a q param prefills the input and filters after the debounce', async () => {
const { getByTestId, queryByText } = renderPage({ q: 'Cucumber' })
expect(getByTestId(SEARCH_INPUT).props.value).toBe('Cucumber')
await loadCatalogue()
expect(queryByText('Cucumber')).toBeTruthy()
expect(queryByText('Chicken Breast')).toBeNull()
})
it('SEARCH-03: before the 300ms debounce the old results remain', async () => {
const { getByTestId, queryByText } = renderPage()
await loadCatalogue()
expect(queryByText('Chicken Breast')).toBeTruthy()
jest.useFakeTimers()
fireEvent.changeText(getByTestId(SEARCH_INPUT), 'Cucumber')
await advance(SEARCH_DEBOUNCE_MS - 1)
// Not debounced yet: still the full catalogue.
expect(queryByText('Chicken Breast')).toBeTruthy()
expect(queryByText('Mutton')).toBeTruthy()
})
it('SEARCH-04: at the 300ms boundary the results update', async () => {
const { getByTestId, queryByText } = renderPage()
await loadCatalogue()
jest.useFakeTimers()
fireEvent.changeText(getByTestId(SEARCH_INPUT), 'Cucumber')
await advance(SEARCH_DEBOUNCE_MS - 1)
expect(queryByText('Chicken Breast')).toBeTruthy()
await advance(1)
expect(queryByText('Cucumber')).toBeTruthy()
expect(queryByText('Chicken Breast')).toBeNull()
})
it('SEARCH-05: rapid typing applies only the final query', async () => {
const { getByTestId, queryByText } = renderPage()
await loadCatalogue()
jest.useFakeTimers()
const input = getByTestId(SEARCH_INPUT)
fireEvent.changeText(input, 'C')
await advance(100)
fireEvent.changeText(input, 'Cu')
await advance(100)
fireEvent.changeText(input, 'Cucumber')
await advance(100)
// Every keystroke re-arms the debounce: nothing has been searched yet.
expect(queryByText('Chicken Breast')).toBeTruthy()
await advance(200)
expect(queryByText('Cucumber')).toBeTruthy()
expect(queryByText('Chicken Breast')).toBeNull()
})
it('SEARCH-06: a query matching the product name filters the list', async () => {
const { queryByText } = renderPage({ q: 'Cucumber' })
await loadCatalogue()
expect(queryByText('Cucumber')).toBeTruthy()
expect(queryByText('Chicken Breast')).toBeNull()
})
it('SEARCH-07: a query matching the shortDescription filters the list', async () => {
// P_CHICKEN.shortDescription === 'Tender boneless breast'.
const { queryByText } = renderPage({ q: 'boneless' })
await loadCatalogue()
expect(queryByText('Chicken Breast')).toBeTruthy()
expect(queryByText('Cucumber')).toBeNull()
})
it('SEARCH-08: a typo within the Fuse threshold still matches', async () => {
const { queryByText } = renderPage({ q: 'Chickn' })
await loadCatalogue()
expect(queryByText('Chicken Breast')).toBeTruthy()
expect(queryByText('Cucumber')).toBeNull()
})
it('SEARCH-09: no match shows the empty state and the search hint', async () => {
const { getByText } = renderPage({ q: 'zzzzzz' })
await loadCatalogue()
expect(getByText('No products found')).toBeTruthy()
expect(getByText('Try adjusting your search for "zzzzzz"')).toBeTruthy()
})
it('SEARCH-10: clearing the query restores every product and the header', async () => {
const { getByTestId, getByText, queryByText, getAllByTestId } = renderPage({
q: 'Cucumber',
})
await loadCatalogue()
expect(queryByText('Chicken Breast')).toBeNull()
fireEvent.changeText(getByTestId(SEARCH_INPUT), '')
await waitFor(() => expect(getByText('All Products')).toBeTruthy())
expect(getAllByTestId('product-card')).toHaveLength(ALL_NAMES.length)
})
it('SEARCH-11: a whitespace-only query behaves like an empty one', async () => {
const { getAllByTestId } = renderPage({ q: ' ' })
await loadCatalogue()
expect(getAllByTestId('product-card')).toHaveLength(ALL_NAMES.length)
})
it('SEARCH-12: special characters do not crash and are echoed in the header', async () => {
const { getByText } = renderPage({ q: 'Chicken "special"' })
await loadCatalogue()
expect(getByText('Search Results for "Chicken "special""')).toBeTruthy()
})
it('SEARCH-13: a pending products request shows the loading empty state', async () => {
setJsonPending(productsCacheUrl())
const { getByText } = renderPage()
await loadCatalogue()
expect(getByText('Loading products...')).toBeTruthy()
})
it('SEARCH-14: a failed products request falls back to the empty state', async () => {
seedEmptyCatalogue()
setJsonError(productsCacheUrl(), new Error('offline'))
const { getByText } = renderPage()
await loadCatalogue()
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(0)
expect(getByText('No products found')).toBeTruthy()
})
it('SEARCH-15: the search input is focused through requestAnimationFrame on mount', async () => {
const raf = jest.spyOn(global as any, 'requestAnimationFrame')
renderPage()
await flush(2)
expect(raf).toHaveBeenCalled()
})
it('SEARCH-16: pull to refresh refetches the products document', async () => {
const { UNSAFE_getAllByType } = renderPage()
await loadCatalogue()
const before = jsonCallsFor(productsCacheUrl()).length
await act(async () => {
UNSAFE_getAllByType(RefreshControl)[0].props.onRefresh()
})
await flush(3)
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before)
})
it('SEARCH-17: a re-focus through useMarkDataFetchers refetches products', async () => {
renderPage()
await loadCatalogue()
const before = jsonCallsFor(productsCacheUrl()).length
await emitFocus()
await flush(3)
expect(jsonCallsFor(productsCacheUrl()).length).toBeGreaterThan(before)
})
it('SEARCH-18: tapping a result pushes the home product detail route', async () => {
const { getAllByTestId } = renderPage()
await loadCatalogue()
fireEvent.press(getAllByTestId('product-card')[0])
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/product-detail/2')
})
it('SEARCH-19: the card add button queues the add-to-cart dialog product', async () => {
const { getAllByText } = renderPage()
await loadCatalogue()
fireEvent.press(getAllByText('Add to Cart')[0])
expect(useCartStore.getState().addedToCartProduct?.productId).toBe(2)
})
it('SEARCH-20: the floating cart bar reflects the local cart', async () => {
setSecureItem('cart_items', CART_REG)
const { getByText, getByTestId } = renderPage()
await loadCatalogue()
expect(getByText(/1 Item/)).toBeTruthy()
expect(getByText(/₹430/)).toBeTruthy()
expect(getByTestId('go-to-cart')).toBeTruthy()
})
it('SEARCH-21: combo-only SKUs stay hidden from the catalogue', async () => {
const { queryByText } = renderPage()
await loadCatalogue()
expect(queryByText('Combo Only SKU')).toBeNull()
})
it('SEARCH-22: unmounting before the debounce fires clears the timer', async () => {
const errorSpy = jest.spyOn(console, 'error')
const clearTimeoutSpy = jest.spyOn(global as any, 'clearTimeout')
const { getByTestId, unmount } = renderPage()
await loadCatalogue()
jest.useFakeTimers()
fireEvent.changeText(getByTestId(SEARCH_INPUT), 'Cucumber')
const errorsBeforeUnmount = errorSpy.mock.calls.length
unmount()
expect(clearTimeoutSpy).toHaveBeenCalled()
await advance(SEARCH_DEBOUNCE_MS + 100)
const afterUnmount = errorSpy.mock.calls
.slice(errorsBeforeUnmount)
.map((call) => String(call[0] ?? ''))
expect(
afterUnmount.filter((message) =>
/not wrapped in act|unmounted|cannot update/i.test(message)
)
).toEqual([])
errorSpy.mockRestore()
clearTimeoutSpy.mockRestore()
})
})