Files
leadboard/tests/html-scripts.test.mjs
2026-11-25 08:47:35 +00:00

36 lines
1.9 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { Script } from 'node:vm';
// 看板大半的邏輯寫在 index.html 的 inline script 裡(二十幾萬字元),瀏覽器才會執行。
// node --test 不會碰它,所以語法打壞了 CI 照樣綠燈,網站卻整頁空白。
// 這裡把每一段 inline script 和每一支瀏覽器用的 .js 都交給 V8 解析一次(只解析、不執行)。
const PAGES = ['index.html', 'my.html', 'archive.html'];
const BROWSER_SCRIPTS = ['calc-core.js', 'scope-ui.js', 'i18n.js'];
// 只挑沒有 src 的 <script>;有 type 的另外處理(目前沒有,有的話要先確認能不能當一般腳本解析)。
const INLINE = /<script([^>]*)>([\s\S]*?)<\/script>/g;
const read = (name) => readFile(new URL(`../${name}`, import.meta.url), 'utf8');
const parses = (source, filename) => assert.doesNotThrow(
() => new Script(source, { filename }), `${filename} 的 JavaScript 語法有問題`);
for (const page of PAGES) {
test(`${page} 的 inline script 語法正確`, async () => {
const html = await read(page);
const blocks = [...html.matchAll(INLINE)]
.map(([, attrs, body]) => ({ attrs: attrs.trim(), body }))
.filter(block => !/\bsrc=/.test(block.attrs));
assert.ok(blocks.length > 0, `${page} 裡找不到 inline script,選取條件可能要更新`);
for (const [index, block] of blocks.entries()) {
// 有 type 的腳本(module、JSON)不能當一般腳本解析,出現就要先更新這個測試。
assert.equal(block.attrs, '', `${page} 第 ${index + 1} 段 script 有屬性「${block.attrs}」,請確認這個測試還適用`);
parses(block.body, `${page}#script${index + 1}`);
}
});
}
test('瀏覽器用的 .js 檔語法正確', async () => {
for (const name of BROWSER_SCRIPTS) parses(await read(name), name);
});