zcbot/tests/frontend_preview.test.mjs

41 lines
2.0 KiB
JavaScript

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { htmlPreviewDocument } from "../web/static/js/preview_content.js";
// preview.js has browser-only top-level bindings, so exercise the integration contract
// through its shipped source and markup while keeping this test dependency-free.
const previewJs = readFileSync(new URL("../web/static/js/preview.js", import.meta.url), "utf8");
const pageHtml = readFileSync(new URL("../web/static/dev.html", import.meta.url), "utf8");
test("HTML is a renderable category rather than plain text", () => {
assert.match(previewJs, /html:\s+new Set\(\["html","htm"\]\)/);
assert.match(previewJs, /frame\.setAttribute\("sandbox", ""\)/);
assert.match(previewJs, /frame\.srcdoc = htmlPreviewDocument\(text\)/);
});
test("HTML preview blocks scripts, navigation, and external resources", () => {
const document = htmlPreviewDocument("<!doctype html><html><head><title>x</title></head><body>x</body></html>");
assert.match(document, /<head><meta http-equiv="Content-Security-Policy"/);
assert.match(document, /default-src 'none'/);
assert.match(document, /form-action 'none'/);
assert.match(document, /base-uri 'none'/);
assert.ok(document.indexOf("Content-Security-Policy") < document.indexOf("<title>"));
assert.doesNotMatch(previewJs, /allow-scripts/);
});
test("HTML fragments receive a restrictive head before their content", () => {
const document = htmlPreviewDocument("<h1>报告</h1>");
assert.match(document, /^<head><meta http-equiv="Content-Security-Policy"/);
assert.match(document, /<\/head><h1>报告<\/h1>$/);
});
test("main and mini previews expose preview/source mode controls", () => {
for (const prefix of ["fp", "mp"]) {
assert.match(pageHtml, new RegExp(`id="${prefix}-mode-preview"`));
assert.match(pageHtml, new RegExp(`id="${prefix}-mode-source"`));
assert.match(previewJs, new RegExp(`_showRenderableText\\("${prefix}", cat, text\\)`));
}
});