Files
jiapuapp/tests/a05-reset-password-runtime-smoke.js
T
2026-07-23 08:24:07 +08:00

173 lines
9.3 KiB
JavaScript

const assert = require('assert')
const a01Url = 'http://localhost:5173/#/pages/auth/a01-entry'
const a05Url = 'http://localhost:5173/#/pages/auth/a05-reset-password'
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 setInputs = async (send, values) => {
for (const [index, value] of values.entries()) {
await valueOf(send, `(() => {
const input = document.querySelectorAll('.auth-input input')[${index}]
input.value = ${JSON.stringify(value)}
input.dispatchEvent(new Event('input', { bubbles: true }))
})()`)
await sleep(30)
}
}
const run = async () => {
const { socket, send, exceptions } = await connect()
try {
await send('Page.enable')
await send('Runtime.enable')
await navigate(send, a01Url, '.login-tab')
await valueOf(send, "document.querySelectorAll('.login-tab')[0].click()")
await waitFor(send, "Boolean(document.querySelector('.forgot-password'))", 'A01 password state did not expose forgot-password entry')
await valueOf(send, "document.querySelector('.forgot-password').click()")
await waitFor(send, "location.href.includes('/pages/auth/a05-reset-password')", 'A01 forgot-password entry did not open A05')
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, a05Url, '.reset-submit')
await waitFor(send, "document.querySelector('.auth-shell__header-image img')?.naturalWidth === 824", `A05 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, `A05 has horizontal overflow at ${size.width}x${size.height}`)
assert.deepStrictEqual([metrics.headerNaturalWidth, metrics.headerNaturalHeight], [824, 340], `A05 header asset changed at ${size.width}x${size.height}`)
assert(Math.abs(metrics.headerImageHeight / metrics.headerImageWidth - 340 / 824) < 0.01, `A05 header is distorted at ${size.width}x${size.height}`)
assert(metrics.paperTop >= metrics.headerBottom - 1, `A05 paper overlaps its header at ${size.width}x${size.height}`)
assert(Math.abs(metrics.titleCenter - size.width / 2) <= 1, `A05 title is not centered at ${size.width}x${size.height}: ${metrics.titleCenter}`)
assert(metrics.loginEntryBottom <= metrics.documentScrollHeight + 1, `A05 last action is unreachable at ${size.width}x${size.height}`)
}
await valueOf(send, "document.querySelector('.get-code').click()")
await waitFor(send, "Boolean(document.querySelector('.field-error'))", 'A05 invalid phone did not show inline error')
await setInputs(send, ['13800138000', '', '', ''])
await valueOf(send, "document.querySelector('.get-code').click()")
await waitFor(
send,
"document.querySelector('.app-toast__copy')?.textContent === '当前为本地预览模式,真实认证服务未启用'",
'A05 local preview did not fail closed before requesting TAC'
)
assert.strictEqual(await valueOf(send, "Boolean(document.querySelector('.verification-layer'))"), false, 'A05 retained the obsolete fake verification layer')
assert.strictEqual(await valueOf(send, "Boolean(document.querySelector('.tac-layer--visible'))"), false, 'A05 opened TAC without a remote requirement response')
assert.strictEqual(await valueOf(send, "document.querySelector('.auth-input input').value"), '13800138000', 'A05 unavailable remote verification cleared the form')
assert.strictEqual(await valueOf(send, "document.querySelector('.get-code').textContent.trim()"), '获取验证码', 'A05 faked a requested-code state without TAC and the SMS service')
await valueOf(send, "document.querySelector('.reset-submit').click()")
await waitFor(send, "document.querySelectorAll('.field-error').length === 3", 'A05 incomplete submit did not show three remaining field errors')
await setInputs(send, ['13800138000', '1234', 'new-password', 'different-password'])
await sleep(100)
await valueOf(send, "document.querySelector('.reset-submit').click()")
await sleep(100)
const mismatchState = await valueOf(send, `({
values: Array.from(document.querySelectorAll('.auth-input input')).map((item) => item.value),
errors: Array.from(document.querySelectorAll('.field-error')).map((item) => item.textContent),
success: document.querySelector('.app-dialog__title')?.textContent === '密码已重设'
})`)
assert(mismatchState.errors.some((message) => message.includes('不一致')), `A05 mismatched passwords did not show inline error: ${JSON.stringify(mismatchState)}`)
await setInputs(send, ['13800138000', '1234', 'new-password', 'new-password'])
await sleep(100)
await valueOf(send, "document.querySelector('.reset-submit').click()")
await waitFor(
send,
"document.querySelector('.app-toast__copy')?.textContent === '当前为本地预览模式,真实认证服务未启用'",
'A05 local preview did not reject a fake password reset'
)
assert.strictEqual(await valueOf(send, "document.querySelector('.app-dialog__title')?.textContent === '密码已重设'"), false, 'A05 showed reset success without a successful remote response')
assert.deepStrictEqual(
await valueOf(send, "Array.from(document.querySelectorAll('.auth-input input')).map((item) => item.value)"),
['13800138000', '1234', 'new-password', 'new-password'],
'A05 cleared the form after a rejected remote reset'
)
assert.deepStrictEqual(exceptions, [], `A05 raised browser exceptions: ${exceptions.join('; ')}`)
process.stdout.write('A05-RESET-PASSWORD-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)
})