diff --git a/src/shared/lib/helpers/__mocks__/canvas.ts b/src/shared/lib/helpers/__mocks__/canvas.ts new file mode 100644 index 0000000..326de30 --- /dev/null +++ b/src/shared/lib/helpers/__mocks__/canvas.ts @@ -0,0 +1,29 @@ +// src/shared/lib/helpers/__mocks__/canvas.ts +// +// Call installCanvasMock(fn) before any pretext import to control measureText. +// The factory receives the current ctx.font string and the text to measure. +import { vi } from 'vitest'; + +export type MeasureFactory = (font: string, text: string) => number; + +export function installCanvasMock(factory: MeasureFactory): void { + let currentFont = ''; + + const mockCtx = { + get font() { + return currentFont; + }, + set font(f: string) { + currentFont = f; + }, + measureText: vi.fn((text: string) => ({ width: factory(currentFont, text) })), + }; + + // HTMLCanvasElement.prototype.getContext is the entry point pretext uses in DOM environments. + // OffscreenCanvas takes priority in pretext; jsdom does not define it so DOM path is used. + Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', { + configurable: true, + writable: true, + value: vi.fn(() => mockCtx), + }); +}