Files
jiapuapp/tests/a04-registration-runtime-smoke.js
T
2026-07-24 18:03:14 +08:00

149 lines
7.8 KiB
JavaScript

const assert = require('assert')
const a01Url = 'http://localhost:5173/#/pages/auth/a01-entry'
const a04Url = 'http://localhost:5173/#/pages/auth/a04-register'
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))
const connect = async () => {
const port = process.env.CHROME_DEBUGGING_PORT || '9222'
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()
const page = pages.find((item) => item.type === 'page' && item.url.startsWith('http://localhost:5173'))
if (!page) throw new Error('Chrome debugging has no application page')
const socket = new WebSocket(page.webSocketDebuggerUrl)
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true })
socket.addEventListener('error', reject, { once: true })
})
let id = 0
const pending = new Map()
const exceptions = []
socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data)
if (message.method === 'Runtime.exceptionThrown') exceptions.push(message.params.exceptionDetails.text)
const request = pending.get(message.id)
if (!request) return
pending.delete(message.id)
if (message.error) request.reject(new Error(message.error.message))
else request.resolve(message.result)
})
const send = (method, params = {}) => new Promise((resolve, reject) => {
id += 1
pending.set(id, { resolve, reject })
socket.send(JSON.stringify({ id, method, params }))
})
return { socket, send, exceptions }
}
const valueOf = async (send, expression) => {
const result = await send('Runtime.evaluate', { expression, returnByValue: true })
if (result.exceptionDetails) {
throw new Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text)
}
return result.result?.value
}
const waitFor = async (send, expression, message) => {
for (let attempt = 0; attempt < 40; attempt += 1) {
if (await valueOf(send, expression)) return
await sleep(100)
}
throw new Error(message)
}
const navigate = async (send, url, selector) => {
// 每次增加查询戳,确保同一路由也会建立全新文档,避免沿用上一次表单状态。
const targetUrl = url.replace('/#/', `/?runtime=${Date.now()}#/`)
await send('Page.navigate', { url: targetUrl })
await waitFor(send, `location.href.includes(${JSON.stringify(new URL(url).hash.slice(1))})`, `Page did not navigate to ${url}`)
await waitFor(send, `Boolean(document.querySelector(${JSON.stringify(selector)}))`, `Page did not render ${selector}`)
}
const run = async () => {
const { socket, send, exceptions } = await connect()
try {
await send('Page.enable')
await send('Runtime.enable')
await navigate(send, a01Url, '.register-link')
await valueOf(send, "document.querySelector('.register-link').click()")
await waitFor(send, "location.href.includes('/pages/auth/a04-register')", 'A01 registration entry did not open A04')
for (const size of [
{ width: 320, height: 568 },
{ width: 360, height: 616 },
{ width: 360, height: 640 },
{ width: 360, height: 800 },
{ width: 412, height: 915 },
{ width: 480, height: 1040 }
]) {
await send('Emulation.setDeviceMetricsOverride', { ...size, deviceScaleFactor: 1, mobile: true })
await navigate(send, a04Url, '.register-submit')
await waitFor(send, "document.querySelector('.auth-shell__header-image img')?.naturalWidth === 824", `A04 header did not load at ${size.width}x${size.height}`)
const metrics = await valueOf(send, `(() => {
const header = document.querySelector('.auth-shell__header')
const headerImage = document.querySelector('.auth-shell__header-image img')
const paper = document.querySelector('.auth-shell__paper')
const title = document.querySelector('.page-title')
const loginEntry = document.querySelector('.login-entry')
return {
width: document.documentElement.scrollWidth,
documentScrollHeight: Math.max(document.documentElement.scrollHeight, document.body.scrollHeight),
headerBottom: header?.getBoundingClientRect().bottom,
headerImageWidth: headerImage?.getBoundingClientRect().width,
headerImageHeight: headerImage?.getBoundingClientRect().height,
headerNaturalWidth: headerImage?.naturalWidth,
headerNaturalHeight: headerImage?.naturalHeight,
paperTop: paper?.getBoundingClientRect().top,
titleCenter: title ? title.getBoundingClientRect().left + title.getBoundingClientRect().width / 2 : null,
loginEntryBottom: loginEntry?.getBoundingClientRect().bottom + window.scrollY
}
})()`)
assert(metrics.width <= size.width + 1, `A04 has horizontal overflow at ${size.width}x${size.height}`)
assert.deepStrictEqual([metrics.headerNaturalWidth, metrics.headerNaturalHeight], [824, 340], `A04 header asset changed at ${size.width}x${size.height}`)
assert(Math.abs(metrics.headerImageHeight / metrics.headerImageWidth - 340 / 824) < 0.01, `A04 header is distorted at ${size.width}x${size.height}`)
assert(metrics.paperTop >= metrics.headerBottom - 1, `A04 paper overlaps its header at ${size.width}x${size.height}`)
assert(Math.abs(metrics.titleCenter - size.width / 2) <= 1, `A04 title is not centered at ${size.width}x${size.height}: ${metrics.titleCenter}`)
assert(metrics.loginEntryBottom <= metrics.documentScrollHeight + 1, `A04 last action is unreachable at ${size.width}x${size.height}`)
}
await valueOf(send, "document.querySelector('.register-submit').click()")
await waitFor(send, "document.querySelectorAll('.field-error').length === 4", 'A04 empty submit did not show four field errors')
assert(await valueOf(send, "Boolean(document.querySelector('.agreement-error'))"), 'A04 empty submit did not show agreement error')
await valueOf(send, `(() => {
const inputs = document.querySelectorAll('.auth-input input')
const values = ['13800138000', '联调昵称', '1234', 'demo-password', 'demo-password']
inputs.forEach((input, index) => {
input.value = values[index]
input.dispatchEvent(new Event('input', { bubbles: true }))
})
document.querySelector('.agreement-toggle').click()
document.querySelector('.register-submit').click()
})()`)
await waitFor(
send,
"document.querySelector('.app-toast__copy')?.textContent === '当前为本地预览模式,真实认证服务未启用'",
'A04 local preview did not fail closed instead of faking registration success'
)
assert.strictEqual(await valueOf(send, "Boolean(document.querySelector('.verification-layer'))"), false, 'A04 retained the obsolete fake verification layer')
assert.strictEqual(await valueOf(send, "Boolean(document.querySelector('.tac-layer--visible'))"), false, 'A04 opened TAC during registration submission instead of the SMS request phase')
const toastBorderImage = await valueOf(send, "getComputedStyle(document.querySelector('.app-toast')).borderImageSource")
assert(toastBorderImage.includes('a01-scroll-toast-v3.png'), `A04 Toast did not render the v3 nine-slice asset: ${toastBorderImage}`)
await navigate(send, a04Url, '.login-entry__link')
await valueOf(send, "document.querySelector('.login-entry__link').click()")
await waitFor(send, "Boolean(document.querySelector('.login-tab')) && (location.hash === '#/' || location.href.includes('/pages/auth/a01-entry'))", 'A04 login entry did not return to A01')
assert.deepStrictEqual(exceptions, [], `A04 raised browser exceptions: ${exceptions.join('; ')}`)
process.stdout.write('A04-REGISTRATION-RUNTIME-SMOKE PASS\n')
} finally {
try { await send('Emulation.clearDeviceMetricsOverride') } catch (_) {}
socket.close()
}
}
run().catch((error) => {
process.stderr.write(`${error.stack || error.message}\n`)
process.exit(1)
})