339 lines
11 KiB
TypeScript
339 lines
11 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import * as React from 'react'
|
|
import { render as rtlRender, RenderResult } from '@testing-library/react-native'
|
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
import { RefreshProvider } from 'common-ui'
|
|
import { AuthProvider } from '@/src/contexts/AuthContext'
|
|
import { trpc, trpcClient } from '@/src/trpc-client'
|
|
import { recordQueryInvalidation } from '../mocks/trpc-client'
|
|
import { setJsonResponse } from '../mocks/fetch-json'
|
|
import { __set as setSecureItem, __delete as deleteSecureItem } from '../mocks/secure-store-mock'
|
|
import {
|
|
AVAILABILITY_RESPONSE,
|
|
PRODUCT_AVAILABILITY,
|
|
PRODUCTS_RESPONSE,
|
|
SLOTS,
|
|
SLOTS_RESPONSE,
|
|
STORES_RESPONSE,
|
|
STORE_DETAIL_1,
|
|
MERGED_PRODUCTS,
|
|
TAGS,
|
|
AVAILABILITY,
|
|
TEST_JWT,
|
|
availabilityCacheUrl,
|
|
productsCacheUrl,
|
|
slotsCacheUrl,
|
|
storeDetailCacheUrl,
|
|
storesCacheUrl,
|
|
A1,
|
|
A2,
|
|
A3,
|
|
REGION_1,
|
|
REGION_2,
|
|
} from '../fixtures'
|
|
import {
|
|
useCentralProductStore,
|
|
useInitializeCentralProductStore,
|
|
} from '@/src/store/centralProductStore'
|
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
|
import { useRegionStore } from '@/src/store/regionStore'
|
|
import { bindNeoRegionQueryClient, useNeoRegionStore } from '@/src/store/neoRegionStore'
|
|
import { useAddressStore } from '@/src/store/addressStore'
|
|
|
|
export function createTestQueryClient(): QueryClient {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: {
|
|
queries: {
|
|
retry: false,
|
|
gcTime: Infinity,
|
|
staleTime: Infinity,
|
|
refetchOnWindowFocus: false,
|
|
},
|
|
mutations: { retry: false },
|
|
},
|
|
})
|
|
|
|
// Record real tRPC invalidations (`useUtils().x.invalidate()`) for the
|
|
// existing `procedureInvalidations(path)` assertions.
|
|
const originalInvalidate = queryClient.invalidateQueries.bind(queryClient)
|
|
;(queryClient as any).invalidateQueries = ((filters?: any, options?: any) => {
|
|
recordQueryInvalidation(filters)
|
|
return originalInvalidate(filters, options)
|
|
}) as any
|
|
|
|
return queryClient
|
|
}
|
|
|
|
type AuthMode = 'in' | 'out' | false
|
|
|
|
export interface RenderOptions {
|
|
queryClient?: QueryClient
|
|
auth?: AuthMode
|
|
withRefresh?: boolean
|
|
/**
|
|
* Mount the real catalogue producer (`useInitializeCentralProductStore`) so
|
|
* the mocked products JSON flows into the central product store exactly like
|
|
* production. Catalogue screens read the store now, so the page suites that
|
|
* drive them through `setJsonResponse(productsCacheUrl(), …)` opt in here.
|
|
*/
|
|
withProductStore?: boolean
|
|
userId?: string
|
|
token?: string
|
|
}
|
|
|
|
/** Production's only catalogue reader: JSON -> central product store. */
|
|
function ProductStoreSync() {
|
|
useInitializeCentralProductStore()
|
|
return null
|
|
}
|
|
|
|
export function seedAuthStorage(mode: AuthMode, userId = '5', token = TEST_JWT) {
|
|
if (mode === 'in') {
|
|
setSecureItem('authToken', token)
|
|
setSecureItem('userId', userId)
|
|
} else {
|
|
deleteSecureItem('authToken')
|
|
deleteSecureItem('userId')
|
|
}
|
|
}
|
|
|
|
export interface RenderWithProvidersResult extends RenderResult {
|
|
queryClient: QueryClient
|
|
}
|
|
|
|
export function renderWithProviders(
|
|
ui: React.ReactElement,
|
|
options: RenderOptions = {}
|
|
): RenderWithProvidersResult {
|
|
const queryClient = options.queryClient ?? createTestQueryClient()
|
|
bindNeoRegionQueryClient(queryClient)
|
|
const auth = options.auth ?? 'out'
|
|
const withRefresh = options.withRefresh ?? true
|
|
const withProductStore = options.withProductStore ?? false
|
|
|
|
if (auth !== false) {
|
|
// Synchronous seeding so AuthProvider's bootstrap effect reads the token.
|
|
seedAuthStorage(auth, options.userId, options.token)
|
|
}
|
|
|
|
const Wrapper = ({ children }: { children: React.ReactNode }) => {
|
|
let tree: React.ReactElement = React.createElement(React.Fragment, null, children)
|
|
if (withProductStore) {
|
|
tree = React.createElement(
|
|
React.Fragment,
|
|
null,
|
|
React.createElement(ProductStoreSync),
|
|
tree
|
|
)
|
|
}
|
|
if (auth !== false) {
|
|
tree = React.createElement(AuthProvider, null, tree)
|
|
}
|
|
if (withRefresh) {
|
|
tree = React.createElement(RefreshProvider, { queryClient, children: tree } as any)
|
|
}
|
|
// Real tRPC React hooks need the real client + provider.
|
|
tree = React.createElement(trpc.Provider, { client: trpcClient, queryClient, children: tree })
|
|
tree = React.createElement(QueryClientProvider, { client: queryClient }, tree)
|
|
return tree
|
|
}
|
|
|
|
const result = rtlRender(ui, { wrapper: Wrapper })
|
|
return { ...result, queryClient }
|
|
}
|
|
|
|
/** Render and let queued effects / microtasks settle. */
|
|
export async function renderAndFlush(
|
|
ui: React.ReactElement,
|
|
options: RenderOptions = {}
|
|
): Promise<RenderWithProvidersResult> {
|
|
const result = renderWithProviders(ui, options)
|
|
await flush()
|
|
return result
|
|
}
|
|
|
|
/** Await a macrotask so promise chains and effects settle. */
|
|
export async function flush(times = 2) {
|
|
const { act } = require('@testing-library/react-native')
|
|
for (let index = 0; index < times; index += 1) {
|
|
// eslint-disable-next-line no-await-in-loop
|
|
await act(async () => {
|
|
await new Promise((resolve) => setTimeout(resolve, 0))
|
|
})
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Register the standard regional CDN documents. Override any of them by calling
|
|
* `setJsonResponse` again *after* this helper (later registrations win).
|
|
*/
|
|
export function seedJsonCache(overrides: {
|
|
products?: any
|
|
availability?: any
|
|
slots?: any
|
|
stores?: any
|
|
storeDetail?: any
|
|
regionId?: number
|
|
} = {}) {
|
|
const regionId = overrides.regionId ?? 1
|
|
setJsonResponse(productsCacheUrl(regionId), overrides.products ?? PRODUCTS_RESPONSE)
|
|
setJsonResponse(availabilityCacheUrl(regionId), overrides.availability ?? AVAILABILITY_RESPONSE)
|
|
setJsonResponse(slotsCacheUrl(regionId), overrides.slots ?? SLOTS_RESPONSE)
|
|
setJsonResponse(`${slotsCacheUrl(regionId)}?v=123`, overrides.slots ?? SLOTS_RESPONSE)
|
|
setJsonResponse(storesCacheUrl(regionId), overrides.stores ?? STORES_RESPONSE)
|
|
setJsonResponse(storeDetailCacheUrl(1, regionId), overrides.storeDetail ?? STORE_DETAIL_1)
|
|
setJsonResponse(storeDetailCacheUrl(2, regionId), overrides.storeDetail ?? STORE_DETAIL_1)
|
|
}
|
|
|
|
/** Populate the central product/slot stores so `useGetCart` can enrich lines. */
|
|
export function seedCentralStores(options: { products?: any[]; tags?: any[]; slots?: any[] } = {}) {
|
|
const products = options.products ?? MERGED_PRODUCTS
|
|
const productStore = useCentralProductStore.getState()
|
|
productStore.setProducts(products)
|
|
// Catalogue metadata travels with the products: screens select both from the
|
|
// store, so a seeded store must look like a loaded one.
|
|
productStore.setTags((options.tags ?? TAGS) as any)
|
|
productStore.setCatalogMeta({ isLoading: false, error: null })
|
|
useCentralSlotStore
|
|
.getState()
|
|
.setSlotsData((options.slots ?? SLOTS) as any, PRODUCT_AVAILABILITY as any, AVAILABILITY as any)
|
|
}
|
|
|
|
/** Select a browsing region (+ bound) without going through the location flow. */
|
|
export function seedRegion(region = REGION_1, boundId: number | null = 7) {
|
|
useRegionStore.getState().setRegion(region as any, boundId)
|
|
const center = (region as any).center
|
|
seedNeoRegion({
|
|
regionId: region.id,
|
|
boundId: boundId ?? (region as any).effectiveBoundId ?? 7,
|
|
regionName: region.name,
|
|
coords: center ? { latitude: center.lat, longitude: center.lng } : undefined,
|
|
})
|
|
}
|
|
|
|
export function seedSelectedAddress(addressId: number | null = A1.id) {
|
|
useAddressStore.getState().setSelectedAddressId(addressId)
|
|
useNeoRegionStore.setState({ selectedAddressId: addressId })
|
|
}
|
|
|
|
/** Clear the neo region for the tests that assert the no-region state. */
|
|
export function clearNeoRegion() {
|
|
useNeoRegionStore.setState({
|
|
regionId: null,
|
|
boundId: null,
|
|
regionName: null,
|
|
coords: null,
|
|
origin: null,
|
|
regions: [],
|
|
addresses: [],
|
|
selectedAddressId: null,
|
|
needsAddressFormFlow: false,
|
|
needsAddressConfirmation: false,
|
|
})
|
|
}
|
|
|
|
/** Seed the neo region store (the post-migration source of truth). */
|
|
export function seedNeoRegion(options: {
|
|
regionId?: number
|
|
boundId?: number
|
|
regionName?: string
|
|
coords?: { latitude: number; longitude: number }
|
|
addresses?: any[]
|
|
selectedAddressId?: number | null
|
|
} = {}) {
|
|
const regionId = options.regionId ?? REGION_1.id
|
|
useNeoRegionStore.setState({
|
|
regionId,
|
|
boundId: options.boundId ?? 7,
|
|
regionName: options.regionName ?? REGION_1.name,
|
|
coords: options.coords ?? { latitude: 16.7488, longitude: 77.9851 },
|
|
origin: 'manual',
|
|
regions: [REGION_1 as any, REGION_2 as any],
|
|
addresses: (options.addresses ?? []) as any,
|
|
selectedAddressId: options.selectedAddressId ?? null,
|
|
needsAddressFormFlow: false,
|
|
needsAddressConfirmation: false,
|
|
})
|
|
}
|
|
|
|
/** Convenience: the usual home/cart boot state (region + catalogue + cache). */
|
|
const NEO_A2 = {
|
|
id: A2.id,
|
|
regionId: A2.regionId,
|
|
boundId: A2.boundId,
|
|
name: A2.name,
|
|
phone: A2.mobile,
|
|
addressLine1: A2.line1,
|
|
addressLine2: A2.line2,
|
|
city: A2.city,
|
|
state: A2.state,
|
|
isDefault: A2.isDefault,
|
|
latitude: A2.latitude,
|
|
longitude: A2.longitude,
|
|
googleMapsUrl: A2.googleMapsUrl,
|
|
}
|
|
|
|
const NEO_A3 = {
|
|
id: A3.id,
|
|
regionId: A3.regionId,
|
|
boundId: A3.boundId,
|
|
name: A3.name,
|
|
phone: A3.mobile,
|
|
addressLine1: A3.line1,
|
|
addressLine2: A3.line2,
|
|
city: A3.city,
|
|
state: A3.state,
|
|
isDefault: A3.isDefault,
|
|
latitude: A3.latitude,
|
|
longitude: A3.longitude,
|
|
googleMapsUrl: A3.googleMapsUrl,
|
|
}
|
|
|
|
const NEO_A1 = {
|
|
id: A1.id,
|
|
regionId: A1.regionId,
|
|
boundId: A1.boundId,
|
|
name: A1.name,
|
|
phone: A1.mobile,
|
|
addressLine1: A1.line1,
|
|
addressLine2: A1.line2,
|
|
city: A1.city,
|
|
state: A1.state,
|
|
isDefault: A1.isDefault,
|
|
latitude: A1.latitude,
|
|
longitude: A1.longitude,
|
|
googleMapsUrl: A1.googleMapsUrl,
|
|
}
|
|
|
|
export function seedBoot(options: { auth?: AuthMode; addressId?: number | null } = {}) {
|
|
// Mirror the launch decision: a default address exists, so A1 is selected
|
|
// unless the caller explicitly asks for no address (addressId: null).
|
|
const selectedId = options.addressId === undefined ? A1.id : options.addressId
|
|
seedJsonCache()
|
|
seedCentralStores()
|
|
seedRegion()
|
|
seedSelectedAddress(selectedId)
|
|
// The post-migration components read the neo store; seed a ready region so no
|
|
// test renders them outside LocationWrapperNeo with an empty store.
|
|
seedNeoRegion({
|
|
addresses: [NEO_A1, NEO_A2, NEO_A3],
|
|
selectedAddressId: selectedId,
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Simulate a cold start: nothing in the catalogue yet. Catalogue screens pick
|
|
* their loading/error copy from the store, so a first-load failure test needs an
|
|
* empty store — `seedBoot` seeds a *loaded* catalogue (that is what cart
|
|
* enrichment needs), and a failed background refresh keeps it on purpose.
|
|
*/
|
|
export function seedEmptyCatalogue() {
|
|
const store = useCentralProductStore.getState()
|
|
store.setProducts([])
|
|
store.setTags([])
|
|
store.setCatalogMeta({ isLoading: true, error: null })
|
|
}
|
|
|
|
export function setConsoleErrorMock() {
|
|
return jest.spyOn(console, 'error').mockImplementation(() => undefined)
|
|
}
|