56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
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"]]);
|
|
});
|