All files / src/tests/testUtils chartTestUtils.ts

83.33% Statements 35/42
50% Branches 3/6
63.15% Functions 12/19
83.33% Lines 35/42

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                                    3x               3x         3x 3x           3x           3x     1x 1x                                         3x             3x         3x           1x 1x                       1x 1x         1x             1x 1x 1x 1x     1x 1x 1x       1x                           1x   2x 2x   1x 1x                   2x                   2x     5x 5x                         2x 1x      
import { render } from "@testing-library/react";
import { vi } from "vitest";
 
// Define a proper type for the Chart mock constructor
type ChartMockConstructor = ReturnType<typeof vi.fn> & {
  register: ReturnType<typeof vi.fn>;
  defaults: {
    font: { family: string };
    plugins: { legend: { display: boolean } };
  };
};
 
/**
 * Setup function for Chart.js tests to standardize mocking
 * @returns utilities for testing Chart.js components
 */
export function setupChartTest() {
  // Create a mock Chart instance
  const mockChartInstance = {
    destroy: vi.fn(),
    update: vi.fn(),
    resize: vi.fn(),
    data: { datasets: [] },
  };
 
  // Create a constructor mock with proper type
  const mockConstructor = vi.fn(
    () => mockChartInstance
  ) as ChartMockConstructor;
 
  // Add static methods/properties that Chart has
  mockConstructor.register = vi.fn();
  mockConstructor.defaults = {
    font: { family: "Arial" },
    plugins: { legend: { display: false } },
  };
 
  // Create the chart mock module
  const chartMock = {
    __esModule: true,
    default: mockConstructor,
  };
 
  // Mock canvas context
  HTMLCanvasElement.prototype.getContext = vi
    .fn()
    .mockImplementation((contextId) => {
      Eif (contextId === "2d") {
        return {
          canvas: { width: 200, height: 200 },
          clearRect: vi.fn(),
          fill: vi.fn(),
          beginPath: vi.fn(),
          stroke: vi.fn(),
          moveTo: vi.fn(),
          lineTo: vi.fn(),
          arc: vi.fn(),
          fillText: vi.fn(),
          measureText: vi.fn().mockReturnValue({ width: 10 }),
          save: vi.fn(),
          restore: vi.fn(),
          translate: vi.fn(),
          rotate: vi.fn(),
        } as unknown as CanvasRenderingContext2D;
      }
      return null;
    });
 
  // Mock browser APIs
  globalThis.ResizeObserver = class ResizeObserver {
    constructor(_callback: ResizeObserverCallback) {}
    observe() {}
    unobserve() {}
    disconnect() {}
  };
 
  globalThis.requestAnimationFrame = vi.fn().mockImplementation((cb) => {
    cb(0);
    return 0;
  });
 
  return {
    mockChartInstance,
    mockConstructor,
    chartMock,
    renderChart: (component: React.ReactElement) => render(component),
    cleanupMocks: () => {
      vi.clearAllMocks();
      vi.resetAllMocks();
    },
  };
}
 
/**
 * Creates a properly typed mock for Chart.js that can be used in tests
 *
 * @returns An object containing the mocked Chart class and data collectors
 */
export function createChartMock() {
  // Variables to store chart data for assertions in tests
  let mockChartData: any = null;
  let mockChartOptions: any = null;
 
  // Create a properly typed mock Chart class
  class MockChart {
    // Define static register method with correct TypeScript typing
    static register = vi.fn();
 
    data: any;
    options: any;
 
    constructor(ctx: any, config: any) {
      // Store chart data and options for test assertions
      mockChartData = config.data;
      mockChartOptions = config.options;
      this.data = config.data;
      this.options = config.options;
    }
 
    destroy = vi.fn();
    update = vi.fn();
    resize = vi.fn();
  }
 
  // Create the mock module
  const chartModule = {
    Chart: MockChart,
    register: vi.fn(),
    RadarController: {},
    ArcElement: {},
    RadialLinearScale: {},
    PointElement: {},
    LineElement: {},
    Tooltip: {},
    Legend: {},
    // Add other Chart.js components as needed
  };
 
  // Return both the mock module and data collectors
  return {
    chartModule,
    getMockData: () => mockChartData,
    getMockOptions: () => mockChartOptions,
    resetMockData: () => {
      mockChartData = null;
      mockChartOptions = null;
    },
  };
}
 
/**
 * Setup function to mock browser APIs required by Chart.js
 */
export function setupChartEnvironment() {
  // Mock ResizeObserver
  window.ResizeObserver =
    window.ResizeObserver ||
    vi.fn().mockImplementation(() => ({
      observe: vi.fn(),
      unobserve: vi.fn(),
      disconnect: vi.fn(),
    }));
 
  // Mock canvas context if needed
  // Use proper type assertion to fix TypeScript error
  HTMLCanvasElement.prototype.getContext = vi
    .fn()
    .mockImplementation((contextId) => {
      Eif (contextId === "2d") {
        return {
          // Add canvas context methods as needed
          clearRect: vi.fn(),
          beginPath: vi.fn(),
          arc: vi.fn(),
          fill: vi.fn(),
          // Add more methods as tests require them
        } as unknown as CanvasRenderingContext2D;
      }
      return null;
    });
 
  // Return cleanup function
  return () => {
    vi.restoreAllMocks();
  };
}