Adjust tests to use vitest + jsdom

This commit is contained in:
Schluffe
2026-08-08 18:35:57 +02:00
parent ae8c63ce11
commit 9bdffd06e4
20 changed files with 196 additions and 150 deletions
+55
View File
@@ -0,0 +1,55 @@
import { afterEach, beforeEach, expect, test } from "vitest";
import { loadImage } from "./loadImage.ts";
class MockImage {
static instances: MockImage[] = [];
onload: (() => void) | null = null;
onerror: ((error: unknown) => void) | null = null;
src = "";
constructor() {
MockImage.instances.push(this);
}
}
const RealImage = globalThis.Image;
const realError = console.error;
const errors: unknown[][] = [];
beforeEach(() => {
globalThis.Image = MockImage as unknown as typeof Image;
console.error = (...args: unknown[]) => {
errors.push(args);
};
});
afterEach(() => {
globalThis.Image = RealImage;
console.error = realError;
MockImage.instances = [];
errors.length = 0;
});
test("loadImage", async () => {
const promise = loadImage("image.png");
const image = MockImage.instances[0];
expect(image.src).toBe("image.png");
image.onload!();
await expect(promise).resolves.toBe(image);
expect(errors).toEqual([]);
});
test("loadImage error", async () => {
const promise = loadImage("missing.png");
const image = MockImage.instances[0];
image.onerror!("missing");
// errors are logged, but the promise still resolves with the image
await expect(promise).resolves.toBe(image);
expect(errors).toEqual([["missing"]]);
});