import { toMatchImageSnapshot } from "jest-image-snapshot"; import { expect, test } from "vitest"; import { Formation, formationToSvg } from "./formation.js"; import { svgToPng } from "./testutils.js"; expect.extend({ toMatchImageSnapshot }); function toPng(...args: Parameters) { return svgToPng(new Formation(...args).toString()); } test("toElement", () => { const formation = new Formation("1> 2>"); const svg = formation.toString(); // Simulate a bare SVGSVGElement with setAttribute and innerHTML const el = { attrs: {} as Record, innerHTML: "" } as unknown as SVGSVGElement; Object.defineProperty(el, "setAttribute", { value(name: string, value: string) { (el as any).attrs[name] = value; }, }); formation.toElement(el); // Should set the viewBox and inject inner content expect((el as any).attrs.viewBox).toBeDefined(); expect(el.innerHTML).toBeTruthy(); // innerHTML and viewBox should be non-empty; IDs may differ across renders // so we check structural equivalence by stripping mask IDs const stripIds = (s: string) => s.replace(/\bm\d+/g, "m#"); expect(stripIds(svg)).toContain(stripIds(el.innerHTML)); expect(svg).toContain((el as any).attrs.viewBox); }); test("render", async () => { expect(await toPng("1> 2> . . / . . 6< 5<")).toMatchImageSnapshot({ customSnapshotIdentifier: "sample1", }); expect( await toPng("e.e/nsns/w.w", { body: { fillOpacity: 0.2 }, nose: { size: `*2` }, }), ).toMatchImageSnapshot({ customSnapshotIdentifier: "sample2" }); expect( await toPng( [ { x: 0, y: 0, direction: "north", label: "A", color: "blue" }, { x: 1, y: 0, direction: ["north", "south"], label: "B", phantom: true, }, ], { layout: { geometry: "hexagon", origin: { x: 0.5, y: -1.5 } } }, ), ).toMatchImageSnapshot({ customSnapshotIdentifier: "sample3" }); }); test("centered", () => { const viewBox = (centered: boolean) => { const svg = formationToSvg( [{ x: 1, y: 1, direction: "north" }, { x: 2, y: 1, direction: "north" }], { layout: { centered, origin: { x: 1, y: 0 } } }, ); return svg.match(/viewBox="([^"]+)"/)![1]!.split(" ").map(Number); }; const [x, y, w, h] = viewBox(true); // origin (1, 0) is 1 * (30 + 20) = 50 svg units across, 0 down expect(x + w / 2).toBeCloseTo(50); expect(y + h / 2).toBeCloseTo(0); // uncentered fits the dancers, so is smaller const [, , w0, h0] = viewBox(false); expect(w).toBeGreaterThan(w0); expect(h).toBeGreaterThan(h0); });