All files / src/test-utils a11y.tsx

0% Statements 0/200
100% Branches 0/0
0% Functions 0/1
0% Lines 0/200

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                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Accessibility (A11y) Testing Utilities
 *
 * Provides helpers for testing WCAG 2.1 AA compliance using jest-axe.
 * Use these utilities in component tests to catch accessibility issues.
 */

import { configureAxe, toHaveNoViolations } from 'jest-axe';
import { render, RenderResult } from '@testing-library/react';
import { ReactElement } from 'react';

// Extend Jest matchers with accessibility matchers
expect.extend(toHaveNoViolations);

/**
 * Configured axe instance with WCAG 2.1 AA rules
 */
export const axe = configureAxe({
  rules: {
    // Critical accessibility rules
    region: { enabled: true },
    'color-contrast': { enabled: true },
    'label': { enabled: true },
    'button-name': { enabled: true },
    'link-name': { enabled: true },
    'image-alt': { enabled: true },
    'html-has-lang': { enabled: true },
    'landmark-one-main': { enabled: true },
    'page-has-heading-one': { enabled: true },
    // Focus management
    'focus-order-semantics': { enabled: true },
    'tabindex': { enabled: true },
    // ARIA rules
    'aria-allowed-attr': { enabled: true },
    'aria-hidden-focus': { enabled: true },
    'aria-required-attr': { enabled: true },
    'aria-required-children': { enabled: true },
    'aria-required-parent': { enabled: true },
    'aria-roles': { enabled: true },
    'aria-valid-attr-value': { enabled: true },
    'aria-valid-attr': { enabled: true }
  }
});

/**
 * Result of an accessibility check
 */
export interface A11yCheckResult {
  /** Whether any violations were found */
  passed: boolean;
  /** Array of violations found */
  violations: A11yViolation[];
  /** Summary message */
  summary: string;
}

/**
 * Individual accessibility violation
 */
export interface A11yViolation {
  /** Unique identifier for the rule */
  id: string;
  /** Impact level */
  impact: 'minor' | 'moderate' | 'serious' | 'critical';
  /** Description of the issue */
  description: string;
  /** Help text for fixing the issue */
  help: string;
  /** URL to more information */
  helpUrl: string;
  /** HTML elements affected */
  nodes: string[];
}

/**
 * Check a rendered component for accessibility violations.
 *
 * @param ui - React element to test
 * @returns Promise that resolves with the axe results
 *
 * @example
 * ```tsx
 * import { checkA11y } from '@/test-utils/a11y';
 * import { Button } from '@/components/ui/Button';
 *
 * describe('Button Accessibility', () => {
 *   it('has no accessibility violations', async () => {
 *     await checkA11y(<Button>Click me</Button>);
 *   });
 * });
 * ```
 */
export async function checkA11y(ui: ReactElement): Promise<void> {
  const { container } = render(ui);
  const results = await axe(container);
  expect(results).toHaveNoViolations();
}

/**
 * Check a rendered component and return detailed results.
 * Use this when you need more control over handling violations.
 *
 * @param ui - React element to test
 * @returns Promise with detailed accessibility check results
 *
 * @example
 * ```tsx
 * import { checkA11yWithDetails } from '@/test-utils/a11y';
 * import { ProductCard } from '@/components/features/shop/ProductCard';
 *
 * describe('ProductCard Accessibility', () => {
 *   it('reports accessibility issues', async () => {
 *     const results = await checkA11yWithDetails(<ProductCard product={mockProduct} />);
 *     if (!results.passed) {
 *       console.log('Violations:', results.violations);
 *     }
 *     expect(results.passed).toBe(true);
 *   });
 * });
 * ```
 */
export async function checkA11yWithDetails(ui: ReactElement): Promise<A11yCheckResult> {
  const { container } = render(ui);
  const results = await axe(container);

  const violations: A11yViolation[] = results.violations.map((violation) => ({
    id: violation.id,
    impact: violation.impact as A11yViolation['impact'],
    description: violation.description,
    help: violation.help,
    helpUrl: violation.helpUrl,
    nodes: violation.nodes.map((node) => node.html)
  }));

  return {
    passed: violations.length === 0,
    violations,
    summary:
      violations.length === 0
        ? 'No accessibility violations found'
        : `Found ${violations.length} accessibility violation(s)`
  };
}

/**
 * Check an already rendered component for accessibility violations.
 * Use when you have custom render logic.
 *
 * @param renderResult - Result from render()
 * @returns Promise that resolves with the axe results
 *
 * @example
 * ```tsx
 * import { checkA11yContainer } from '@/test-utils/a11y';
 * import { render } from '@testing-library/react';
 *
 * describe('Complex Component', () => {
 *   it('has no violations with custom wrapper', async () => {
 *     const result = render(<MyComponent />, { wrapper: CustomProvider });
 *     await checkA11yContainer(result);
 *   });
 * });
 * ```
 */
export async function checkA11yContainer(renderResult: RenderResult): Promise<void> {
  const results = await axe(renderResult.container);
  expect(results).toHaveNoViolations();
}

/**
 * Create a wrapper component that provides common context providers
 * needed for accessibility testing.
 *
 * @example
 * ```tsx
 * import { createA11yWrapper } from '@/test-utils/a11y';
 * import { LiveRegionProvider } from '@/components/ui/LiveRegion';
 *
 * const wrapper = createA11yWrapper([LiveRegionProvider, ThemeProvider]);
 *
 * describe('Component with providers', () => {
 *   it('renders accessibly', async () => {
 *     const { container } = render(<MyComponent />, { wrapper });
 *     await checkA11yContainer({ container } as RenderResult);
 *   });
 * });
 * ```
 */
export function createA11yWrapper(
  providers: React.ComponentType<{ children: React.ReactNode }>[]
): React.ComponentType<{ children: React.ReactNode }> {
  return function A11yWrapper({ children }: { children: React.ReactNode }) {
    return providers.reduceRight((acc, Provider) => {
      return <Provider>{acc}</Provider>;
    }, children);
  };
}

// Re-export for convenience
export { toHaveNoViolations };