All files / src/test-utils snapshot-utils.tsx

73.58% Statements 39/53
60.6% Branches 20/33
71.42% Functions 10/14
72.54% Lines 37/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316              30x                             30x                                                                 2x   2x   16x     16x   16x         16x 16x                 16x         16x         16x 16x 16x           16x                                 53x   53x   606x     606x   606x         606x 606x                 606x 121x       606x         606x 606x 606x                 30x                                                                   30x                                             30x                                             14x                         12x                 30x                                                             30x                 30x         30x                  
import type { ComponentType, ReactElement, ReactNode } from 'react';
import { createElement, isValidElement } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderWithoutRouter, renderWithRouter } from '@/test-utils';
import { ThemeProvider } from '@/components/theme-provider';
 
// Create a test query client for React Query
const createTestQueryClient = () => {
  return new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
        gcTime: 0,
      },
      mutations: {
        retry: false,
      },
    },
  });
};
 
// Mock environment variables
Object.defineProperty(global, 'import', {
  value: {
    meta: {
      env: {
        // VITE_API_URL: 'http://localhost:3000/api',
        // VITE_APP_NAME: 'Test App',
      },
    },
  },
  configurable: true,
});
 
export interface SnapshotScenario<T = any> {
  name: string;
  props?: T;
  children?: ReactNode;
  wrapper?: ComponentType<{ children: ReactNode }>;
}
 
export interface SnapshotTestOptions {
  withRouter?: boolean;
  wrapper?: ComponentType<{ children: ReactNode }>;
}
 
/**
 * Test component snapshots with multiple scenarios
 */
export function testComponentSnapshots<T extends Record<string, any>>(
  componentName: string,
  Component: ComponentType<T> | ((props: T) => ReactElement),
  scenarios: SnapshotScenario<T>[],
  options: SnapshotTestOptions = {}
) {
  const { withRouter = false, wrapper } = options;
 
  scenarios.forEach(
    ({ name, props = {} as T, children, wrapper: scenarioWrapper }) => {
      it(`${componentName} - ${name}`, () => {
        let element: ReactElement;
 
        Iif (isValidElement(Component)) {
          element = Component;
        } else if (
          typeof Component === 'function' ||
          typeof Component === 'object'
        ) {
          // Handle regular components, forwardRef components, and memo components
          const propsWithChildren = children ? { ...props, children } : props;
          element = createElement(
            Component as ComponentType<T>,
            propsWithChildren
          );
        } else E{
          throw new Error('Component must be a React component or function');
        }
 
        // Apply scenario wrapper if provided
        Iif (scenarioWrapper) {
          element = createElement(scenarioWrapper, null, element);
        }
 
        // Apply global wrapper if provided
        Iif (wrapper) {
          element = createElement(wrapper, null, element);
        }
 
        let tree;
        if (withRouter) {
          const { container } = renderWithRouter(element);
          tree = container.firstChild;
        } else E{
          const { container } = renderWithoutRouter(element);
          tree = container.firstChild;
        }
 
        expect(tree).toMatchSnapshot();
      });
    }
  );
}
 
/**
 * Test component snapshots using react-test-renderer for more detailed snapshots
 */
export function testComponentSnapshotsWithRenderer<
  T extends Record<string, any>,
>(
  componentName: string,
  Component: ComponentType<T> | ((props: T) => ReactElement),
  scenarios: SnapshotScenario<T>[],
  options: SnapshotTestOptions = {}
) {
  const { wrapper } = options;
 
  scenarios.forEach(
    ({ name, props = {} as T, children, wrapper: scenarioWrapper }) => {
      it(`${componentName} - ${name}`, () => {
        let element: ReactElement;
 
        Iif (isValidElement(Component)) {
          element = Component;
        } else if (
          typeof Component === 'function' ||
          typeof Component === 'object'
        ) {
          // Handle regular components, forwardRef components, and memo components
          const propsWithChildren = children ? { ...props, children } : props;
          element = createElement(
            Component as ComponentType<T>,
            propsWithChildren
          );
        } else E{
          throw new Error('Component must be a React component or function');
        }
 
        // Apply scenario wrapper if provided
        if (scenarioWrapper) {
          element = createElement(scenarioWrapper, null, element);
        }
 
        // Apply global wrapper if provided
        Iif (wrapper) {
          element = createElement(wrapper, null, element);
        }
 
        // Use renderWithoutRouter for better DOM handling instead of react-test-renderer
        const { container } = renderWithoutRouter(element);
        const tree = container.firstChild;
        expect(tree).toMatchSnapshot();
      });
    }
  );
}
 
