Project Files
test / pixlstash.test.ts
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { Jimp } from "jimp";
import { describeError, downscale } from "../src/pixlstash.ts";
describe("describeError", () => {
it("stringifies non-Error values", () => {
assert.equal(describeError("oops"), "oops");
assert.equal(describeError(42), "42");
assert.equal(describeError(null), "null");
});
it("formats an Error without cause as just the message", () => {
assert.equal(describeError(new Error("boom")), "Error: boom");
});
it("formats an Error with a cause as `message — cause`", () => {
const cause = new Error("ECONNREFUSED");
const err = new Error("fetch failed", { cause });
assert.equal(describeError(err), "fetch failed — Error: ECONNREFUSED");
});
});
describe("downscale", () => {
const makePng = async (w: number, h: number): Promise<Buffer> => {
const img = new Jimp({ width: w, height: h, color: 0x336699ff });
return Buffer.from(await img.getBuffer("image/png"));
};
it("returns original bytes when format isn't PNG/JPEG", async () => {
const bytes = Buffer.from([1, 2, 3, 4]);
assert.equal(await downscale(bytes, "webp", 100), bytes);
assert.equal(await downscale(bytes, "gif", 100), bytes);
});
it("returns original bytes when maxHeight <= 0", async () => {
const png = await makePng(100, 1000);
assert.equal(await downscale(png, "png", 0), png);
assert.equal(await downscale(png, "png", -1), png);
});
it("returns original bytes when image is already shorter than the cap", async () => {
const png = await makePng(100, 200);
assert.equal(await downscale(png, "png", 500), png);
});
it("resizes a taller PNG to the cap, preserving aspect ratio", async () => {
const png = await makePng(200, 1000); // aspect 1:5
const out = await downscale(png, "png", 200);
assert.notEqual(out, png);
const result = await Jimp.read(out);
assert.equal(result.height, 200);
assert.equal(result.width, 40); // 200 × (200/1000)
});
it("falls back to the original bytes when the decoder throws", async () => {
const garbage = Buffer.from("not actually an image");
const out = await downscale(garbage, "png", 100);
assert.equal(out, garbage);
});
});