From fcde78abad77db1e0cf95f32bb242feaa01bdb70 Mon Sep 17 00:00:00 2001 From: Ilia Mashkov Date: Sat, 11 Apr 2026 15:48:47 +0300 Subject: [PATCH] test: add canvas mock helper for pretext-based engine tests --- src/shared/lib/helpers/__mocks__/canvas.ts | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/shared/lib/helpers/__mocks__/canvas.ts 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), + }); +}