import type { CaseResult, Snapshot } from "../shared/ipc";
import type { Layer } from "../shared/spec";
function escapeHtml(text: string): string {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&") return "&";
if (char === "<") return "<";
if (char === ">") return ">";
return """;
});
}
function time(at: number): string {
return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function layerLabel(layer: Layer): string {
return layer === "unit" ? "单元" : layer === "integration" ? "集成" : "E2E";
}
function resultRow(row: CaseResult): string {
return `
${row.pass ? "PASS" : "FAIL"}
${layerLabel(row.layer)}
${escapeHtml(row.name)}
${row.ms}ms
${escapeHtml(row.detail)}
`;
}
export function mountApp(root: HTMLElement): void {
root.innerHTML = `
正在运行测试…
怎么跑
命令与真实测试
pnpm --filter @tutorial/51-test-pyramid-app test:unitVitest(示例单测)
pnpm --filter @tutorial/51-test-pyramid-app smokeUI + IPC + E2E 自检
pnpm exec playwright test仓库级 E2E(未在本章 verify 跑)
本章把 10 个单元、5 个集成契约与 4 个 E2E 自检放进同一个界面;
失败注入只改一个单元用例,用来演示红灯。
`;
const summaryPill = root.querySelector(
'[data-testid="summary-pill"]',
);
const banner = root.querySelector('[data-testid="banner"]');
const pyramidCounts = root.querySelector(
'[data-testid="pyramid-counts"]',
);
const unitMs = root.querySelector('[data-testid="unit-ms"]');
const integrationMs = root.querySelector(
'[data-testid="integration-ms"]',
);
const e2eMs = root.querySelector('[data-testid="e2e-ms"]');
const statsEl = root.querySelector('[data-testid="stats"]');
const resultsEl = root.querySelector('[data-testid="results"]');
const todosEl = root.querySelector('[data-testid="todos"]');
const todoCount = root.querySelector(
'[data-testid="todo-count"]',
);
const todoInput = root.querySelector(
'[data-testid="todo-input"]',
);
const eventsEl = root.querySelector('[data-testid="events"]');
const injectBtn = root.querySelector(
'[data-testid="inject"]',
);
let state: Snapshot | null = null;
let filter: "all" | Layer = "all";
function totals(layer: Layer): number {
if (!state) return 0;
return (
Math.round(
state.results
.filter((row) => row.layer === layer)
.reduce((sum, row) => sum + row.ms, 0) * 100,
) / 100
);
}
function renderSummary(): void {
if (!state) return;
const { summary } = state;
if (summaryPill) {
summaryPill.textContent = `${summary.passed}/${summary.total} 通过`;
summaryPill.className = `pill ${summary.failed === 0 ? "ok-pill" : "bad-pill"}`;
}
if (banner) {
banner.textContent =
summary.failed === 0
? `全部通过:${summary.passed}/${summary.total} · 总耗时 ${summary.ms}ms`
: `有失败:${summary.failed} 项红灯,先修单元用例再扩大范围`;
banner.className = `banner ${summary.failed === 0 ? "ok" : "warn"}`;
}
if (pyramidCounts) {
pyramidCounts.textContent = `${state.counts.unit} / ${state.counts.integration} / ${state.counts.e2e}`;
}
if (unitMs) unitMs.textContent = `${totals("unit")}ms`;
if (integrationMs) integrationMs.textContent = `${totals("integration")}ms`;
if (e2eMs) e2eMs.textContent = `${totals("e2e")}ms`;
if (statsEl) {
statsEl.innerHTML = `
总数${summary.total}
通过${summary.passed}
失败${summary.failed}
耗时${summary.ms}ms`;
}
if (injectBtn) {
injectBtn.textContent = state.injectFailure ? "关闭失败注入" : "注入失败";
injectBtn.className = `btn ${state.injectFailure ? "danger" : ""}`;
}
}
function renderResults(): void {
if (!state || !resultsEl) return;
const rows = state.results.filter(
(row) => filter === "all" || row.layer === filter,
);
resultsEl.innerHTML =
rows.length === 0
? `当前过滤条件下没有结果`
: rows.map(resultRow).join("");
}
function renderTodos(): void {
if (!state) return;
if (todoCount) {
todoCount.textContent = `${state.todos.filter((todo) => todo.done).length}/${state.todos.length} 完成`;
}
if (!todosEl) return;
todosEl.innerHTML = state.todos
.map(
(
todo,
) => `
${escapeHtml(todo.title)}
`,
)
.join("");
}
function renderEvents(): void {
if (!eventsEl || !state) return;
eventsEl.innerHTML =
state.events.length === 0
? `暂无活动`
: state.events
.slice(0, 8)
.map(
(row) => `
${time(row.at)}
${escapeHtml(row.kind)}
${escapeHtml(row.detail)}
`,
)
.join("");
}
function render(next: Snapshot): void {
state = next;
renderSummary();
renderResults();
renderTodos();
renderEvents();
}
async function addFromInput(): Promise {
if (!todoInput) return;
const value = todoInput.value;
if (!value.trim()) return;
todoInput.value = "";
render(await window.api.testing.add(value));
}
async function waitFor(
check: () => boolean,
timeout = 2500,
): Promise {
const start = performance.now();
while (performance.now() - start < timeout) {
if (check()) return true;
await new Promise((resolve) => setTimeout(resolve, 50));
}
return false;
}
window.__runE2E = async () => {
if (!state) return;
const results: CaseResult[] = [];
const push = (name: string, pass: boolean, detail: string, ms: number) => {
results.push({ layer: "e2e", name, pass, ms, detail });
};
const before = document.querySelectorAll('[data-testid="todo-row"]').length;
push(
"初始列表渲染",
before === state.todos.length,
`${before}/${state.todos.length}`,
0,
);
const title = `E2E ${Date.now().toString().slice(-4)}`;
const start = performance.now();
if (todoInput) todoInput.value = title;
root.querySelector('[data-testid="todo-add"]')?.click();
const added = await waitFor(
() =>
document.querySelectorAll('[data-testid="todo-row"]').length ===
before + 1,
);
push(
"添加后列表 +1",
added,
added ? "ok" : "timeout",
Math.round(performance.now() - start),
);
const text =
document.querySelector('[data-testid="todos"]')?.textContent ?? "";
push("新项文本可见", text.includes(title), title, 0);
const firstBox = document.querySelector(
'[data-testid="todo-row"] input[type="checkbox"]',
);
if (!firstBox) {
push("切换第一项状态", false, "missing checkbox", 0);
} else {
const wasChecked = firstBox.checked;
const toggleStart = performance.now();
firstBox.click();
const flipped = await waitFor(() => {
const current = document.querySelector(
'[data-testid="todo-row"] input[type="checkbox"]',
);
return current ? current.checked !== wasChecked : false;
});
push(
"切换第一项状态",
flipped,
flipped ? "ok" : "timeout",
Math.round(performance.now() - toggleStart),
);
}
render(await window.api.testing.reportE2E(results));
return {
count: results.length,
passed: results.filter((row) => row.pass).length,
};
};
void window.api.testing.snapshot().then(render);
window.api.testing.onEvent(() => {
void window.api.testing.snapshot().then(render);
});
root
.querySelector('[data-testid="run"]')
?.addEventListener("click", async () => {
render(await window.api.testing.run());
await window.__runE2E?.();
});
injectBtn?.addEventListener("click", async () => {
render(await window.api.testing.inject(!state?.injectFailure));
});
root
.querySelector('[data-testid="todo-add"]')
?.addEventListener("click", () => {
void addFromInput();
});
todoInput?.addEventListener("keydown", (event) => {
if (event.key === "Enter") void addFromInput();
});
todosEl?.addEventListener("change", (event) => {
const target = event.target as HTMLInputElement;
if (target.type !== "checkbox") return;
const id = Number(target.dataset.id);
if (Number.isInteger(id)) void window.api.testing.toggle(id).then(render);
});
for (const [id, value] of [
["filter-all", "all"],
["filter-unit", "unit"],
["filter-integration", "integration"],
["filter-e2e", "e2e"],
] as const) {
root
.querySelector(`[data-testid="${id}"]`)
?.addEventListener("click", () => {
filter = value;
renderResults();
});
}
window.__prepareShots = async (stage) => {
document.body.dataset.shot = stage;
if (stage === "failure") {
render(await window.api.testing.inject(true));
render(await window.api.testing.run());
filter = "all";
renderResults();
document
.querySelector(".results-card")
?.scrollIntoView({ block: "start" });
return;
}
if (stage === "e2e") {
render(await window.api.testing.inject(false));
await window.__runE2E?.();
filter = "e2e";
renderResults();
document
.querySelector(".results-card")
?.scrollIntoView({ block: "start" });
return;
}
render(await window.api.testing.inject(false));
await window.__runE2E?.();
filter = "all";
renderResults();
document.querySelector(".pyramid-card")?.scrollIntoView({ block: "start" });
};
window.__demo = async () => {
const next = await window.api.testing.snapshot();
state = next;
return {
total: next.summary.total,
passed: next.summary.passed,
failed: next.summary.failed,
unit: next.counts.unit,
integration: next.counts.integration,
e2e: next.counts.e2e,
e2ePassed: next.results.filter((row) => row.layer === "e2e" && row.pass)
.length,
inject: next.injectFailure,
todos: next.todos.length,
ms: next.summary.ms,
};
};
}