test.build/core/adapters/document.adapter.test.ts
test.build/core/adapters/document.adapter.test.ts is a file in Codebase Testing. 79 lines of code and 0 definitions.
import { describe, expect, it } from "vitest";
import {
installDocument,
mapSettled,
readDocument,
rewriteDocument,
rewriteEach,
} from "@banes-lab/build-scripts/core/adapters/document.adapter.ts";
const PAGE = "<!doctype html><html><head><title>Terms</title></head><body><main>Text</main></body></html>";
describe("rewriteEach", () => {
it("rewrites one parsed document per item and hands each serialized page to the writer", () => {
const written = new Map<string, string>();
rewriteEach(
PAGE,
["a", "b"],
(document, item) => {
document.title = item;
},
(item, html) => {
written.set(item, html);
},
);
expect(written.get("a")).toContain("<title>a</title>");
expect(written.get("b")).toContain("<title>b</title>");
});
});
describe("readDocument", () => {
it("hands the parsed document to the reader and returns what it reads", () => {
expect(readDocument(PAGE, (document) => document.title)).toBe("Terms");
});
it("releases the document even when the reader throws", () => {
expect(() =>
readDocument(PAGE, () => {
throw new Error("reader");
}),
).toThrow("reader");
});
});
describe("rewriteDocument", () => {
it("serializes the document after the edit", () => {
const html = rewriteDocument(PAGE, (document) => {
document.title = "Privacy";
});
expect(html).toContain("<title>Privacy</title>");
});
});
describe("installDocument", () => {
it("installs a document at the site's address and moves it to each path it is given", () => {
const visit = installDocument("https://example.test");
visit("/terms");
expect(globalThis.document.location.href).toBe("https://example.test/terms");
});
});
describe("mapSettled", () => {
it("runs each item in order and lets the document's queued tasks run before the next item", async () => {
installDocument("https://example.test");
let toggled = 0;
const seen = await mapSettled(["a", "b", "c"], (item) => {
const details = globalThis.document.createElement("details");
details.addEventListener("toggle", () => {
toggled += 1;
});
details.open = true;
return `${item}${String(toggled)}`;
});
expect(seen).toStrictEqual(["a0", "b1", "c2"]);
expect(toggled).toBe(3);
});
it("awaits an asynchronous item before it starts the next one", async () => {
const order: string[] = [];
await mapSettled(["slow", "fast"], async (item) => {
await new Promise<void>((resolve) => {
setTimeout(resolve, item === "slow" ? 20 : 0);
});
order.push(item);
});
expect(order).toStrictEqual(["slow", "fast"]);
});
});