// 프로젝트 관리 화면(project/project.html + static/project.js) UI 회귀 테스트 — jsdom.
// 서버 응답은 가짜(fetch 대체)로, 지연·실패·순서 역전을 직접 만든다. 실제 브라우저 레이아웃·입력기는 아니다.
//
// python tests/js/render_project.py # 템플릿 렌더 → tests/js/.out/project_render.html
// npm install jsdom # (최초 1회)
// TZ=America/Los_Angeles node tests/js/project_ui.test.js # 해외 시간대 브라우저 흉내
//
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
// Git Bash 는 윈도우 프로그램에 TZ 를 넘기지 않아 PJ_TEST_TZ 로도 받는다(날짜 객체를 만들기 전에 설정).
if (process.env.PJ_TEST_TZ) process.env.TZ = process.env.PJ_TEST_TZ;
const fs = require("fs");
const path = require("path");
const { JSDOM } = require("jsdom");
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 90000);
const ROOT = path.join(__dirname, "..", "..");
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
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 makeEnv(page) {
const dom = new JSDOM(page || html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
const w = dom.window, d = w.document;
w.__PJ_TEST__ = true;
w.HTMLDialogElement.prototype.showModal = function () { this.open = true; };
w.HTMLDialogElement.prototype.close = function () { this.open = false; this.dispatchEvent(new w.Event("close")); };
Object.defineProperty(d, "fonts", { configurable: true, value: { load: async function () { return [{}]; } } });
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
w.URL.createObjectURL = function () { return "blob:x"; };
w.URL.revokeObjectURL = function () {};
w.Image = function () { const self = this; Object.defineProperty(self, "src", { set: function () { setTimeout(function () { if (self.onerror) self.onerror(); }, 0); } }); };
w.console.error = function () {};
let confirmAnswer = false;
w.erpConfirm = function () { env.confirms++; return Promise.resolve(confirmAnswer); };
w.erpAlert = function (m) { env.alerts.push(m); };
w.alert = function (m) { env.alerts.push(m); };
// 8초 이상 타이머(실시간 새로고침)는 붙잡아 두고 테스트가 직접 돌린다.
const realSetTimeout = w.setTimeout.bind(w);
const slow = [];
w.setTimeout = function (fn, ms) {
if (ms >= 8000) { slow.push({ fn: fn, ms: ms }); return 999000 + slow.length; }
return realSetTimeout(fn, ms);
};
const env = {
w: w, d: d, calls: [], routes: [], slow: slow, confirms: 0, alerts: [],
setConfirm: function (v) { confirmAnswer = v; },
route: function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); },
runSlow: async function () { const t = slow.shift(); if (t) { t.fn(); await settle(); } return t; },
};
w.fetch = async function (url, opts) {
const method = (opts && opts.method) || "GET";
let body = opts && opts.body;
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
env.calls.push({ method: method, url: String(url), body: body });
if (process.env.PJ_TEST_TRACE && method === "PUT") console.log(" TRACE PUT", url, new Error().stack.split("\n").slice(2, 7).join(" | "));
for (const r of env.routes) {
if (r.method === method && r.re.test(String(url))) {
const out = await r.fn(String(url), body);
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; } };
}
}
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; } };
};
return env;
}
function settle(n) {
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 30)) return r(); setImmediate(spin); })(); });
}
function detail(id, title, extra) {
return Object.assign({ id: id, title: title, project_id: 1, stage_id: 11, description: "", priority: "normal",
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null }, extra || {});
}
function baseRoutes(env) {
env.route("GET", /\/project\/api\/tasks\/\d+\/attachments/, function () { return { body: { attachments: [] } }; });
env.route("GET", /\/project\/api\/tasks\/\d+\/comments/, function () { return { body: { comments: [], events: [], features: {} } }; });
env.route("GET", /\/project\/api\/projects\/\d+\/members/, function () { return { body: { members: [{ user_email: "me@test.local" }] } }; });
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [] } }; });
env.route("GET", /\/project\/api\/all-users/, function () { return { body: { users: [] } }; });
env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: "v1" } }; });
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return { body: { task: detail(101, "작업 A") } }; });
env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B") } }; });
}
async function boot(env) {
// jsdom 이 문서를 다 읽고 DOMContentLoaded 를 보낸 뒤에 넣는다 — 먼저 넣으면 초기화가 두 번 돈다.
if (env.d.readyState === "loading") {
await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
}
// jsdom 의