Files
excalidraw/setupTests.ts
T
Mark Tolmacs f9bc601b61 fix: Circular deps #0
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-11-17 14:42:57 +01:00

184 lines
5.1 KiB
TypeScript

import fs from "fs";
// vitest.setup.ts
import "vitest-canvas-mock";
import "@testing-library/jest-dom";
import { configure } from "@testing-library/react";
import { diffStringsUnified } from "jest-diff";
import { vi } from "vitest";
import polyfill from "./packages/excalidraw/polyfill";
import { mockThrottleRAF } from "./packages/excalidraw/tests/helpers/mocks";
import { yellow } from "./packages/excalidraw/tests/helpers/colorize";
import {
PolyfillLocalStorage,
testPolyfills,
} from "./packages/excalidraw/tests/helpers/polyfills";
Object.assign(globalThis, testPolyfills);
PolyfillLocalStorage();
// typed in packages/excalidraw/global.d.ts
expect.extend({
toCloselyEqualPoints(received, expected, precision) {
if (!Array.isArray(received) || !Array.isArray(expected)) {
throw new Error("expected and received are not point arrays");
}
const COMPARE = 1 / precision === 0 ? 1 : Math.pow(10, precision ?? 2);
const pass = expected.every(
(point, idx) =>
Math.abs(received[idx][0] - point[0]) < COMPARE &&
Math.abs(received[idx][1] - point[1]) < COMPARE,
);
if (!pass) {
return {
message: () => ` The provided array of points are not close enough.
${diffStringsUnified(
JSON.stringify(expected, undefined, 2),
JSON.stringify(received, undefined, 2),
)}`,
pass: false,
};
}
return {
message: () => `expected ${received} to not be close to ${expected}`,
pass: true,
};
},
});
// By default testing-library dumps the entire serialized DOM into the error
// message whenever a `waitFor`/`getBy*` fails, which floods the test output
// (often hundreds of lines of HTML per failure). Strip it out unless
// VITE_DEBUG_DOM is enabled (see .env.test), e.g. `VITE_DEBUG_DOM=true pnpm test`.
const debugDom = ["true", "1"].includes(process.env.VITE_DEBUG_DOM ?? "");
if (!debugDom) {
configure({
getElementError: (message) => {
const error = new Error(message ?? undefined);
error.name = "TestingLibraryElementError";
return error;
},
});
}
vi.mock("@excalidraw/common", async (importOriginal) => {
const module = await importOriginal<typeof import("@excalidraw/common")>();
return {
...module,
throttleRAF: mockThrottleRAF,
};
});
// mock for pep.js not working with setPointerCapture()
HTMLElement.prototype.setPointerCapture = vi.fn();
require("fake-indexeddb/auto");
polyfill();
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(),
})),
});
Object.defineProperty(window, "FontFace", {
enumerable: true,
value: class {
private family: string;
private source: string;
private descriptors: any;
private status: string;
private unicodeRange: string;
constructor(family, source, descriptors) {
this.family = family;
this.source = source;
this.descriptors = descriptors;
this.status = "unloaded";
this.unicodeRange = "U+0000-00FF";
}
load() {
this.status = "loaded";
}
},
});
Object.defineProperty(document, "fonts", {
value: {
load: vi.fn().mockResolvedValue([]),
check: vi.fn().mockResolvedValue(true),
has: vi.fn().mockResolvedValue(true),
add: vi.fn(),
},
});
Object.defineProperty(window, "EXCALIDRAW_ASSET_PATH", {
value: `file://${__dirname}/`,
});
// mock the font fetch only, so that everything else, as font subsetting, can run inside of the (snapshot) tests
vi.mock(
"./packages/excalidraw/fonts/ExcalidrawFontFace",
async (importOriginal) => {
const mod = await importOriginal<
typeof import("./packages/excalidraw/fonts/ExcalidrawFontFace")
>();
const ExcalidrawFontFaceImpl = mod.ExcalidrawFontFace;
return {
...mod,
ExcalidrawFontFace: class extends ExcalidrawFontFaceImpl {
public async fetchFont(url: URL): Promise<ArrayBuffer> {
if (!url.toString().startsWith("file://")) {
return super.fetchFont(url);
}
// read local assets directly, without running a server
const content = await fs.promises.readFile(url);
return content.buffer;
}
},
};
},
);
// ReactDOM is located inside index.tsx file
// as a result, we need a place for it to render into
const element = document.createElement("div");
element.id = "root";
document.body.appendChild(element);
const _consoleError = console.error.bind(console);
console.error = (...args) => {
// the react's act() warning usually doesn't contain any useful stack trace
// so we're catching the log and re-logging the message with the test name,
// also stripping the actual component stack trace as it's not useful
if (args[0]?.includes?.("act(")) {
_consoleError(
yellow(
`<<< WARNING: test "${
expect.getState().currentTestName
}" does not wrap some state update in act() >>>`,
),
);
} else {
_consoleError(...args);
}
};