// 前端修复(F1–F14)的单元测试:只测能脱离 DOM 跑的纯函数 + 模板/源码级约束。 // 纯函数模块用 esbuild(devDependency)现场转成 CJS 再 require;模块级带 DOM 副作用的文件用 vm 切片执行。 const { test } = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm'); const Module = require('node:module'); const ROOT = path.join(__dirname, '..'); const read = rel => fs.readFileSync(path.join(ROOT, rel), 'utf8'); /** 把一个没有 import 的 TS 模块转成 CJS 并 require */ function loadTs(rel) { const esbuild = require('esbuild'); const src = read(rel); const out = esbuild.transformSync(src, { loader: 'ts', format: 'cjs', target: 'es2019' }).code; const m = new Module(rel, null); m.filename = path.join(ROOT, rel); m.paths = Module._nodeModulePaths(ROOT); m._compile(out, m.filename); return m.exports; } /** 从源码里切出一个顶层函数,在沙箱里执行 */ function evalFunction(rel, name, sandbox = {}) { const src = read(rel); const start = src.indexOf(`export function ${name}(`); assert.ok(start >= 0, `${rel} 里找不到 ${name}`); const end = src.indexOf('\n}\n', start); const code = src.slice(start, end + 3).replace(/^export /m, '') + `\n;${name}`; return vm.runInNewContext(code, sandbox); } // ---------- F6:fetchWithTimeout ---------- const { fetchWithTimeout, fetchJsonWithTimeout, makeTimeoutError } = loadTs('src-ts/core/fetch.ts'); test('fetchWithTimeout aborts a hanging request after the given ms and reports a timeout error', async () => { let signalSeen = null; const fakeFetch = (url, opts) => new Promise((_, reject) => { signalSeen = opts.signal; opts.signal.addEventListener('abort', () => { const e = new Error('The operation was aborted'); e.name = 'AbortError'; reject(e); }); }); const timers = []; const saved = { fetch: global.fetch, setTimeout: global.setTimeout, clearTimeout: global.clearTimeout, AbortController: global.AbortController }; global.fetch = fakeFetch; global.setTimeout = (fn, ms) => { timers.push({ fn, ms }); return timers.length; }; global.clearTimeout = id => { timers[id - 1].cleared = true; }; try { const p = fetchWithTimeout('/api/config', {}, 250); assert.ok(signalSeen, '必须把 AbortController.signal 挂到 fetch 上'); assert.equal(timers[0].ms, 250, '超时计时器应等于传入的 ms'); timers[0].fn(); // 模拟计时器到点 await assert.rejects(p, err => err.name === 'AbortError' && err.timeout === true && /超时/.test(err.message)); } finally { Object.assign(global, saved); } }); test('fetchWithTimeout clears the timer on success and keeps a caller-provided signal', async () => { const timers = []; const saved = { fetch: global.fetch, setTimeout: global.setTimeout, clearTimeout: global.clearTimeout }; global.fetch = async (url, opts) => ({ ok: true, url, opts }); global.setTimeout = (fn, ms) => { timers.push({ fn, ms }); return timers.length; }; global.clearTimeout = id => { timers[id - 1].cleared = true; }; try { const resp = await fetchWithTimeout('/api/map?type=3', {}, 1000); assert.equal(resp.url, '/api/map?type=3'); assert.equal(timers[0].cleared, true, '请求完成后必须清掉计时器'); // 调用方自带 signal:不新建 controller,直接透传 const own = new AbortController().signal; const r2 = await fetchWithTimeout('/x', { signal: own }, 10); assert.equal(r2.opts.signal, own); assert.equal(timers.length, 1, '自带 signal 时不应再起计时器'); } finally { Object.assign(global, saved); } }); test('fetchJsonWithTimeout returns ok=false instead of throwing on a non-JSON body', async () => { const saved = global.fetch; global.fetch = async () => ({ status: 502, json: async () => { throw new SyntaxError('Unexpected token <'); } }); try { const r = await fetchJsonWithTimeout('/api/bicycle', {}, 1000); assert.equal(r.resp.status, 502); assert.equal(r.body, null); assert.equal(r.ok, false); } finally { global.fetch = saved; } assert.equal(makeTimeoutError(8).timeout, true); }); test('friendlyError turns a timeout abort into a readable message', () => { const { friendlyError } = loadTs('src-ts/core/format.ts'); assert.equal(friendlyError(makeTimeoutError(8000)), '请求超时,请检查网络后重试'); assert.equal(friendlyError({ name: 'AbortError', message: '' }), '请求超时,请检查网络后重试'); assert.equal(friendlyError(new Error('boom')), 'boom'); }); // ---------- F7:getBikeState 判定顺序 ---------- const { getBikeState, getBikeStateText } = loadTs('src-ts/map/icons.ts'); test('getBikeState order: 损坏 → 使用中 → 欠压 → 低电量 → 空闲', () => { assert.equal(getBikeState({ state: 2, status: 0, electric_quantity: 90 }), 'reserved'); assert.equal(getBikeState({ state: 1, status: 1, electric_quantity: 90 }), 'inuse'); assert.equal(getBikeState({ state: 4, status: 0, electric_quantity: 90 }), 'locked'); assert.equal(getBikeState({ state: 10, status: 0, electric_quantity: 90 }), 'lowbattery'); // 15% 的空闲车:到处都是「低电量」,不再是「空闲」 assert.equal(getBikeState({ state: 1, status: 0, electric_quantity: 15 }), 'lowbattery'); assert.equal(getBikeStateText({ state: 1, status: 0, electric_quantity: 15 }), '低电量'); assert.equal(getBikeState({ state: 1, status: 0, electric_quantity: 20 }), 'available'); assert.equal(getBikeStateText({ state: 1, status: 0, electric_quantity: 20 }), '空闲'); assert.equal(getBikeState({ state: 1, status: 0, electricQuantity: 55 }), 'available'); assert.equal(getBikeState({ state: 1, status: 0 }), 'available', '缺电量字段默认 100'); assert.equal(getBikeState({ state: 9, status: 0 }), 'unknown'); // 顺序:损坏优先于使用中/低电量;使用中优先于低电量 assert.equal(getBikeState({ state: 2, status: 1, electric_quantity: 10 }), 'reserved'); assert.equal(getBikeState({ state: 1, status: 1, electric_quantity: 10 }), 'inuse'); assert.equal(getBikeState({ state: 4, status: 0, electric_quantity: 10 }), 'locked'); }); // ---------- F4:toast 栈位置(纯函数切片) ---------- test('toastStackTop sits below the order banner when it is shown, otherwise at the default top', () => { const toastStackTop = evalFunction('src-ts/ui/modals.ts', 'toastStackTop', { Number }); assert.equal(toastStackTop(58.5), 66.5, '横幅底边 58.5px → toast 栈贴在它下方 8px'); assert.equal(toastStackTop(null), 80); assert.equal(toastStackTop(0), 80); assert.equal(toastStackTop(undefined, 100), 100); }); test('toast stack DOM/CSS/JS constraints (max 3, independent 2500ms, role=status)', () => { const src = read('src-ts/ui/modals.ts'); assert.match(src, /const TOAST_MAX = 3;/); assert.match(src, /export const TOAST_MS = 2500;/); assert.match(src, /item\.setAttribute\("role", "status"\)/); assert.match(src, /while \(stack\.children\.length >= TOAST_MAX/, '超过 3 条要先移除最旧的'); assert.doesNotMatch(src.slice(src.indexOf('export function showToast'), src.indexOf('// ========== 定位失败兜底弹窗')), /getElementById\("toast"\)\.textContent/, '新路径不能再写死单个 #toast'); assert.match(read('templates/map.html'), /
<\/div>/); assert.match(read('static/css/map.css'), /#toast-stack\s*\{/); }); // ---------- F1:定位策略 ---------- test('location strategy: no auto locate at init, silent start after login, FAB goes through ensureLocation', () => { const core = read('src-ts/map/core.ts'); const initCore = core.slice(core.indexOf('export function initMapCore'), core.indexOf('// ========== 深色模式适配')); assert.doesNotMatch(initCore, /\n\s*startAutoLocation\(\);/, '地图初始化里不能再对访客直接 startAutoLocation()'); assert.match(initCore, /startAutoLocationIfLoggedIn\(\);/); assert.match(core, /if \(!S\.authToken \|\| !S\.map\) return Promise\.resolve\(false\);/, '静默定位必须同时满足已登录 + 地图就绪'); const startAuto = core.slice(core.indexOf('export function startAutoLocation('), core.indexOf('export function startAutoLocationIfLoggedIn')); assert.ok(startAuto.includes('const silent = !!(opts && opts.silent);'), 'startAutoLocation 要认 silent 选项'); assert.ok(startAuto.includes('if (!silent) showToast("正在获取您的位置...");'), 'silent 时不弹「正在获取您的位置...」'); const fab = core.slice(core.indexOf('export function findNearestBikeManual'), core.indexOf('// 显示我的位置')); assert.match(fab, /ensureLocation\(point => findNearestBike\(point\)/); assert.doesNotMatch(fab.replace(/\/\/.*$/mg, ''), /请先开启定位/, 'FAB 不再只 toast「请先开启定位」'); const ensure = core.slice(core.indexOf('export function ensureLocation')); assert.match(ensure, /Number\(err\.code\) === 1/, 'PERMISSION_DENIED 走卡片'); assert.match(ensure, /iOS:设置 → Safari → 位置;微信:右上角 … → 设置 → 位置/); assert.match(ensure, /okText: "用地图中心找车"/); assert.match(read('src-ts/nav/navigation.ts'), /ensureLocation\(pt => startNavigation\(bike, pt\), \{ verb: "导航" \}\)/, '卡片「导航」按钮走同一条定位路径'); assert.match(read('src-ts/order/actions.ts'), /ensureLocation\(point => applyCurrentLocation\(point\)/); const settings = read('src-ts/ui/settings.ts'); assert.ok((settings.match(/startAutoLocationIfLoggedIn\(\);/g) || []).length >= 3, '登录/注册/登录态校验三条路径都要挂静默定位'); assert.match(read('templates/map.html'), /id="location-fallback-modal"[\s\S]*id="location-fallback-ok">用地图中心找车 { const rentalIsFromRealOrder = evalFunction('src-ts/order/actions.ts', 'rentalIsFromRealOrder', { S: {} }); assert.equal(rentalIsFromRealOrder({ source: 'unlock' }), true); assert.equal(rentalIsFromRealOrder({ source: 'share' }), true); assert.equal(rentalIsFromRealOrder({ source: 'reminder' }), false); assert.equal(rentalIsFromRealOrder({}), false); assert.equal(rentalIsFromRealOrder(null), false); const actions = read('src-ts/order/actions.ts'); const check = actions.slice(actions.indexOf('export function checkRentalStatus'), actions.indexOf('export function resetUserState')); assert.doesNotMatch(check, /^\s*clearRentalState\(\);/m, 'checkRentalStatus 里不能再直接 clearRentalState()'); assert.ok((check.match(/clearRentalStateUnlessRealOrder\(\)/g) || []).length === 2); const sync = actions.slice(actions.indexOf('export async function syncWechatOrder'), actions.indexOf('export function rentalIsFromRealOrder')); assert.doesNotMatch(sync, /^\s*clearRentalState\(\);/m); assert.match(actions, /order_id: rentalId \|\| null,[\s\S]*bike_code: bikeCode,/, 'startRentalFromServer 要存 order_id'); const status = read('src-ts/order/status.ts'); assert.match(status, /if \(hadOrder && rentalIsFromRealOrder\(\)\) clearRentalState\(\);/, '只有订单横幅报告订单结束才清真实订单计时条'); }); test('resetUserState clears banner, timer, order, share banners and localStorage; wired into logout and kick', () => { const actions = read('src-ts/order/actions.ts'); const fn = actions.slice(actions.indexOf('export function resetUserState'), actions.indexOf('// static/js/map.js:3894')); for (const piece of ['hideOrderBanner()', 'clearRentalState()', 'S.currentOrder = null', 'getElementById("share-banners")', 'localStorage.removeItem(RENTAL_KEY)']) { assert.ok(fn.includes(piece), `resetUserState 缺少 ${piece}`); } const settings = read('src-ts/ui/settings.ts'); const logout = settings.slice(settings.indexOf('export async function handleLogout'), settings.indexOf('export function updateAuthButton')); assert.match(logout, /resetUserState\(\);/); const check = settings.slice(settings.indexOf('export async function checkAuthStatus'), settings.indexOf('// ========== 订单状态检测')); assert.match(check, /resetUserState\(\);/); }); // ---------- F6:core/actions 里的业务 fetch 都带超时 ---------- test('no bare fetch( left in map/core.ts, order/actions.ts, core/http.ts (SSE excluded)', () => { for (const f of ['src-ts/map/core.ts', 'src-ts/order/actions.ts', 'src-ts/core/http.ts']) { assert.doesNotMatch(read(f), /(^|[^\w.])fetch\(/, `${f} 仍有裸 fetch(`); } assert.match(read('src-ts/map/core.ts'), /showMapLoadFailure\("config", friendlyError\(err\)\)/, 'config 超时/失败要落到失败卡片'); }); // ---------- F8 / F13 / F14 ---------- test('renderMap refreshes or closes the open card; scanCode guards 401/non-JSON; refreshMap forces a request', () => { const markers = read('src-ts/map/markers.ts'); assert.match(markers, /showBikeDetail\(fresh\.code, \{ pan: false \}\)/); assert.match(markers, /showToast\("这辆车已离开实时列表"\)/); assert.match(read('src-ts/card/bike-card.ts'), /showBikeDetail\(id, opts\?: any\)/); const actions = read('src-ts/order/actions.ts'); const scan = actions.slice(actions.indexOf('export async function scanCode'), actions.indexOf('export function handleScanResult')); assert.match(scan, /btn\.disabled = true; btn\.textContent = "查询中\.\.\."/); assert.match(scan, /if \(resp\.status === 401\) \{ showLoginGate\(\); return; \}/); assert.match(scan, /if \(!data \|\| typeof data !== "object"\) \{ showLoginGate\(\); return; \}/); assert.match(actions, /S\.map\?\.panTo\(/); const core = read('src-ts/map/core.ts'); assert.match(core, /export function loadMapData\(type, showLoading = true, quiet = false, force = false\)/); assert.match(core, /if \(mapRequest && mapRequest\.type === String\(type\) && !force\) return mapRequest\.promise;/); const refresh = core.slice(core.indexOf('export function refreshMap'), core.indexOf('// ========== 渲染地图')); assert.match(refresh, /loadMapData\(S\.currentType, false, false, true\)/); assert.match(refresh, /\.finally\(\(\) => btn\.classList\.remove\("spinning"\)\)/, '转圈必须跟真实请求绑定'); assert.doesNotMatch(refresh, /setTimeout\(/); }); // ---------- F10 / F11 / F12 / bike-clusters ---------- test('templates and static script constraints', () => { const map = read('templates/map.html'); assert.match(map, /