freshyo/apps/user-ui/tests/pages/stores.test.tsx
2026-10-18 21:51:01 +05:30

374 lines
12 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 9 — Stores (`tests/pages/stores.test.tsx`, STORES-01..24).
*
* The page loads `stores.json` through `useStores`, renders one card per store
* (header, sampled products, "+N Discover" footer, Explore button) and reacts to
* the home deep-link flags in `useNavigationStore`.
*
* STORES-17..20 need to run the focus effect more than once, so `expo-router`'s
* `useFocusEffect` is narrowed to a registry that still runs on mount.
* STORES-22 needs a *second* focus for `useMarkDataFetchers`, which reads
* `@react-navigation/native`; that module is narrowed the same way.
*/
import * as React from 'react'
import { DeviceEventEmitter } from 'react-native'
import { act, fireEvent, waitFor, within } from '@testing-library/react-native'
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
import Stores from '@/app/(drawer)/(tabs)/stores/index'
import { useNavigationStore } from '@/src/store/navigationStore'
import { flush, renderWithProviders, seedBoot } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { router } from '../mocks/expo-router-mock'
import { setProcedure } from '../mocks/trpc-client'
import { jsonCallsFor, setJsonError, setJsonPending, setJsonResponse } from '../mocks/fetch-json'
import { A1, STORES, storesCacheUrl } from '../fixtures'
/** Focus listeners registered through the narrowed `@react-navigation/native`. */
const mockNavFocusCallbacks = new Set<() => void>()
/** Focus listeners registered through the narrowed `expo-router`. */
const mockRouterFocusCallbacks = 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(() => {
mockNavFocusCallbacks.add(callback)
const cleanup = callback()
return () => {
mockNavFocusCallbacks.delete(callback)
if (typeof cleanup === 'function') cleanup()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
},
}
})
jest.mock('expo-router', () => {
const React = require('react')
const actual = jest.requireActual(__dirname + '/../mocks/expo-router-mock')
return {
...actual,
useFocusEffect: (callback: () => void | (() => void)) => {
React.useEffect(() => {
mockRouterFocusCallbacks.add(callback)
const cleanup = callback()
return () => {
mockRouterFocusCallbacks.delete(callback)
if (typeof cleanup === 'function') cleanup()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
},
}
})
async function emitRouterFocus() {
await act(async () => {
Array.from(mockRouterFocusCallbacks).forEach((callback) => callback())
})
}
async function emitNavFocus() {
await act(async () => {
Array.from(mockNavFocusCallbacks).forEach((callback) => callback())
})
}
async function load() {
await flush(3)
}
function renderPage(auth: 'in' | 'out' | false = false) {
return renderWithProviders(<Stores />, { auth })
}
function seedStores(stores: any[]) {
setJsonResponse(storesCacheUrl(), { stores })
}
describe('Stores (STORES)', () => {
beforeEach(() => {
resetAllMocks()
mockNavFocusCallbacks.clear()
mockRouterFocusCallbacks.clear()
seedBoot()
})
it('STORES-01: stores pending shows the marketplace loading state', async () => {
setJsonPending(storesCacheUrl())
const { getByText, getByTestId } = renderPage()
await waitFor(() => expect(getByTestId('stores-loading')).toBeTruthy())
expect(getByText('Opening Marketplace...')).toBeTruthy()
})
it('STORES-02: a failed stores request shows the error state and Retry refetches', async () => {
setJsonError(storesCacheUrl(), new Error('offline'))
const { getByText, getByTestId } = renderPage()
await waitFor(() => expect(getByTestId('stores-error')).toBeTruthy())
expect(getByText('Store Fetch Failed')).toBeTruthy()
const before = jsonCallsFor(storesCacheUrl()).length
fireEvent.press(getByTestId('stores-retry'))
await flush(3)
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(before)
})
it('STORES-03: an empty stores document shows the empty state', async () => {
seedStores([])
const { getByText, getByTestId } = renderPage()
await load()
expect(getByTestId('stores-empty')).toBeTruthy()
expect(getByText('No Stores Available')).toBeTruthy()
})
it('STORES-04: loaded stores render every name, count and sampled product', async () => {
const { getAllByTestId, getByTestId } = renderPage()
await load()
const cards = getAllByTestId('store-card')
expect(cards).toHaveLength(2)
const first = within(cards[0])
expect(first.getByTestId('store-card-name').props.children).toBe('The Freshyo Meat House')
expect(first.getByTestId('store-card-count').props.children).toBe(12)
const firstSamples = first.getAllByTestId('store-sample-product')
expect(firstSamples).toHaveLength(2)
expect(within(firstSamples[0]).getByText('Chicken Breast')).toBeTruthy()
expect(within(firstSamples[1]).getByText('Cucumber')).toBeTruthy()
const second = within(cards[1])
expect(second.getByTestId('store-card-name').props.children).toBe('Freshyo Greens')
expect(second.getByTestId('store-card-count').props.children).toBe(2)
expect(second.getAllByTestId('store-sample-product')).toHaveLength(1)
// The page header and the tabs wrapper are present.
expect(getByTestId('stores-list')).toBeTruthy()
expect(getByTestId('tab-layout-wrapper')).toBeTruthy()
})
it('STORES-05: more products than samples renders a +N Discover card', async () => {
const { getAllByTestId, getByText } = renderPage()
await load()
// Store 1: 12 - 2 = +10, store 2: 2 - 1 = +1.
expect(getAllByTestId('store-discover-more')).toHaveLength(2)
expect(getByText('+10')).toBeTruthy()
expect(getByText('+1')).toBeTruthy()
})
it('STORES-06: a productCount equal to the samples renders no +N card', async () => {
seedStores([{ ...STORES[0], productCount: 2 }])
const { queryAllByTestId, getByTestId } = renderPage()
await load()
expect(getByTestId('store-card')).toBeTruthy()
expect(queryAllByTestId('store-discover-more')).toHaveLength(0)
})
it('STORES-07: a productCount lower than the samples renders no +N card', async () => {
seedStores([{ ...STORES[0], productCount: 1 }])
const { queryAllByTestId } = renderPage()
await load()
expect(queryAllByTestId('store-discover-more')).toHaveLength(0)
})
it('STORES-08: a store without sampled products renders an empty strip', async () => {
seedStores([{ ...STORES[1], productCount: 0, sampleProducts: [] }])
const { queryAllByTestId, getByTestId } = renderPage()
await load()
expect(getByTestId('store-card')).toBeTruthy()
expect(queryAllByTestId('store-sample-product')).toHaveLength(0)
expect(queryAllByTestId('store-discover-more')).toHaveLength(0)
})
it('STORES-09: a store whose name contains meat shows the halal/preservs banner', async () => {
const { getAllByTestId, getByLabelText } = renderPage()
await load()
expect(getAllByTestId('store-meat-banner')).toHaveLength(1)
expect(getByLabelText(/halal\.jpg/)).toBeTruthy()
expect(getByLabelText(/preservs\.jpg/)).toBeTruthy()
})
it('STORES-10: uppercase MEAT in the name still shows the banner', async () => {
seedStores([{ ...STORES[0], name: 'MEAT MARKET' }])
const { getAllByTestId } = renderPage()
await load()
expect(getAllByTestId('store-meat-banner')).toHaveLength(1)
})
it('STORES-11: a non-meat store shows no banner', async () => {
seedStores([{ ...STORES[1] }])
const { queryAllByTestId, getByTestId } = renderPage()
await load()
expect(getByTestId('store-card')).toBeTruthy()
expect(queryAllByTestId('store-meat-banner')).toHaveLength(0)
})
it('STORES-12: a store without a signed image shows the storefront fallback', async () => {
const { getAllByTestId } = renderPage()
await load()
// Only "Freshyo Greens" has `signedImageUrl: null`.
expect(getAllByTestId('store-image-fallback')).toHaveLength(1)
})
it('STORES-13: the store name is truncated to a single line', async () => {
seedStores([
{ ...STORES[0], name: 'The Freshyo Meat House With A Very Long Name That Overflows' },
])
const { getByTestId } = renderPage()
await load()
expect(getByTestId('store-card-name').props.numberOfLines).toBe(1)
})
it('STORES-14: tapping the store header pushes the store detail route', async () => {
const { getAllByTestId } = renderPage()
await load()
fireEvent.press(getAllByTestId('store-card-header')[0])
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/stores/store-detail/1')
})
it('STORES-15: tapping a sample product opens the same store detail route', async () => {
const { getAllByTestId } = renderPage()
await load()
fireEvent.press(getAllByTestId('store-sample-product')[0])
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/stores/store-detail/1')
})
it('STORES-16: tapping Explore Store opens the same store detail route', async () => {
const { getAllByTestId } = renderPage()
await load()
fireEvent.press(getAllByTestId('store-explore')[0])
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/stores/store-detail/1')
})
it('STORES-17: a home deep-link pushes the detail once and clears both flags', async () => {
useNavigationStore.setState({ isNavigatedFromHome: true, selectedStoreId: 1 })
renderPage()
await load()
expect(router.push).toHaveBeenCalledTimes(1)
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/stores/store-detail/1')
expect(useNavigationStore.getState().isNavigatedFromHome).toBe(false)
expect(useNavigationStore.getState().selectedStoreId).toBeNull()
})
it('STORES-18: only isNavigatedFromHome set does not navigate', async () => {
useNavigationStore.setState({ isNavigatedFromHome: true, selectedStoreId: null })
renderPage()
await load()
expect(router.push).not.toHaveBeenCalled()
// The flag is left untouched because there is no target.
expect(useNavigationStore.getState().isNavigatedFromHome).toBe(true)
})
it('STORES-19: only selectedStoreId set does not navigate', async () => {
useNavigationStore.setState({ isNavigatedFromHome: false, selectedStoreId: 1 })
renderPage()
await load()
expect(router.push).not.toHaveBeenCalled()
expect(useNavigationStore.getState().selectedStoreId).toBe(1)
})
it('STORES-20: running the focus effect again does not push a second time', async () => {
useNavigationStore.setState({ isNavigatedFromHome: true, selectedStoreId: 1 })
renderPage()
await load()
expect(router.push).toHaveBeenCalledTimes(1)
await emitRouterFocus()
await emitRouterFocus()
await flush(3)
expect(router.push).toHaveBeenCalledTimes(1)
})
it('STORES-21: a refresh event refetches the stores document', async () => {
renderPage()
await load()
const before = jsonCallsFor(storesCacheUrl()).length
await act(async () => {
DeviceEventEmitter.emit(REFRESH_EVENT)
})
await flush(3)
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(before)
})
it('STORES-22: a re-focus through useMarkDataFetchers refetches stores', async () => {
renderPage()
await load()
const before = jsonCallsFor(storesCacheUrl()).length
await emitNavFocus()
await flush(3)
expect(jsonCallsFor(storesCacheUrl()).length).toBeGreaterThan(before)
})
it('STORES-23: the floating cart bar is visible', async () => {
const { getByTestId, getByText } = renderPage()
await load()
expect(getByTestId('go-to-cart')).toBeTruthy()
expect(getByText('No Items In Cart')).toBeTruthy()
})
it('STORES-24: the location bar shows the active region and address', async () => {
setProcedure('user.address.getUserAddresses', {
data: {
data: [{ ...A1, addressLine1: '12 Main Road', addressLine2: null }],
},
})
const { getByTestId } = renderPage('in')
await load()
const bar = within(getByTestId('location-bar'))
expect(bar.getByText('Deliver to')).toBeTruthy()
expect(bar.getByText('Mahabubnagar')).toBeTruthy()
expect(bar.getByText('12 Main Road, Mahabubnagar')).toBeTruthy()
})
})