Files
nage/engine/lib/loadImage.test.ts
T

64 lines
1.4 KiB
TypeScript

import { afterEach, beforeEach, expect, test } from "vitest";
import { loadImage } from "./loadImage.ts";
import missingTextureSrc from "./missingTexture.svg?url";
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!("boom");
const placeholder = MockImage.instances[1];
expect(errors).toEqual([["boom"]]);
expect(placeholder.src).toBe(missingTextureSrc);
placeholder.onload!();
// errors are logged, but the promise still resolves
// with a drawable placeholder texture
await expect(promise).resolves.toBe(placeholder);
});