platform-codebase/@packages/@testing/test-utils/src/providers/test-wrapper.tsx
2026-01-18 09:20:18 -08:00

67 lines
1.8 KiB
TypeScript
Executable file

/**
* Test Wrapper Providers
*
* Wrapper components for testing React components with required context providers.
*/
import { type ReactNode, type FC } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export interface TestWrapperOptions {
/** Custom QueryClient instance */
queryClient?: QueryClient
/** Additional providers to wrap around children */
additionalProviders?: FC<{ children: ReactNode }>[]
}
/**
* Create a default QueryClient for testing
*/
export function createTestQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
gcTime: 0,
staleTime: 0,
},
mutations: {
retry: false,
},
},
})
}
/**
* Create a QueryClient wrapper for testing React Query hooks
*/
export function createQueryClientWrapper(
queryClient?: QueryClient
): FC<{ children: ReactNode }> {
const client = queryClient || createTestQueryClient()
return function QueryClientWrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={client}>{children}</QueryClientProvider>
}
}
/**
* Create a test wrapper with all common providers
*/
export function createTestWrapper(options: TestWrapperOptions = {}): FC<{ children: ReactNode }> {
const { queryClient, additionalProviders = [] } = options
const QueryWrapper = createQueryClientWrapper(queryClient)
return function TestWrapper({ children }: { children: ReactNode }) {
let content = children
// Wrap with additional providers (innermost first)
for (let i = additionalProviders.length - 1; i >= 0; i--) {
const Provider = additionalProviders[i]
content = <Provider>{content}</Provider>
}
// Wrap with QueryClient (outermost)
return <QueryWrapper>{content}</QueryWrapper>
}
}