= {}) {
+ // 1. Create mock handlers
+ const mockHandler = jest.fn();
+ const mockErrorHandler = jest.fn();
+
+ // 2. Setup userEvent instance
+ const user = userEvent.setup();
+
+ // 3. Provide default props with overrides
+ const defaultProps: Props = {
+ title: 'Default Title',
+ isEnabled: true,
+ onAction: mockHandler,
+ onError: mockErrorHandler,
+ ...props, // Allow test-specific overrides
+ };
+
+ // 4. Render component with providers if needed
+ render(
+
+
+
+ );
+
+ // 5. Return commonly used test utilities
+ return {
+ user,
+ mockHandler,
+ mockErrorHandler,
+ // Return screen for convenience
+ screen,
+ };
+}
+```
+
+**Usage Examples:**
+```typescript
+describe(ComponentName.name, () => {
+ it('should render with default props', () => {
+ setup(); // Uses all defaults
+
+ expect(screen.getByText('Default Title')).toBeInTheDocument();
+ });
+
+ it('should render with custom props', () => {
+ setup({ title: 'Custom Title', isEnabled: false });
+
+ expect(screen.getByText('Custom Title')).toBeInTheDocument();
+ expect(screen.getByRole('button')).toBeDisabled();
+ });
+
+ it('should handle user interactions', async () => {
+ const { user, mockHandler } = setup();
+
+ await user.click(screen.getByRole('button'));
+
+ expect(mockHandler).toHaveBeenCalledTimes(1);
+ });
+});
+```
+
+### 5. Test Utilities
+- Use custom test utilities from `@/test-utils/rtl`
+- Create setup functions for complex test scenarios
+- Use fixtures for test data
+- Mock external dependencies appropriately
+
+### 6. Test Coverage
+- Test user interactions, not implementation details
+- Test error states and edge cases
+- Use descriptive test names
+- Group related tests with `describe` blocks
+
+### 7. Component Mocking
+Mock child components in unit tests to isolate the parent component's behavior and allow for flexible testing of sub-behaviors in forks:
+
+```typescript
+import React from 'react';
+import { render, screen } from '@/test-utils/rtl';
+
+// Mock child components
+jest.mock('../child-component', () => {
+ return function MockChildComponent({ onAction, data }: any) {
+ return (
+
+
+
+ );
+ };
+});
+
+import ParentComponent from '../parent-component';
+
+describe(ParentComponent.name, () => {
+ it('should handle child component interactions', () => {
+ const mockHandler = jest.fn();
+ render();
+
+ // Test parent component behavior without depending on child implementation
+ expect(screen.getByTestId('mock-child-component')).toBeInTheDocument();
+ });
+});
+```
+
+**Benefits of Component Mocking:**
+- **Isolation**: Test parent component logic independently of child component implementation
+- **Flexibility**: Allow forks to modify child component behavior without breaking parent tests
+- **Performance**: Faster test execution by avoiding complex child component rendering
+- **Maintainability**: Reduce test brittleness when child components change
+- **Focus**: Concentrate on testing the specific behavior of the component under test
+
+## Utility Patterns
+
+### 1. Utility Function Structure
+```typescript
+/**
+ * Brief description of what the function does.
+ *
+ * @param param1 - Description of parameter
+ * @param param2 - Description of parameter
+ * @returns Description of return value
+ */
+export default function utilityFunction(
+ param1: string,
+ param2: T
+): ReturnType {
+ // Implementation with proper error handling
+ try {
+ // Logic here
+ return result;
+ } catch (error) {
+ logger.warn({ param1, param2, error }, 'Utility function failed');
+ return defaultValue;
+ }
+}
+```
+
+### 2. Error Handling in Utilities
+- Use structured logging with context
+- Return sensible defaults when possible
+- Don't throw errors unless absolutely necessary
+- Use TypeScript for type safety
+
+### 3. Generic Utilities
+```typescript
+// Use generics for reusable utilities
+export default function processArray(
+ array: T[],
+ processor: (item: T) => R
+): R[] {
+ return array.map(processor);
+}
+```
+
+## Hook Patterns
+
+### 1. Custom Hook Structure
+```typescript
+import { useCallback, useState, useMemo } from 'react';
+import { type Props, type ReturnType } from './hook-name.types';
+
+export default function useHookName({
+ initialValue,
+ options,
+}: Props): ReturnType {
+ const [state, setState] = useState(initialValue);
+
+ const computedValue = useMemo(() => {
+ // Expensive computation
+ return processState(state);
+ }, [state]);
+
+ const handler = useCallback((newValue: T) => {
+ setState(newValue);
+ }, []);
+
+ return {
+ state,
+ computedValue,
+ handler,
+ };
+}
+```
+
+### 2. Hook Types
+```typescript
+export type Props = {
+ initialValue: T;
+ options?: HookOptions;
+};
+
+export type ReturnType = {
+ state: T;
+ computedValue: ProcessedValue;
+ handler: (value: T) => void;
+};
+```
+
+### 3. Hook Best Practices
+- Use TypeScript generics for reusable hooks
+- Memoize expensive computations
+- Use `useCallback` for event handlers
+- Return objects for multiple values
+- Provide clear prop and return types
+
+## Error Handling
+
+### 1. Error Boundaries
+```typescript
+import { ErrorBoundary } from 'react-error-boundary';
+
+export default function ErrorBoundaryWrapper({ children }: Props) {
+ return (
+ {
+ logger.error({ error, errorInfo }, 'Component error boundary triggered');
+ }}
+ >
+ {children}
+
+ );
+}
+```
+
+### 2. Structured Logging
+```typescript
+// Use structured logging with context
+logger.error(
+ { requestParams, error, userId },
+ 'Descriptive error message'
+);
+```
+
+### 3. Error Types
+```typescript
+// Define specific error types
+export class ValidationError extends Error {
+ constructor(message: string, public validationErrors: ValidationError[]) {
+ super(message);
+ this.name = 'ValidationError';
+ }
+}
+```
+
+## Performance Considerations
+
+### 1. Code Splitting
+- Use dynamic imports for large components
+- Implement route-based code splitting
+- Lazy load non-critical features
+
+### 2. Memoization
+```typescript
+// Use React.memo for expensive components
+export default React.memo(function ExpensiveComponent({ data }: Props) {
+ // Component implementation
+});
+
+// Use useMemo for expensive calculations
+const processedData = useMemo(() => {
+ return expensiveCalculation(data);
+}, [data]);
+```
+
+### 3. Virtualization
+- Use `react-virtuoso` for large lists
+- Implement virtual scrolling for tables
+- Consider pagination for large datasets
+
+### 4. Bundle Optimization
+- Use tree shaking effectively
+- Minimize bundle size with proper imports
+- Use dynamic imports for optional features
+
+## Best Practices Summary
+
+1. **Consistency**: Follow established patterns throughout the codebase
+2. **Type Safety**: Use TypeScript effectively with proper types and generics
+3. **Error Handling**: Implement comprehensive error handling and logging
+4. **Testing**: Write meaningful tests that focus on user behavior
+5. **Performance**: Consider performance implications of all changes
+6. **Documentation**: Document complex logic and architectural decisions
+7. **Accessibility**: Ensure components are accessible and follow WCAG guidelines
+8. **Security**: Validate all inputs and handle sensitive data appropriately
+
+## Common Pitfalls to Avoid
+
+1. **Don't** bypass TypeScript types with `any`
+2. **Don't** create components without proper error boundaries
+3. **Don't** ignore performance implications of re-renders
+4. **Don't** hardcode values that should come from configuration
+5. **Don't** skip validation for user inputs
+6. **Don't** forget to handle loading and error states
+7. **Don't** create overly complex components - split them up
+8. **Don't** ignore accessibility requirements
+
+This document should be updated as new patterns emerge and existing patterns evolve. Always refer to the existing codebase for the most current examples of these patterns in practice.