// 연간 목표(goals.html)·주간 회의록(goal_meeting.html) + static/project.js UI 회귀 테스트 — jsdom.
// 서버는 가짜(fetch 대체)로 두고 지연(deferred)·순서 역전·503·연속 입력을 직접 만든다. 실제 브라우저 레이아웃·입력기·터치 기기는 아니다.
//
// python tests/js/render_goals.py # 템플릿 렌더 → tests/js/.out/goals_*.html · meeting_*.html
// npm install jsdom # (최초 1회, 또는 NODE_PATH 로 jsdom 이 있는 node_modules 지정)
// node tests/js/goals_meeting_ui.test.js
//
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
const fs = require("fs");
const path = require("path");
const { JSDOM, VirtualConsole } = require("jsdom");
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 180000);
const ROOT = path.join(__dirname, "..", "..");
const OUT = path.join(__dirname, ".out");
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
const PAGE = {};
["goals_admin", "goals_ro", "meeting_admin", "meeting_err", "meeting_ro"].forEach(function (n) {
PAGE[n] = fs.readFileSync(path.join(OUT, n + ".html"), "utf8");
});
const GOALS_URL = "http://localhost/project/goals/2026";
const MEET_URL = "http://localhost/project/goals/2026/meetings/9?week=2026-09-28";
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
function deferred() {
let resolve, reject;
const p = new Promise(function (a, b) { resolve = a; reject = b; });
return { promise: p, resolve: resolve, reject: reject };
}
function settle(n) {
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 40)) return r(); setImmediate(spin); })(); });
}
function wait(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
const unhandled = [];
process.on("unhandledRejection", function (e) { unhandled.push(String(e && e.message || e)); });
// env.route(method, re, fn(url, body, call)) — fn 이 {status, body, text} 또는 "NETWORK" 를 돌려준다(Promise 가능)
function makeEnv(html, url, opts) {
opts = opts || {};
const vc = new VirtualConsole();
const env = { calls: [], routes: [], navigations: 0, toasts: [], prompts: [], inflight: {}, maxInflight: {} };
vc.on("jsdomError", function (e) { if (/navigation/i.test(String(e && e.message))) env.navigations++; });
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: url, virtualConsole: vc });
const w = dom.window, d = w.document;
env.w = w; env.d = d;
w.__PJ_TEST__ = true;
w.console.error = function () {};
w.scrollTo = function () {};
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
w.erpConfirm = function () { return Promise.resolve(true); };
w.erpPrompt = function (msg, def) { env.prompts.push(msg); return Promise.resolve(opts.promptAnswer != null ? opts.promptAnswer : "새 이름"); };
w.erpAlert = function () {};
if (opts.storage) Object.keys(opts.storage).forEach(function (k) { w.localStorage.setItem(k, opts.storage[k]); });
if (opts.session) Object.keys(opts.session).forEach(function (k) { w.sessionStorage.setItem(k, opts.session[k]); });
env.route = function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); };
w.fetch = async function (u, o) {
const method = (o && o.method) || "GET";
let body = o && o.body;
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
const call = { method: method, url: String(u), body: body, keepalive: !!(o && o.keepalive), done: false };
env.calls.push(call);
const key = method + " " + String(u).replace(/^https?:\/\/[^/]+/, "");
env.inflight[key] = (env.inflight[key] || 0) + 1;
env.maxInflight[key] = Math.max(env.maxInflight[key] || 0, env.inflight[key]);
try {
for (const r of env.routes) {
if (r.method === method && r.re.test(String(u))) {
const out = await r.fn(String(u), body, call);
if (out === "NETWORK") throw new TypeError("Failed to fetch");
const status = out.status || 200;
return { ok: status < 400, status: status, statusText: "x",
json: async function () { return out.body || {}; }, text: async function () { return out.text || ""; } };
}
}
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; }, text: async function () { return ""; } };
} finally {
env.inflight[key]--;
call.done = true;
}
};
env.puts = function (re) { return env.calls.filter(function (c) { return c.method === "PUT" && re.test(c.url); }); };
env.toastText = function () { const t = d.querySelector(".erp-toast"); return t ? t.textContent : ""; };
return env;
}
async function boot(env) {
if (env.d.readyState === "loading") await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
env.w.eval(JS);
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
await settle();
return env;
}
function type(env, node, value) {
node.value = value;
node.dispatchEvent(new env.w.Event("input", { bubbles: true }));
}
function fire(env, node, name) { node.dispatchEvent(new env.w.Event(name, { bubbles: name !== "blur" && name !== "focus" })); }
function key(env, node, k, extra) {
const e = new env.w.KeyboardEvent("keydown", Object.assign({ key: k, bubbles: true, cancelable: true }, extra || {}));
node.dispatchEvent(e);
return e;
}
// 블록 하나가 예외로 멈춰도 나머지 블록은 계속(예외는 FAIL 로)
async function section(fn) {
try { await fn(); } catch (e) { check("블록 예외 없음: " + String(e && e.message || e).slice(0, 120), false); }
}
function itemLabel(b) { return (b.querySelector(".pj-ctxmenu-label") || b).textContent.trim(); }
function unload(env) {
const e = new env.w.Event("beforeunload", { cancelable: true });
env.w.dispatchEvent(e);
return e;
}
// ── 가짜 서버 — 목표 표(글 칸 상태를 기억해 화면 GET 에 반영) ───────────────
function goalsServer(env, st) {
st = Object.assign({ cells: {}, areaAdded: false, cellHook: null, metricHook: null, getHook: null }, st || {});
env.route("GET", /\/project\/api\//, function () { return { body: {} }; });
env.route("PUT", /\/project\/api\/goals\/rows\/\d+\/cells\/\d+$/, async function (u, body, call) {
const m = u.match(/rows\/(\d+)\/cells\/(\d+)/);
if (st.cellHook) { const r = await st.cellHook(u, body, call); if (r) return r; }
st.cells[m[1] + ":" + m[2]] = body.body;
return { body: { ok: true } };
});
env.route("PUT", /\/project\/api\/goals\/2026\/metrics$/, async function (u, body, call) {
if (st.metricHook) { const r = await st.metricHook(u, body, call); if (r) return r; }
const n = Number(String(body.value).replace(/[,\s]/g, ""));
st.metric = String(body.value);
return { body: { ok: true, label: body.value === "" ? "" : n.toLocaleString("en-US") } };
});
env.route("POST", /\/project\/api\/goals\/2026\/areas$/, function () { st.areaAdded = true; return { body: { ok: true } }; });
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/rows$/, function () { return { status: 201, body: { ok: true } }; });
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/move$/, function () { return { body: { ok: true } }; });
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/merge$/, function () { st.merged = true; return { body: { ok: true, row_id: 10, start: 1 } }; });
env.route("GET", /\/project\/goals\/2026$/, async function () {
if (st.getHook) await st.getHook();
st.gets = (st.gets || 0) + 1;
let html = PAGE.goals_admin.replace(/(