Files
dacli/tests/e2e/spike-form-design.spec.ts
T
sswandClaude 35953aa1ee feat(form): 抽取 spike 模拟人类操作能力为 --via=ui 兜底命令
spike (tests/e2e/spike-form-design.spec.ts) 跑通 80%, 暴露 web 设计器
viewFields=0 阻塞 (ViewForm.vue:234). 抽取为 dacli form create --via=ui
作为 API 路径失败时的兜底.

完整路径: formDesign/index.vue:251 dropdown 选视图 → 填 fullName+enCode
→ category (字典) → interfaceId (InterfaceModal) → 保存. 模拟失败时
返回精确诊断 (例如 viewFields=0), 调用方可 fallback 到 API.

Co-Authored-By: Claude <[email protected]>
2026-06-16 18:59:29 +08:00

250 lines
12 KiB
TypeScript

/**
* tests/e2e/spike-form-design.spec.ts
*
* SPIKE: 老老实实在 web 上建一条表单, 记录每步 UI 红框 / 校验 / 数据关系。
*
* 目标: 把 UI 表现 ↔ web 校验代码 (Form.vue + FormGenerator.vue + ColumnDesign) ↔ 后端数据 三者对应。
*
* 步骤:
* 1. 切到 tdd app
* 2. 打开 formDesign 后台入口
* 3. 点"新建" → 选"视图" (实际打开 ViewForm.vue 不是 Form.vue)
* 4. 不填任何字段 → 点"保存" → 记录所有红框必填
* 5. 逐项填字段, 每步截图, 观察校验变化
* 6. 用 dacli 看是否保存
*
* 跑法:
* npx playwright test spike-form-design.spec.ts --project=chromium
*/
import { test, expect } from '@playwright/test'
import { execSync } from 'node:child_process'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const ROOT = resolve(fileURLToPath(import.meta.url), '../../..')
const APP_CODE = 'tdd'
const TS = Date.now().toString(36).slice(-6)
const FINAL_ENCODE = `spike${TS}` // 合法: 字母+数字, 无下划线
const FULLNAME = 'Spike 测试表单'
test.describe.configure({ mode: 'serial' })
test('SPIKE: tdd app 老老实实创建一条 type=4 视图表单', async ({ page }) => {
test.setTimeout(120_000)
// 监听 network
const apiCalls: Array<{ method: string; url: string; status: number; body?: string }> = []
page.on('response', async (resp) => {
const url = resp.url()
if (url.includes('/api/visualdev/') || url.includes('/api/system/DictionaryData') ||
url.includes('/api/system/DataInterface') || url.includes('/api/system/DataSource')) {
let body: string | undefined
try { body = await resp.text() } catch {}
apiCalls.push({ method: resp.request().method(), url: url.replace('http://nginx', ''), status: resp.status(), body: body?.slice(0, 300) })
}
})
execSync(`npx tsx src/cli.ts app login --account=admin --password=123456 --appCode=${APP_CODE}`, {
cwd: ROOT, encoding: 'utf-8',
})
console.log(`[SPIKE] 登录 ${APP_CODE}`)
const listUrl = `/jnpf_app_backend_${APP_CODE}/onlineDev/formDesign`
await page.goto(listUrl)
await page.waitForLoadState('networkidle')
await page.waitForTimeout(2000)
// ===== 点"新建" → 选"视图" =====
await page.locator('button:has-text("新建")').first().click()
await page.locator('.ant-dropdown-menu-item:has-text("视图")').first().click()
await page.waitForSelector('.ant-modal:visible', { timeout: 10_000 })
await page.waitForLoadState('networkidle')
// ===== 步骤 A: 弹窗打开, 不填任何字段, 点"保存" → 收集所有红框 =====
console.log('\n========== 步骤 A: 不填字段, 点保存 (收集必填校验) ==========')
await page.screenshot({ path: 'screenshots/spike-A-empty-form.png', fullPage: true })
// 记录所有红框 label (jnpf .ant-form-item-required)
const requiredLabels = await page.locator('.ant-form-item-required .ant-form-item-label label').allTextContents()
console.log(`[SPIKE] 必填字段: ${JSON.stringify(requiredLabels)}`)
// 点保存
await page.locator('.ant-modal button:has-text("保 存")').first().click()
await page.waitForTimeout(2_000)
await page.screenshot({ path: 'screenshots/spike-A-after-save-empty.png', fullPage: true })
// 收集所有错误提示
const errorTexts = await page.locator('.ant-form-item-explain-error, .ant-form-item-explain').allTextContents()
const errors = errorTexts.map(t => t.trim()).filter(t => t && t.length < 100)
console.log(`[SPIKE] 错误提示: ${JSON.stringify(errors)}`)
// ===== 步骤 B: 填 fullName + enCode, 点保存 =====
console.log('\n========== 步骤 B: 填 fullName + enCode (合法), 点保存 ==========')
await page.locator('.ant-modal input').first().fill(FULLNAME)
await page.locator('.ant-modal input').nth(1).fill(FINAL_ENCODE)
await page.waitForTimeout(500)
await page.screenshot({ path: 'screenshots/spike-B-name-filled.png', fullPage: true })
await page.locator('.ant-modal button:has-text("保 存")').first().click()
await page.waitForTimeout(2_000)
await page.screenshot({ path: 'screenshots/spike-B-after-save.png', fullPage: true })
// 检查弹窗是否还在
const modalStillOpen = await page.locator('.ant-modal:visible').count() > 0
console.log(`[SPIKE] 弹窗状态: ${modalStillOpen ? '仍开 (校验失败)' : '已关闭 (保存成功)'}`)
if (modalStillOpen) {
const errs2 = await page.locator('.ant-form-item-explain-error').allTextContents()
console.log(`[SPIKE] B 步骤剩余错误: ${JSON.stringify(errs2.map(t => t.trim()).filter(Boolean))}`)
} else {
console.log(`[SPIKE] 🎉 步骤 B 保存成功! enCode=${FINAL_ENCODE}`)
}
// ===== 步骤 C: 步骤 B 失败, 看看需要补哪些字段 =====
// 看 select 数 (枚举可选字段, 比如 interfaceId / category / dbLinkId)
if (modalStillOpen) {
console.log('\n========== 步骤 C: 看 select 字段 (必填枚举) ==========')
const selects = await page.locator('.ant-modal .ant-select').count()
console.log(`[SPIKE] 弹窗内 select 数: ${selects}`)
// ===== 步骤 D: 选 category (第 1 个 select) =====
console.log('\n========== 步骤 D: 选 category ==========')
const categorySelect = page.locator('.ant-modal .ant-select').nth(0)
const catBox = await categorySelect.boundingBox()
if (catBox) {
await page.mouse.click(catBox.x + catBox.width / 2, catBox.y + catBox.height / 2)
await page.waitForSelector('.ant-select-dropdown:visible', { timeout: 5_000 })
await page.waitForTimeout(800) // 等选项渲染
// 选第一个 option
const catOpt = page.locator('.ant-select-dropdown:visible .ant-select-item-option').first()
await catOpt.waitFor({ state: 'visible', timeout: 5_000 })
const catText = (await catOpt.textContent())?.trim() || '?'
await catOpt.click()
await page.waitForTimeout(500)
// 验证 select 已显示选中值
const catSelectedText = await categorySelect.locator('.ant-select-selection-item').textContent().catch(() => '')
console.log(`[SPIKE] 选了 category: ${catText} (实际回填: ${catSelectedText?.trim() || '(空)'})`)
} else {
console.log('[SPIKE] category select 无 boundingBox')
}
await page.screenshot({ path: 'screenshots/spike-D-category-selected.png', fullPage: true })
// ===== 步骤 E: 选 interfaceId (第 2 个 select, InterfaceModal 弹窗模式) =====
// 控件特殊: InterfaceModal 渲染成 a-select 但 open:false + @click 触发 AModal
// (不是普通 dropdown)
console.log('\n========== 步骤 E: 选 interfaceId (InterfaceModal 弹窗) ==========')
const interfaceSelect = page.locator('.ant-modal .ant-select').nth(1)
const intBox = await interfaceSelect.boundingBox()
if (intBox) {
// 点 select 触发 AModal (不是 dropdown)
await page.mouse.click(intBox.x + intBox.width / 2, intBox.y + intBox.height / 2)
// 等 AModal (jnpf 的 common-container-modal)
await page.waitForSelector('.common-container-modal:visible, .ant-modal:visible', { timeout: 5_000 })
await page.waitForTimeout(2_000) // 等左侧 tree + 右侧 table 渲染
console.log('[SPIKE] AModal 已弹出')
// 等右侧表格行
const rows = page.locator('.common-container-modal .vxe-body--row')
const rowCount = await rows.count()
console.log(`[SPIKE] 表格行数: ${rowCount}`)
for (let i = 0; i < rowCount; i++) {
const txt = await rows.nth(i).textContent()
console.log(` 行 ${i + 1}: ${txt?.slice(0, 80)}`)
}
// 看每行的 fieldJson (从 window.__JNPF_CACHE__ 或 store 取)
const dataJson = await page.evaluate(() => {
// 尝试拿 interfaceModal 的 row data
const grid = document.querySelector('.common-container-modal .vxe-table')
if (!grid) return 'no grid'
// vxe-table 数据存在内部 _data
return JSON.stringify((window as any).__JNPF_DEBUG__?.interfaceRows?.slice(0, 5) || [])
})
console.log(`[SPIKE] debug 接口 rows: ${dataJson.slice(0, 200)}`)
if (rowCount > 0) {
// 选第一行 (radio)
const radio = page.locator('.common-container-modal .vxe-body--row').first().locator('.ant-radio-input').first()
await radio.click({ force: true })
console.log('[SPIKE] 选了第一行')
// 等"确定"按钮可见再点
const okBtn = page.locator('.common-container-modal .ant-modal-footer button.ant-btn-primary').first()
await okBtn.waitFor({ state: 'visible', timeout: 3_000 })
console.log('[SPIKE] 找到 OK 按钮, 点击')
await okBtn.click({ force: true })
// 等 InterfaceModal 关闭
await page.waitForSelector('.common-container-modal', { state: 'hidden', timeout: 5_000 })
console.log('[SPIKE] InterfaceModal 已关闭')
}
}
await page.waitForTimeout(1_000)
await page.screenshot({ path: 'screenshots/spike-DE-all-filled.png', fullPage: true })
// ===== 步骤 F: 保存 =====
console.log('\n========== 步骤 F: 点保存 ==========')
// 监听 message (toast)
const messages: string[] = []
page.on('console', (msg) => {
const txt = msg.text()
if (txt && !txt.includes('webpack') && !txt.includes('vue')) {
messages.push(`[${msg.type()}] ${txt.slice(0, 200)}`)
}
})
// 监听新出现的 .ant-message
const messagePromise = page.waitForSelector('.ant-message-notice', { timeout: 3_000 }).then(async (el) => {
const txt = await el?.textContent()
return txt?.trim() || ''
}).catch(() => '')
// 找 full-modal header 里的"保 存"按钮
const saveBtn = page.locator('.jnpf-full-modal-header button.ant-btn-primary, .jnpf-full-modal-header button:has-text("保 存")').first()
await saveBtn.click({ force: true })
console.log('[SPIKE] 强制点击 save 按钮')
// 等 message 出现
const msgTxt = await messagePromise
if (msgTxt) {
console.log(`[SPIKE] 弹出 message: ${msgTxt}`)
} else {
console.log('[SPIKE] 未捕获到 message (可能没弹或已消失)')
}
await page.waitForTimeout(2_000)
await page.screenshot({ path: 'screenshots/spike-F-after-save.png', fullPage: true })
// 打印所有 console 消息 (前 20)
console.log(`[SPIKE] console 消息数: ${messages.length}`)
messages.slice(-20).forEach(m => console.log(` ${m}`))
const modalOpen2 = await page.locator('.ant-modal:visible, .jnpf-full-modal:visible').count() > 0
console.log(`[SPIKE] 弹窗状态: ${modalOpen2 ? '仍开 (校验失败)' : '已关闭 (保存成功)'}`)
}
// ===== 验证 dacli list =====
console.log('\n========== 网络请求汇总 ==========')
for (const c of apiCalls.slice(-20)) {
console.log(` [${c.status}] ${c.method} ${c.url}`)
if (c.url.includes('visualdev/Base') && c.method === 'POST') {
console.log(` body: ${c.body}`)
}
}
console.log('\n========== dacli form list 验证 ==========')
const listOutput = execSync(`npx tsx src/cli.ts form list --json`, { cwd: ROOT, encoding: 'utf-8' })
if (listOutput.includes(FINAL_ENCODE)) {
console.log(`[SPIKE] 🎉 dacli list 含 ${FINAL_ENCODE}, 已保存到 tdd app`)
const idMatch = listOutput.match(new RegExp(`"enCode":"${FINAL_ENCODE}"[\\s\\S]*?"id":"([^"]+)"`))
if (idMatch) {
console.log(` 新表单 id: ${idMatch[1]}`)
console.log(` 清理命令: dacli form delete --id=${idMatch[1]} --appCode=${APP_CODE} --force`)
}
} else {
console.log(`[SPIKE] ⚠️ dacli list 不含 ${FINAL_ENCODE}`)
}
expect(listOutput, 'spike 表单应保存到 tdd app').toContain(FINAL_ENCODE)
})