229 lines
7.9 KiB
TypeScript
229 lines
7.9 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,
|
|
REGION_1,
|
|
} from '../fixtures'
|
|
import {
|
|
useCentralProductStore,
|
|
useInitializeCentralProductStore,
|
|
} from '@/src/store/centralProductStore'
|
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
|
import { useRegionStore } from '@/src/store/regionStore'
|
|
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()
|
|
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)
|
|
}
|
|
|
|
export function seedSelectedAddress(addressId: number | null = A1.id) {
|
|
useAddressStore.getState().setSelectedAddressId(addressId)
|
|
}
|
|
|
|
/** Convenience: the usual home/cart boot state (region + catalogue + cache). */
|
|
export function seedBoot(options: { auth?: AuthMode; addressId?: number | null } = {}) {
|
|
seedJsonCache()
|
|
seedCentralStores()
|
|
seedRegion()
|
|
seedSelectedAddress(options.addressId ?? null)
|
|
}
|
|
|
|
/**
|
|
* 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)
|
|
}
|