import { test, expect, beforeEach } from "bun:test"; import { Window } from "happy-dom"; import { NAV_RUNTIME } from "../src/nav-runtime.ts"; let win: any; let fetchCalls: { url: string; opts: any }[]; let nextHtml: string; function install(bodyHtml: string): void { win = new Window({ url: "https://example.test/" }); win.document.body.innerHTML = bodyHtml; fetchCalls = []; nextHtml = ""; const g = globalThis as any; g.window = win; g.document = win.document; g.history = win.history; g.location = win.location; g.DOMParser = win.DOMParser; g.CustomEvent = win.CustomEvent; g.fetch = win.fetch = (url: string, opts: any) => { fetchCalls.push({ url, opts }); return Promise.resolve({ redirected: false, url, headers: { get: (k: string) => k.toLowerCase() === "content-type" ? "text/html; charset=utf-8" : null, }, text: () => Promise.resolve(nextHtml), }); }; (0, eval)(NAV_RUNTIME); } const flush = () => new Promise((r) => setTimeout(r, 0)); beforeEach(() => { const g = globalThis as any; for (const k of [ "window", "document", "history", "location", "DOMParser", "CustomEvent", "fetch", ]) { delete g[k]; } }); test("intercepts an internal link click and swaps #app in place", async () => { install(`

Home

About
`); nextHtml = `About` + `

About page

`; win.document.getElementById("lnk").click(); await flush(); expect(fetchCalls.length).toBe(1); expect(fetchCalls[0]!.url).toContain("/about"); expect(fetchCalls[0]!.opts.headers["x-wrnexus-nav"]).toBe("1"); expect(win.document.getElementById("app").innerHTML).toContain("About page"); expect(win.document.title).toBe("About"); }); test("ignores cross-origin links (full navigation)", async () => { install(`
x
`); win.document.getElementById("lnk").click(); await flush(); expect(fetchCalls.length).toBe(0); }); test("ignores modified clicks so new-tab still works", async () => { install(`
x
`); win.document .getElementById("lnk") .dispatchEvent( new win.MouseEvent("click", { bubbles: true, cancelable: true, button: 0, metaKey: true }), ); await flush(); expect(fetchCalls.length).toBe(0); }); test("exposes programmatic navigation", async () => { install(`

Home

`); nextHtml = `Dash

Dashboard

`; expect(typeof win.__wrnexusNavigate).toBe("function"); win.__wrnexusNavigate("/dashboard"); await flush(); expect(fetchCalls.length).toBe(1); expect(win.document.getElementById("app").innerHTML).toContain("Dashboard"); }); test("rebinds theme controls after swapping the page", async () => { install(`
About
`); let boundRoot: unknown; win.wireTheme = { bind: (root: unknown) => (boundRoot = root) }; nextHtml = `
`; win.document.getElementById("lnk").click(); await flush(); expect(boundRoot).toBe(win.document); expect(win.document.querySelector("[data-wire-theme-toggle]")).not.toBeNull(); });