Files
jiapuapp/tests/g03-create-flow-runtime-smoke.js
T
2026-07-23 08:24:07 +08:00

180 lines
8.8 KiB
JavaScript

const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))
const connect = async () => {
const pages = await (await fetch('http://127.0.0.1:9222/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 localhost:5173 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 setInput = async (send, index, value) => {
await waitFor(
send,
`Boolean(document.querySelectorAll('.flow-fields input')[${index}])`,
`G03 input ${index} did not render`
)
const expression = `(() => {
const input = document.querySelectorAll('.flow-fields input')[${index}]
if (!input) return false
input.value = ${JSON.stringify(value)}
input.dispatchEvent(new Event('input', { bubbles: true }))
return true
})()`
if (!await valueOf(send, expression)) throw new Error(`Could not fill G03 input ${index}`)
}
const origin = process.argv[2] || 'http://localhost:5173'
const g03Path = '/pages/genealogy/g03-create-genealogy'
let navigationId = 0
const openG03 = async (send, query = '') => {
navigationId += 1
const url = `${origin}/?g03Audit=${navigationId}#${g03Path}${query}`
await send('Page.navigate', { url })
await waitFor(send, `location.href === ${JSON.stringify(url)}`, `G03 navigation failed: ${query || 'default'}`)
}
const openDefaultG03 = async (send) => {
await openG03(send)
await waitFor(send, "Boolean(document.querySelector('.create-flow-panel .flow-rule'))", 'Default G03 creation step did not render')
}
const advanceToAncestor = async (send, name = '自动验证汤氏家谱') => {
await setInput(send, 0, '汤')
await setInput(send, 1, name)
await setInput(send, 2, '敦本堂')
await setInput(send, 3, '河南·洛阳')
await valueOf(send, "document.querySelector('.flow-primary-action')?.click()")
await waitFor(send, "Boolean(document.querySelector('.duplicate-reminder-layer'))", 'G03 did not show the duplicate reminder')
await valueOf(send, `(() => {
window.__g03SubmitTimerCount = 0
window.__g03OriginalSetTimeout = window.setTimeout
window.setTimeout = (callback, delay, ...args) => {
if (delay === 320) window.__g03SubmitTimerCount += 1
return window.__g03OriginalSetTimeout(callback, delay, ...args)
}
return true
})()`)
await valueOf(send, "(() => { const action = document.querySelector('.duplicate-reminder__confirm'); action.click(); action.click(); return true })()")
await setInput(send, 1, '失败')
await waitFor(send, "Boolean(document.querySelector('.intro-field'))", 'G03 did not advance to the same-page ancestor step')
const timerCount = await valueOf(send, 'window.__g03SubmitTimerCount')
await valueOf(send, 'window.setTimeout = window.__g03OriginalSetTimeout; delete window.__g03OriginalSetTimeout')
if (timerCount !== 1) throw new Error(`G03 duplicate confirmation created ${timerCount} submit timers`)
if (await valueOf(send, "location.hash.includes('step=ancestor')")) {
throw new Error('G03 leaked its internal ancestor step into the route')
}
}
const run = async () => {
const { socket, send, exceptions } = await connect()
try {
await send('Page.enable')
await send('Runtime.enable')
// 步骤一:空表单、创建失败和短暂提交态都由真实控件触发,避免旧截图助手伪装成功能测试。
await openDefaultG03(send)
await valueOf(send, "document.querySelector('.flow-primary-action')?.click()")
await waitFor(send, "document.querySelectorAll('.field-error').length === 3", 'G03 create step did not report all required fields')
await setInput(send, 0, '汤')
await setInput(send, 1, '失败')
await setInput(send, 3, '河南·洛阳')
await valueOf(send, "document.querySelector('.flow-primary-action')?.click()")
await waitFor(send, "Boolean(document.querySelector('.duplicate-reminder-layer'))", 'G03 failure case did not show the duplicate reminder')
await valueOf(send, "document.querySelector('.duplicate-reminder__confirm').click()")
await waitFor(send, "document.querySelector('.flow-primary-action__copy')?.textContent.includes('正在创建')", 'G03 create step did not expose its submitting state')
await waitFor(send, "Boolean(document.querySelector('.flow-error'))", 'G03 simulated create failure did not render')
// 步骤二:只允许从同页第一步进入首代人物,重复确认不能产生第二个提交定时器。
await openDefaultG03(send)
await advanceToAncestor(send, '首代失败验证家谱')
await valueOf(send, "document.querySelector('.flow-primary-action')?.click()")
await waitFor(send, "Boolean(document.querySelector('.field-error'))", 'G03 ancestor step did not validate the required name')
await setInput(send, 0, '失败')
await valueOf(send, "document.querySelector('.flow-primary-action')?.click()")
await setInput(send, 0, '提交后改名')
await waitFor(send, "document.querySelector('.flow-primary-action__copy')?.textContent.includes('正在保存')", 'G03 ancestor step did not expose its submitting state')
await waitFor(send, "Boolean(document.querySelector('.flow-error'))", 'G03 simulated ancestor failure did not render')
// 步骤三:完整成功路径仍需从立谱、重复提醒、首代保存一路进入家谱总览。
await openDefaultG03(send)
await advanceToAncestor(send)
await setInput(send, 0, '汤始祖')
await sleep(100)
await valueOf(send, "document.querySelector('.flow-primary-action')?.click()")
await setInput(send, 0, '失败')
await waitFor(send, "Boolean(document.querySelector('.flow-success-layer'))", 'Saving the first ancestor did not show the custom success result')
await valueOf(send, "document.querySelector('.flow-success-dialog__action').click()")
await waitFor(send, "location.href.includes('/pages/genealogy/g05-genealogy-overview?genealogyId=local-created-')", 'Saving the first ancestor did not open a unique local G05 preview')
await waitFor(send, "Boolean(document.querySelector('.overview-public'))", 'G03 local preview did not render in G05')
const previewText = await valueOf(send, "document.querySelector('.overview-public')?.textContent")
for (const expected of ['自动验证汤氏家谱', '汤氏', '敦本堂', '河南·洛阳', '汤始祖', '仅成员可见']) {
if (!previewText.includes(expected)) throw new Error(`G03 local preview lost submitted field: ${expected}`)
}
await openDefaultG03(send)
if (await valueOf(send, "Boolean(document.querySelector('.intro-field'))")) {
throw new Error('Default G03 must not render the ancestor step')
}
for (const size of [{ width: 320, height: 568 }, { width: 360, height: 800 }, { width: 412, height: 915 }]) {
await send('Emulation.setDeviceMetricsOverride', { ...size, deviceScaleFactor: 1, mobile: true })
await openDefaultG03(send)
const width = await valueOf(send, 'document.documentElement.scrollWidth')
if (width > size.width + 1) throw new Error(`G03 has horizontal overflow at ${size.width}x${size.height}`)
}
if (exceptions.length) throw new Error(`G03 raised browser exceptions: ${exceptions.join('; ')}`)
process.stdout.write('G03-CREATE-FLOW-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)
})