test: add canvas mock helper for pretext-based engine tests
This commit is contained in:
29
src/shared/lib/helpers/__mocks__/canvas.ts
Normal file
29
src/shared/lib/helpers/__mocks__/canvas.ts
Normal file
@@ -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),
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user