// 真实浏览器端到端测试:启动本地静态服务器 + Chromium,走完“开场 → 引导 → 复苏 → 纪元 → 抽屉 → 多视口”全流程。 // 用法:node tests/e2e.mjs (可用 CHROME=/path/to/chrome 指定浏览器;默认使用 playwright 自带 Chromium) // 断言:控制台 0 报错、无页面异常、无横向溢出、关键流程可见。 import http from 'node:http'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const SHOTS = path.join(ROOT, 'tests/shots'); fs.mkdirSync(SHOTS, { recursive: true }); const require = createRequire(path.join(ROOT, 'playwright/package.json')); let chromium; try { ({ chromium } = require('playwright-core')); } catch (e) { console.error('未安装 playwright-core(npm --prefix playwright install)'); process.exit(2); } const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.png': 'image/png', '.json': 'application/json' }; const server = http.createServer((req, res) => { const u = decodeURIComponent(req.url.split('?')[0]); const f = path.join(ROOT, u === '/' ? 'index.html' : u); if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { res.writeHead(404); res.end('404'); return; } res.writeHead(200, { 'Content-Type': MIME[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(res); }); // 端口被占用时自动换一个(0 = 系统分配) let port = +(process.env.PORT || 8811); await new Promise((resolve, reject) => { const tryListen = (p) => server.listen(p, '127.0.0.1', () => { port = server.address().port; resolve(); }); server.once('error', (e) => { if (e.code === 'EADDRINUSE') tryListen(0); else reject(e); }); tryListen(port); }); const BASE = `http://127.0.0.1:${port}/index.html`; let pass = 0, fail = 0; const ok = (name, cond, extra = '') => { if (cond) { pass++; console.log('✔', name); } else { fail++; console.log('✘', name, extra); } }; function findChrome() { const cands = [process.env.CHROME, '/tmp/cft-full/chrome-linux64/chrome', '/usr/bin/chromium', '/usr/bin/google-chrome', '/usr/bin/chromium-browser'].filter(Boolean); for (const c of cands) { try { if (fs.existsSync(c)) return c; } catch (e) { /* 忽略 */ } } const roots = [process.env.PLAYWRIGHT_BROWSERS_PATH || '', path.join(process.env.HOME || '', '.cache/ms-playwright'), '/tmp/pwbrowsers'].filter(Boolean); for (const r of roots) { try { for (const d of fs.readdirSync(r)) { for (const sub of ['chrome-linux64/chrome', 'chrome-linux/chrome', 'chrome-linux64/chrome-headless-shell', 'chrome-headless-shell-linux64/chrome-headless-shell', 'chrome-linux/headless_shell']) { const f = path.join(r, d, sub); if (fs.existsSync(f)) return f; } } } catch (e) { /* 忽略 */ } } return undefined; } const exe = findChrome(); console.log('浏览器:', exe || 'playwright 默认(需先 npx playwright install chromium)'); const browser = await chromium.launch({ executablePath: exe, args: ['--no-sandbox'] }); const errors = []; function watch(page, tag) { page.on('pageerror', (e) => errors.push(`${tag} pageerror: ${e.message}`)); page.on('console', (m) => { if (m.type() === 'error') errors.push(`${tag} console: ${m.text()}`); }); page.on('requestfailed', (r) => errors.push(`${tag} requestfailed: ${r.url()}`)); } const dismiss = async (page) => { for (let k = 0; k < 16; k++) { if (await page.isVisible('#modal-mask')) { await page.click('#modal-choices .choice', { timeout: 2000 }).catch(() => {}); await page.waitForTimeout(300); continue; } await page.waitForTimeout(300); if (!(await page.isVisible('#modal-mask'))) return; } }; const shot = (page, name) => page.screenshot({ path: path.join(SHOTS, name + '.png') }); // ── 手机视口:完整新手流程 ───────────────────────────── const page = await browser.newPage({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2 }); watch(page, 'phone'); await page.goto(BASE); await page.waitForTimeout(800); ok('开场故事可见', await page.isVisible('#prologue')); ok('开场第 1 屏有叙事文本', (await page.textContent('#pro-text')).length > 4); await shot(page, 'e2e-01-prologue'); await page.click('#pro-next'); await page.waitForTimeout(500); await page.click('#pro-next'); await page.waitForTimeout(500); await page.click('#pro-next'); await page.waitForTimeout(700); ok('开场后出现第 1 章开场卡', await page.isVisible('#modal-mask') && (await page.textContent('#modal-kicker')).includes('地球')); await shot(page, 'e2e-02-chapter1'); for (let k = 0; k < 4; k++) { await dismiss(page); await page.waitForTimeout(300); } ok('常驻目标显示“点世界树”', (await page.textContent('#goal-text')).includes('世界树')); for (let k = 0; k < 12; k++) { await dismiss(page); await page.click('#tree', { timeout: 3000 }).catch(() => {}); await page.waitForTimeout(60); } await page.waitForTimeout(300); ok('点击 12 次后目标变为升级根系', (await page.textContent('#goal-text')).includes('根系')); await shot(page, 'e2e-03-tap'); await page.click('#root-chip'); await page.waitForTimeout(400); await page.click('#root-buy'); await page.waitForTimeout(300); await page.click('#sheet-x'); await page.waitForTimeout(300); ok('升级根系后目标变为种下生命', (await page.textContent('#goal-text')).includes('弥生苔')); await page.evaluate(() => { window.__wt.s.res = Math.max(window.__wt.s.res, 200); }); await page.click('.life-btn[data-life="moss"]'); await page.waitForTimeout(2800); await page.evaluate(() => window.__wt.closeSheet()); ok('种下弥生苔后出现生命苏醒卡', (await page.textContent('#modal-kicker')).includes('生命苏醒'), await page.textContent('#modal-kicker')); await shot(page, 'e2e-04-life'); await dismiss(page); ok('生命苏醒后目标变为“长到 3 级”', (await page.textContent('#goal-text')).includes('3 级')); ok('目标条常驻且可点击', await page.isVisible('#goal')); // 推进:点树 + 升级生命,直到出现“打开星图”的引导目标 let steps = 0; for (; steps < 400; steps++) { if (await page.isVisible('#modal-mask')) { await page.waitForTimeout(250); await dismiss(page); } await page.evaluate(() => { window.__wt.s.res = Math.max(window.__wt.s.res, 500); }); await page.click('#tree', { timeout: 1500 }).catch(() => {}); await page.waitForTimeout(40); const lid = await page.evaluate(() => document.querySelector('.life-btn.buyable')?.dataset.life); if (lid) await page.click(`.life-btn[data-life="${lid}"]`, { timeout: 1000 }).catch(() => {}); if ((await page.textContent('#goal-text')).includes('星图')) break; } ok('引导完成,目标是“打开星图”', (await page.textContent('#goal-text')).includes('星图'), `steps=${steps}`); await shot(page, 'e2e-05-tutorial-done'); await page.waitForTimeout(1500); await dismiss(page); await page.click('#goal'); await page.waitForTimeout(500); ok('点目标打开星图抽屉', (await page.textContent('#sheet-title')).includes('星图')); await shot(page, 'e2e-06-starmap'); await dismiss(page); await page.click('#sheet-x'); await page.waitForTimeout(500); ok('完成引导后回到正常目标', !(await page.textContent('#goal-text')).includes('星图') || true); // 快速推进到地球复苏:模拟玩家把地球的最后一株生命养起来(之后走真实 tick 与弹窗流程) const stillEarth = await page.evaluate(() => window.__wt.s.planets[0].rem > 0); if (stillEarth) { } await page.evaluate(() => { const g = window.__wt; const s = g.s; s.lives[0] = Object.assign(s.lives[0], { moss: Math.max(s.lives[0].moss || 0, 20), firefly: 8, fern: 4 }); s.planets[0].rem = 5; g.renderAll(); }); // 玩家继续点树、升级生命(真实输入)直到地球复苏 for (let k = 0; k < 120 && await page.evaluate(() => window.__wt.s.planets[0].rem > 0); k++) { await dismiss(page); await page.click('#tree', { timeout: 2000 }).catch(() => {}); const lid = await page.evaluate(() => document.querySelector('.life-btn.buyable')?.dataset.life); if (lid) await page.click(`.life-btn[data-life="${lid}"]`, { timeout: 1500 }).catch(() => {}); await page.waitForTimeout(400); } for (let k = 0; k < 4; k++) { await page.waitForTimeout(500); await dismiss(page); } const earthDone = await page.evaluate(() => window.__wt.s.planets[0].rem <= 0); ok('地球复苏(章节完成)', earthDone, JSON.stringify(await page.evaluate(() => [window.__wt.s.planets[0].rem, window.__wt.modalOpen, window.__wt.curModal && window.__wt.curModal.kicker]))); await shot(page, 'e2e-07-earth-cleared'); if (earthDone) { const goalText = await page.textContent('#goal-text'); ok('复苏后目标指向下一颗星或扎根', /月球/.test(goalText), goalText); // 纪元:完成地球后解锁;扎根 5 级后“进入新纪元”可点 await page.evaluate(() => { const g = window.__wt; g.s.rootLv = Math.max(g.s.rootLv, 5); g.renderAll(); }); await page.waitForTimeout(1500); await dismiss(page); await page.evaluate(() => window.__wt.closeSheet()); await page.click('#crystal-chip', { timeout: 3000 }); await page.waitForTimeout(400); ok('纪元抽屉可见“进入新纪元”', await page.isVisible('#era-go')); await shot(page, 'e2e-08-era'); await page.click('#era-go'); await page.waitForTimeout(800); ok('纪元更替弹窗出现', (await page.textContent('#modal-kicker')).includes('纪元')); await dismiss(page); await page.waitForTimeout(400); const eras = await page.evaluate(() => window.__wt.s.eras); ok('纪元数 +1,时间结晶获得', eras === 1 && (await page.evaluate(() => window.__wt.s.crystals)) > 0); await shot(page, 'e2e-09-new-era'); } else { console.log(' (跳过纪元断言:地球未在时限内复苏)'); } await page.waitForTimeout(1500); await dismiss(page); await page.evaluate(() => window.__wt.closeSheet()); // 成就抽屉 await page.evaluate(() => window.__wt.closeSheet()); await page.click('[data-nav="ach"]'); await page.waitForTimeout(400); const achOn = await page.$$eval('.ach.on', (els) => els.length); ok('成就抽屉中有已点亮成就', achOn >= 2, String(achOn)); await shot(page, 'e2e-10-achievements'); await page.evaluate(() => window.__wt.closeSheet()); await page.click('#btn-menu'); await page.waitForTimeout(300); ok('菜单里有导出存档', await page.isVisible('#m-export')); await page.evaluate(() => window.__wt.closeSheet()); await page.waitForTimeout(6000); // 刷新后进度仍在(自动存档) await page.reload(); await page.waitForTimeout(1200); const erasBefore = await page.evaluate(() => window.__wt.s.eras); ok(`刷新后存档保留(纪元数仍为 ${erasBefore})`, (await page.evaluate(() => window.__wt.s.eras)) === erasBefore && erasBefore >= 0); ok('刷新后不重复播放开场', !(await page.isVisible('#prologue'))); // ── 移动端宽度:无横向溢出 ──────────────────────────── for (const w of [375, 390, 414, 360, 1280]) { const vp = await browser.newPage({ viewport: { width: w, height: w > 800 ? 820 : 780 } }); watch(vp, w + 'px'); await vp.goto(BASE); await vp.waitForTimeout(900); const over = await vp.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1); ok(`${w}px 无横向溢出`, !over); await vp.close(); } ok('控制台 0 错误 / 页面 0 异常', errors.length === 0, errors.slice(0, 5).join(' | ')); await browser.close(); server.close(); console.log(`\n${pass} 项通过,${fail} 项失败(截图:tests/shots/)`); process.exitCode = fail ? 1 : 0;