hornwitser.no/utils/resolve-refs.test.tsx
Hornwitser 17f8693eae Add resolveRefs transform
Provide a transformation function that maps absolute references to
resources into relative references based on the location of a page.
This makes it possible to use the same links across multiple pages
in the hierarchy that works when loaded as files from the filesystem.
2025-01-22 08:58:48 +01:00

51 lines
1.7 KiB
TypeScript

import assert from "node:assert/strict";
import { suite, test } from "node:test";
import { resolveRefs } from "./resolve-refs.js";
import type { Element } from "antihtml";
suite("function resolveRefs", () => {
test("root to root relative href", () => {
const el = resolveRefs(<a href="/page.html">Link</a>, "/");
assert.equal((el as Element).attributes.get("href"), "page.html");
});
test("root to subdir relative href", () => {
const el = resolveRefs(<a href="/dir/page.html">Link</a>, "/");
assert.equal((el as Element).attributes.get("href"), "dir/page.html");
});
test("subdir to root relative href", () => {
const el = resolveRefs(<a href="/page.html">Link</a>, "/subdir");
assert.equal((el as Element).attributes.get("href"), "../page.html");
});
test("subdir to subdir relative href", () => {
const el = resolveRefs(<a href="/alt/page.html">Link</a>, "/subdir");
assert.equal((el as Element).attributes.get("href"), "../alt/page.html");
});
test("nested element", () => {
const el = resolveRefs(<div>Content with <a href="/page.html">Link</a></div>, "/");
assert.equal((el.childNodes[1] as Element).attributes.get("href"), "page.html");
});
test("returns element if no changes", () => {
const el = <div>Content with <em>emphasis</em></div>;
const resEl = resolveRefs(el, "/");
assert.equal(el, resEl);
});
test("returns new element if changed", () => {
const el = <div>Content with <a href="/page.html">Link</a></div>;
const resEl = resolveRefs(el, "/");
assert.notEqual(el, resEl);
});
test("does not modify input", () => {
const elFn = () => <div>Content with <a href="/page.html">Link</a></div>;
const el = elFn();
resolveRefs(el, "/");
assert.deepEqual(el, elFn());
});
});