Adjust tests to use vitest + jsdom
This commit is contained in:
@@ -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"]]);
|
||||
});
|
||||
Reference in New Issue
Block a user