/**
 * Common snapshot scenarios that can be reused across components
 */
export const commonSnapshotScenarios = {
  default: {
    name: 'default props',
    props: {},
  },
  withCustomClass: {
    name: 'with custom className',
    props: { className: 'custom-test-class' },
  },
  withDataTestId: {
    name: 'with data-testid',
    props: { 'data-testid': 'component-test-id' },
  },
  withAriaLabel: {
    name: 'with aria-label',
    props: { 'aria-label': 'Component description' },
  },
  disabled: {
    name: 'disabled state',
    props: { disabled: true },
  },
  loading: {
    name: 'loading state',
    props: { 'data-loading': 'true' },
  },
  error: {
    name: 'error state',
    props: { 'data-error': 'true' },
  },
};
 
/**
 * Scenarios for form components
 */
export const formComponentScenarios = {
  ...commonSnapshotScenarios,
  required: {
    name: 'required field',
    props: { required: true },
  },
  withPlaceholder: {
    name: 'with placeholder',
    props: { placeholder: 'Enter value...' },
  },
  withValue: {
    name: 'with value',
    props: { value: 'Test value' },
  },
  invalid: {
    name: 'invalid state',
    props: { 'data-invalid': 'true' },
  },
};
 
/**
 * Scenarios for interactive components
 */
export const interactiveComponentScenarios = {
  ...commonSnapshotScenarios,
  focused: {
    name: 'focused state',
    props: { autoFocus: true },
  },
  pressed: {
    name: 'pressed state',
    props: { 'data-state': 'pressed' },
  },
  hovered: {
    name: 'hovered state',
    props: { 'data-state': 'hovered' },
  },
};
 
/**
 * Generate variant scenarios for components with variants
 */
export function createVariantScenarios<T extends string>(
  variants: readonly T[],
  baseProps: Record<string, any> = {}
): SnapshotScenario[] {
  return variants.map(variant => ({
    name: `${variant} variant`,
    props: { ...baseProps, variant },
  }));
}
 
/**
 * Generate size scenarios for components with sizes
 */
export function createSizeScenarios<T extends string>(
  sizes: readonly T[],
  baseProps: Record<string, any> = {}
): SnapshotScenario[] {
  return sizes.map(size => ({
    name: `${size} size`,
    props: { ...baseProps, size },
  }));
}
 
/**
 * Create scenarios for different content types
 */
export const contentScenarios = {
  withText: {
    name: 'with text content',
    children: 'Sample text content',
  },
  withNumber: {
    name: 'with number content',
    children: 42,
  },
  withIcon: {
    name: 'with icon content',
    children: '🔔',
  },
  withMixedContent: {
    name: 'with mixed content',
    children: ['Icon: ', '🔔', ' Text: ', 42],
  },
  withEmptyContent: {
    name: 'with empty content',
    children: '',
  },
  withLongContent: {
    name: 'with long content',
    children:
      'This is a very long text content that might wrap or be truncated depending on the component styling and layout constraints.',
  },
};
 
/**
 * Mock wrapper for components that need specific context
 */
export const MockThemeWrapper = ({ children }: { children: ReactNode }) => (
  <div data-theme="light" className="mock-theme-wrapper">
    {children}
  </div>
);
 
/**
 * Mock wrapper for components that need form context
 */
export const MockFormWrapper = ({ children }: { children: ReactNode }) => (
  <form className="mock-form-wrapper">{children}</form>
);
 
// Test wrapper that provides all necessary contexts
const TestWrapper = ({ children }: { children: ReactNode }) => {
  const queryClient = createTestQueryClient();
 
  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider>{children}</ThemeProvider>
    </QueryClientProvider>
  );
};