shots.mjs 4.2 KB
/**
 * 逐页截图:用本机的 Edge 打开系统,按清单走一遍,每页存一张图。改完界面用它看一眼实际效果。
 *
 *   node web/e2e/shots.mjs                      # 9100、dealer_parts 空间、全部页面
 *   node web/e2e/shots.mjs objects inbox        # 只截名字里带这些词的
 *   PORT=9101 WS=default node web/e2e/shots.mjs
 *
 * 清单里每一项:name、hash、user(以谁的身份看)、可选的 steps(点哪里)、expect(页面上必须出现的字)。
 *
 * 同时是冒烟检查,下面任何一条不满足就以退出码 1 结束:
 *   - 浏览器控制台没有报错,接口没有返回 4xx / 5xx;
 *   - 页面上没有露出 undefined / NaN / [object Object];
 *   - 截图时页面不在转圈(数据加载完了);
 *   - 清单里 expect 的字都在页面上。
 */
import { chromium } from "playwright-core";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || "9100";
const WS = process.env.WS || "dealer_parts";
const OUT = process.env.OUT || path.join(here, "shots");
const BASE = `http://127.0.0.1:${PORT}`;
const only = process.argv.slice(2);

/** @type {{name: string, hash: string, user?: string, steps?: (page: import('playwright-core').Page) => Promise<void>, full?: boolean, width?: number}[]} */
export const PAGES = JSON.parse(fs.readFileSync(path.join(here, "pages.json"), "utf-8"));

const browser = await chromium.launch({ channel: "msedge", headless: true });
const errors = [];
for (const p of PAGES) {
  if (only.length && !only.some((w) => p.name.includes(w))) continue;
  const ctx = await browser.newContext({ viewport: { width: p.width || 1440, height: p.height || 900 }, deviceScaleFactor: 1 });
  await ctx.addInitScript(([ws, user]) => {
    localStorage.setItem("onto.workspace", ws);
    localStorage.setItem("onto.user", user);
  }, [WS, p.user || "admin"]);
  const page = await ctx.newPage();
  page.on("console", (m) => { if (m.type() === "error") errors.push(`${p.name}: ${m.text().slice(0, 200)}`); });
  page.on("pageerror", (e) => errors.push(`${p.name}: ${String(e).slice(0, 200)}`));
  page.on("response", (r) => {
    if (r.status() >= 400 && r.url().includes("/api/")) errors.push(`${p.name}: 接口 ${r.status()} ${r.url().replace(BASE, "").slice(0, 120)}`);
  });
  await page.goto(`${BASE}/#/${p.hash}`);
  await page.waitForTimeout(p.wait || 1800);
  for (const s of p.steps || []) {
    try {
      if (s.click && s.css) await page.locator(s.click).first().click({ timeout: 4000 });
      else if (s.click) await page.getByText(s.click, { exact: !!s.exact }).first().click({ timeout: 4000 });
      if (s.clickRole) await page.getByRole(s.clickRole, { name: s.name }).first().click({ timeout: 4000 });
      if (s.fill) await page.locator(s.fill).first().fill(String(s.value));
      if (s.press) await page.keyboard.press(s.press);
      if (s.scroll !== undefined) await page.evaluate((y) => document.querySelectorAll('.overflow-auto').forEach((e) => { e.scrollTop = y; }), s.scroll);
      await page.waitForTimeout(s.wait || 900);
    } catch (e) {
      errors.push(`${p.name}: 步骤 ${JSON.stringify(s)} 没做成 —— ${String(e).split("\n")[0].slice(0, 160)}`);
    }
  }
  if (await page.locator("main .animate-spin").count()) {
    await page.waitForTimeout(2500);
    if (await page.locator("main .animate-spin").count()) errors.push(`${p.name}: 截图时还在转圈`);
  }
  const text = await page.locator("body").innerText();
  for (const bad of ["undefined", "NaN", "[object Object]"]) {
    if (text.includes(bad)) errors.push(`${p.name}: 页面上出现了「${bad}」`);
  }
  for (const want of p.expect || []) {
    if (!text.includes(want)) errors.push(`${p.name}: 页面上没有「${want}」`);
  }
  fs.mkdirSync(OUT, { recursive: true });
  await page.screenshot({ path: path.join(OUT, `${p.name}.png`), fullPage: !!p.full });
  console.log("✓", p.name);
  await ctx.close();
}
await browser.close();
if (errors.length) {
  console.log("\n页面上的错误:");
  for (const e of [...new Set(errors)]) console.log("  -", e);
  process.exitCode = 1;
} else {
  console.log("冒烟检查通过");
}