import { html, stubNetwork } from "../helpers.ts";
import { assert, assertEquals, assertFalse } from "@std/assert";
import { tryFetchRichContent } from "../../services/rich-content-service.ts";
Deno.test("tryFetchRichContent: a preview and the post that follows share one fetch", async () => {
using net = stubNetwork(() => html(`
Once`));
const first = await tryFetchRichContent("https://example.com/once");
const second = await tryFetchRichContent("https://example.com/once");
assertEquals(second, first);
assertEquals(net.calls.length, 1);
// A refresh always goes to the page.
await tryFetchRichContent("https://example.com/once", { fresh: true });
assertEquals(net.calls.length, 2);
});
Deno.test("tryFetchRichContent: failures aren't kept", async () => {
let up = false;
using net = stubNetwork(() => {
if (!up) throw new TypeError("connection refused");
return html(`Up`);
});
const url = "https://example.com/flaky";
assertFalse((await tryFetchRichContent(url)).ok);
up = true;
const { ok, content } = await tryFetchRichContent(url);
assert(ok);
assertEquals(content?.title, "Up");
assertEquals(net.calls.length, 2);
});
Deno.test("tryFetchRichContent: an unreachable page is ok:false with a stub", async () => {
using _ = stubNetwork(() => {
throw new TypeError("connection refused");
});
assertEquals(await tryFetchRichContent("https://www.example.com/x"), {
ok: false,
content: {
type: "generic",
url: "https://www.example.com/x",
siteName: "example.com",
},
});
});
Deno.test("tryFetchRichContent: an error page is unreachable, not a preview", async () => {
using net = stubNetwork(() => html(`404 Not Found`, 404));
const url = "https://example.com/gone";
assertEquals(await tryFetchRichContent(url), {
ok: false,
content: { type: "generic", url, siteName: "example.com" },
});
// Not kept: the page may be back next time.
await tryFetchRichContent(url);
assertEquals(net.calls.length, 2);
});