All files / test setup.ts

45.45% Statements 70/154
58.82% Branches 40/68
58.33% Functions 14/24
47.18% Lines 67/142

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          449x   449x     449x     449x         15526x     15526x         15526x 15526x       15526x                         449x                       788x 788x 788x 788x 788x 788x 788x 788x   788x     788x 197x   788x             788x 788x 788x     788x   1180x 1180x     1180x     1180x         590x 590x 590x                 788x               449x 449x                                                             449x                                                                                                     449x                                         449x 449x     449x 449x     449x                               2220x 2220x 2220x           449x 449x     449x 449x   449x 29954x 29954x                             449x 188x 188x             449x 103x 103x           26x   77x     449x 29877x 29766x   111x         449x   11741x    
// Test setup for Black Trigram Korean martial arts game
 
import * as matchers from "@testing-library/jest-dom/matchers";
import { afterEach, beforeAll, expect, vi } from "vitest";
 
expect.extend(matchers);
 
beforeAll(() => {
  // Intercept stderr to suppress jsdom HTMLCanvasElement warnings
  // jsdom writes these warnings directly to stderr, bypassing console mocks
  const originalStderrWrite = process.stderr.write.bind(process.stderr);
  
  // Override with proper type-safe signature matching Node's write() overloads
  process.stderr.write = ((
    chunk: string | Uint8Array,
    encodingOrCallback?: BufferEncoding | ((err?: Error | null) => void),
    callback?: (err?: Error | null) => void
  ): boolean => {
    const message = typeof chunk === "string" ? chunk : chunk.toString();
    
    // Suppress HTMLCanvasElement warnings from jsdom
    Eif (
      message.includes("Not implemented: HTMLCanvasElement") ||
      message.includes("without installing the canvas npm package")
    ) {
      // Call callback if provided to avoid breaking the stream
      if (typeof encodingOrCallback === "function") {
        encodingOrCallback();
      E} else if (typeof callback === "function") {
        callback();
      }
      return true;
    }
    
    // Pass through all other messages with proper type handling
    if (typeof encodingOrCallback === "function") {
      return originalStderrWrite(chunk, encodingOrCallback);
    }
    return originalStderrWrite(chunk, encodingOrCallback, callback);
  }) as typeof process.stderr.write;
 
  // Mock APP_VERSION for tests
  // APP_VERSION is declared as a const in vite-env.d.ts but we need to set it in test environment
  // Using type assertion is necessary here to override the const declaration
  (globalThis as unknown as { APP_VERSION: string }).APP_VERSION = "0.5.3";
 
  // Enhanced Audio mock with proper HTMLAudioElement that matches test expectations
  // Vitest 4.0 requires proper function/class constructors, not arrow functions
  // This mock simulates proper audio loading events for AudioAssetLoader tests
  class MockHTMLAudioElement {
    canPlayType: ReturnType<typeof vi.fn>;
    play: ReturnType<typeof vi.fn>;
    pause: ReturnType<typeof vi.fn>;
    load: ReturnType<typeof vi.fn>;
    addEventListener: ReturnType<typeof vi.fn>;
    removeEventListener: ReturnType<typeof vi.fn>;
    volume = 1;
    currentTime = 0;
    duration = 100;
    paused = false;
    ended = false;
    src = "";
    crossOrigin = null;
    preload = "auto";
    private eventListeners: Map<string, Set<EventListenerOrEventListenerObject>> =
      new Map();
 
    constructor(src?: string) {
      if (src) {
        this.src = src;
      }
      this.canPlayType = vi.fn((type: string) => {
        // Return "probably" for mp3 to match test expectations
        if (type === "audio/mp3" || type === "audio/mpeg") return "probably";
        if (type === "audio/wav") return "maybe";
        if (type === "audio/ogg") return "maybe";
        return ""; // Empty string means not supported (webm)
      });
      this.play = vi.fn(() => Promise.resolve());
      this.pause = vi.fn();
      this.load = vi.fn();
 
      // Track event listeners and trigger load events automatically
      this.addEventListener = vi.fn(
        (event: string, handler: EventListenerOrEventListenerObject) => {
          Eif (!this.eventListeners.has(event)) {
            this.eventListeners.set(event, new Set());
          }
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- set created above
          this.eventListeners.get(event)!.add(handler);
 
          // Automatically trigger canplaythrough event after a microtask
          if (
            event === "canplaythrough" ||
            event === "loadeddata" ||
            event === "load"
          ) {
            queueMicrotask(() => {
              if (typeof handler === "function") {
                handler(new Event(event));
              E} else if (handler && typeof handler === "object") {
                handler.handleEvent(new Event(event));
              }
            });
          }
        }
      );
 
      this.removeEventListener = vi.fn(
        (event: string, handler: EventListenerOrEventListenerObject) => {
          this.eventListeners.get(event)?.delete(handler);
        }
      );
    }
  }
 
  global.HTMLAudioElement = MockHTMLAudioElement as unknown as typeof HTMLAudioElement;
  global.Audio = MockHTMLAudioElement as unknown as typeof Audio;
 
  class MockHTMLCanvasElement {
    width = 800;
    height = 600;
    style: Record<string, string | number> = {};
    addEventListener: ReturnType<typeof vi.fn>;
    removeEventListener: ReturnType<typeof vi.fn>;
    getContext: ReturnType<typeof vi.fn>;
 
    constructor() {
      this.addEventListener = vi.fn();
      this.removeEventListener = vi.fn();
      this.getContext = vi.fn(() => ({
        fillRect: vi.fn(),
        clearRect: vi.fn(),
        canvas: { width: 800, height: 600 },
      }));
    }
  }
 
  // Mock Canvas API
  class MockCanvasRenderingContext2D {
    fillRect = vi.fn();
    clearRect = vi.fn();
    beginPath = vi.fn();
    arc = vi.fn();
    fill = vi.fn();
    stroke = vi.fn();
  }
 
  global.CanvasRenderingContext2D = MockCanvasRenderingContext2D as unknown as typeof CanvasRenderingContext2D;
 
  // Mock WebGL context for Three.js
  class MockWebGLRenderingContext {
    getExtension = vi.fn();
    getParameter = vi.fn();
    createShader = vi.fn();
    createProgram = vi.fn();
    attachShader = vi.fn();
    linkProgram = vi.fn();
    getProgramParameter = vi.fn(() => true);
    useProgram = vi.fn();
    createBuffer = vi.fn();
    bindBuffer = vi.fn();
    bufferData = vi.fn();
    enableVertexAttribArray = vi.fn();
    vertexAttribPointer = vi.fn();
    drawArrays = vi.fn();
    clear = vi.fn();
    clearColor = vi.fn();
    enable = vi.fn();
    disable = vi.fn();
    depthFunc = vi.fn();
    viewport = vi.fn();
    getAttribLocation = vi.fn(() => 0);
    getUniformLocation = vi.fn(() => ({}));
    uniformMatrix4fv = vi.fn();
    uniform1i = vi.fn();
    createTexture = vi.fn();
    bindTexture = vi.fn();
    texImage2D = vi.fn();
    texParameteri = vi.fn();
    ARRAY_BUFFER = 0x8892;
    STATIC_DRAW = 0x88e4;
    FLOAT = 0x1406;
    TRIANGLES = 0x0004;
    COLOR_BUFFER_BIT = 0x00004000;
    DEPTH_BUFFER_BIT = 0x00000100;
    DEPTH_TEST = 0x0b71;
    LEQUAL = 0x0203;
    TEXTURE_2D = 0x0de1;
    RGBA = 0x1908;
    UNSIGNED_BYTE = 0x1401;
    TEXTURE_WRAP_S = 0x2802;
    TEXTURE_WRAP_T = 0x2803;
    TEXTURE_MIN_FILTER = 0x2801;
    TEXTURE_MAG_FILTER = 0x2800;
    CLAMP_TO_EDGE = 0x812f;
    LINEAR = 0x2601;
  }
 
  global.WebGLRenderingContext = MockWebGLRenderingContext as unknown as typeof WebGLRenderingContext;
 
  // Update HTMLCanvasElement getContext to support WebGL
  class EnhancedMockHTMLCanvasElement extends MockHTMLCanvasElement {
    getContext: ReturnType<typeof vi.fn>;
 
    constructor() {
      super();
      this.getContext = vi.fn((contextType: string) => {
        if (contextType === "webgl" || contextType === "webgl2") {
          return new MockWebGLRenderingContext();
        }
        return {
          fillRect: vi.fn(),
          clearRect: vi.fn(),
          canvas: { width: 800, height: 600 },
        };
      });
    }
  }
 
  global.HTMLCanvasElement = EnhancedMockHTMLCanvasElement as unknown as typeof HTMLCanvasElement;
  (window as unknown as { HTMLCanvasElement: typeof HTMLCanvasElement }).HTMLCanvasElement = EnhancedMockHTMLCanvasElement as unknown as typeof HTMLCanvasElement;
 
  // Mock requestAnimationFrame
  global.requestAnimationFrame = vi.fn((cb) => window.setTimeout(cb, 16));
  global.cancelAnimationFrame = vi.fn((id) => clearTimeout(id));
 
  // Mock window.matchMedia
  Object.defineProperty(window, "matchMedia", {
    writable: true,
    value: vi.fn().mockImplementation((query) => ({
      matches: false,
      media: query,
      onchange: null,
      addListener: vi.fn(), // deprecated
      removeListener: vi.fn(), // deprecated
      addEventListener: vi.fn(),
      removeEventListener: vi.fn(),
      dispatchEvent: vi.fn(),
    })),
  });
 
  // Mock ResizeObserver (needs to be on window for react-use-measure)
  class MockResizeObserver {
    observe = vi.fn();
    unobserve = vi.fn();
    disconnect = vi.fn();
    constructor(_callback: ResizeObserverCallback) {
      // Store callback for potential testing (prefixed with _ to indicate unused)
    }
  }
 
  global.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
  (window as unknown as { ResizeObserver: typeof ResizeObserver }).ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
 
  // Console warning suppression for cleaner test output
  const originalWarn = console.warn;
  const originalError = console.error;
 
  const suppressReactThreeMessage = (input: unknown): boolean => {
    Iif (typeof input !== "string") return false;
    return (
      input.includes("is using incorrect casing") ||
      input.includes("The tag <") ||
      input.includes("is unrecognized in this browser") ||
      input.includes("React does not recognize the `") ||
      input.includes("Received `true` for a non-boolean attribute") ||
      input.includes("sizeAttenuation") ||
      input.includes("itemSize") ||
      input.includes("shadow-mapSize") ||
      input.includes("polygonOffset") ||
      input.includes("wireframe") ||
      input.includes("transparent")
    );
  };
 
  const suppressJsdomCanvasMessage = (input: unknown): boolean => {
    Iif (typeof input !== "string") return false;
    return (
      input.includes("Not implemented: HTMLCanvasElement") ||
      input.includes("HTMLCanvasElement's getContext() method") ||
      input.includes("without installing the canvas npm package")
    );
  };
 
  console.warn = (...args) => {
    const message = args[0];
    if (
      (typeof message === "string" &&
        (message.includes("WebGL") || message.includes("AudioContext"))) ||
      suppressReactThreeMessage(message) ||
      suppressJsdomCanvasMessage(message)
    ) {
      return;
    }
    originalWarn(...args);
  };
 
  console.error = (...args) => {
    if (suppressReactThreeMessage(args[0]) || suppressJsdomCanvasMessage(args[0])) {
      return;
    }
    originalError(...args);
  };
});
 
// Cleanup after each test case
afterEach(() => {
  // Clean up any test-specific mocks
  vi.clearAllMocks();
});