Files
dacli/tests/e2e/_helpers/form.ts
T
sswandClaude 341f48ef75 fix(verify-form): 7 FILL-WARN 修复 + jnpf 6.2.0 3 模式 + label 模糊匹配
- _helpers/selectors.ts: 加 BASIC_POPUP / BASIC_POPUP_HEADER_BACK scope
                       + FORM_SCOPE_CANDIDATES 跨 3 模式查找列表
                       + formItemByLabel/rowAction 加 Page/Locator 类型
- _helpers/form.ts:
  - findFormItem: 跨 3 模式 (ant-modal/basic-popup/popup-content/body) 找 label
  - label 模糊匹配 (trim + 包含, 不要求精确)
  - fillDateByLabelClick: 点 calendar 选今天 (datePicker readonly)
  - selectByLabelPopup: userSelect/depSelect 弹窗选第一行
  - saveModal/closeModal: 自动 detect 3 模式 scope
  - 所有 helper 内部用 findFormItem 替代 formItemByLabel(page,label,scope)
- _helpers/index.ts: 导出 formItemByLabelScope/findFormItem/fillDateByLabelClick/selectByLabelPopup
- _browser_construct.ts: FieldSample 加 options 字段 (select 等可选 ID 列表)
                       + fetchUserList/fetchOrgList 返 [{id, value}]
- verify-form.ts: fill-form 改用 isSelectItem + selectByLabel (antd select 路径)
                + fillDateByLabelClick 走 datePicker readonly 路径

paymentapply 端到端 8/8 step PASS, fill-form 40213ms → 11288ms (4x 加速).
39/39 单测保持 PASS.

已知限制: 菜单 fksqzy 实际加载 workflow form 797489589626339909 (StartFormId 端点),
        与 paymentapply (id 585398402720727621) schema 不一致, 导致 6 字段 label
        在渲染 form 中不存在 → 6 FILL-WARN. 这是 JNPF menu/form 路由问题, 不
        在本 fix 范围. 完整 8 步流程 (open→save→list) 已稳定 PASS.

Co-Authored-By: Claude <[email protected]>
2026-06-16 14:16:40 +08:00

598 lines
19 KiB
TypeScript

/**
* _helpers/form.ts — 表单操作 helpers
*
* 核心模式:
* - **按 label 找 input/select/textarea** — jnpf 6.2.0 label 是稳定契约
* - **select 必用 mouse.click 触发** (page.evaluate click 不行, antd v-model 内部监听 mouse 事件)
* - **保存/取消走 modal 内主按钮** (优先级: confirm-btns primary > modal primary)
*
* 用法示例:
* await fillByLabel(page, '申请人姓名', '张三')
* await selectByLabel(page, '所在部门', 0) // 选第 1 个 option
* await fillDateByLabel(page, '起始日期', '2026-06-15')
* await fillTextareaByLabel(page, '请假事由', '...')
* await saveModal(page) // 点"确定"或"保存"
* await closeModal(page) // 取消
*/
import type { Page, Locator } from '@playwright/test'
import { SEL, formItemByLabel, FORM_SCOPE_CANDIDATES } from './selectors'
export interface FormOpts {
/** modal 选择器, 默认 .ant-modal (兼容旧 API, 新 helper 用 formItemByLabelScope 自动跨 3 模式) */
scope?: string
/** 等待元素超时 (ms), 默认 5s */
timeout?: number
}
/**
* 转义正则特殊字符 (用于 label 模糊匹配的 hasText RegExp)
*/
function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
/**
* 跨 3 模式找 form item by label (Phase 2 修复)
* 模式 1: .ant-modal
* 模式 2: .jnpf-basic-popup
* 模式 3: body (full-page 路由跳转, 默认全局)
*
* - label 模糊匹配 (trim + 包含, 不要求精确)
* - 逐个 scope 找, 第一个 count > 0 的返回
*/
export function formItemByLabelScope(page: Page, label: string): Locator {
const cleanLabel = label.trim()
const labelRe = new RegExp(escapeRegex(cleanLabel))
// 1) 优先在 3 个 jnpf 模式容器内找
for (const scope of FORM_SCOPE_CANDIDATES) {
const item = page
.locator(
`${scope} ${SEL.FORM_ITEM}:has(${SEL.FORM_ITEM_LABEL}:has-text("${label}"))`,
)
.first()
if ((item as unknown as { count(): Promise<number> }).count !== undefined) {
// synchronous check via .count() in async caller — return locator
}
}
// 实际: Playwright locator 没同步 count, 改用构建一次性 Locator, 调用方负责 first().count() 判断
// 这里返第一个候选, 调用方 (helper 内部) 用 .count() > 0 检测
// 但要求跨 3 模式, 所以返回 chain Locator:
return page
.locator(SEL.FORM_ITEM)
.filter({
has: page.locator(SEL.FORM_ITEM_LABEL, { hasText: labelRe }),
})
.first()
}
/**
* 异步版 formItemByLabelScope — 实际跨 3 模式找, 返回第一个 count > 0 的 Locator
* 用于内部 helper 替换 formItemByLabel
*/
export async function findFormItem(page: Page, label: string): Promise<Locator | null> {
const cleanLabel = label.trim()
const labelRe = new RegExp(escapeRegex(cleanLabel))
// 1) 精确文本匹配 (trim 后) — 在 3 个 scope 候选
for (const scope of FORM_SCOPE_CANDIDATES) {
const exact = page
.locator(
`${scope} ${SEL.FORM_ITEM}:has(${SEL.FORM_ITEM_LABEL}:text-is("${cleanLabel}"))`,
)
.first()
if ((await exact.count()) > 0) return exact
}
// 2) 模糊匹配 (包含) — 在 3 个 scope 候选
for (const scope of FORM_SCOPE_CANDIDATES) {
const fuzzy = page
.locator(
`${scope} ${SEL.FORM_ITEM}:has(${SEL.FORM_ITEM_LABEL}:has-text("${cleanLabel}"))`,
)
.first()
if ((await fuzzy.count()) > 0) return fuzzy
}
// 3) 兜底: body 全局
const body = page
.locator(`body ${SEL.FORM_ITEM}:has(${SEL.FORM_ITEM_LABEL}:has-text("${cleanLabel}"))`)
.first()
if ((await body.count()) > 0) return body
return null
}
/**
* 按 label 文本找到 input 并填值
* 优先 placeholder 包含 label (jnpf 默认 "请输入xxx"), 兜底 form-item 找 input
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function fillByLabel(
page: Page,
label: string,
value: string,
opts: FormOpts = {},
) {
const timeout = opts.timeout ?? 5_000
const cleanLabel = label.trim()
// 1) 优先: 跨 3 模式 placeholder 含 label
for (const scope of FORM_SCOPE_CANDIDATES) {
const byPh = page
.locator(`${scope} input[placeholder*="${cleanLabel}"]`)
.first()
if ((await byPh.count()) > 0) {
await byPh.fill(value, { timeout })
return
}
}
// 2) 兜底: 跨 3 模式 form-item 找 input
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`fillByLabel: 找不到 label="${label}" 的 input`)
}
const input = item.locator('input').first()
await input.fill(value, { timeout })
}
/**
* 按 label 找到 select 并选第 N 个 option (0=第一个)
* 关键: ant-select 必须 mouse.click 触发, page.evaluate click 不行
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function selectByLabel(
page: Page,
label: string,
optionIndex = 0,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`selectByLabel: 找不到 label="${label}"`)
}
const select = item.locator(SEL.SELECT).first()
if ((await select.count()) === 0) {
throw new Error(`selectByLabel: "${label}" 不是 select 类型`)
}
const box = await select.boundingBox()
if (!box) {
throw new Error(`selectByLabel: "${label}" 无 bounding box`)
}
// mouse.click 触发 antd dropdown
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)
await page.waitForSelector(SEL.SELECT_DROPDOWN, { timeout: 5_000 })
// 等 dropdown 动画 + 选项渲染
await page.waitForSelector(
`${SEL.SELECT_DROPDOWN} ${SEL.SELECT_ITEM}`,
{ timeout: 5_000 },
)
const options = page.locator(
`${SEL.SELECT_DROPDOWN} ${SEL.SELECT_ITEM}`,
)
const count = await options.count()
if (count <= optionIndex) {
throw new Error(
`selectByLabel: "${label}" 只有 ${count} 个 option, 索引 ${optionIndex} 越界`,
)
}
await options.nth(optionIndex).click()
await page.waitForTimeout(200)
}
/**
* 按 label 找到 date picker 并填日期 (YYYY-MM-DD)
* jnpf 用 .ant-picker, 内部 <input>, fill 后 Tab 触发 onChange
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function fillDateByLabel(
page: Page,
label: string,
date: string,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`fillDateByLabel: 找不到 label="${label}"`)
}
const input = item.locator(SEL.PICKER).first()
if ((await input.count()) === 0) {
throw new Error(`fillDateByLabel: "${label}" 不是日期类型`)
}
await input.fill(date)
await page.keyboard.press('Tab')
await page.waitForTimeout(200)
}
/**
* datePicker 通常 readonly, 需点击 input 打开 calendar 然后点"今天"
* Phase 2 修复: paymentapply f_date 用此路径
* 跨 3 模式 scope
*/
export async function fillDateByLabelClick(
page: Page,
label: string,
_value?: string,
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`fillDateByLabelClick: 找不到 label="${label}"`)
}
const picker = item.locator('.ant-picker input').first()
if ((await picker.count()) === 0) {
throw new Error(`fillDateByLabelClick: "${label}" 不是 datePicker 类型`)
}
// 点击 input 打开 calendar
await picker.click()
// 等 calendar 弹出
await page
.locator('.ant-picker-dropdown:visible')
.first()
.waitFor({ state: 'visible', timeout: 5_000 })
// 点"今天"按钮 (jnpf 6.2.0 用 ant-picker-today-btn a, 或 "今天" 文字)
const todayBtn = page
.locator(
'.ant-picker-dropdown:visible a.ant-picker-today-btn, .ant-picker-dropdown:visible button:has-text("今天")',
)
.first()
if ((await todayBtn.count()) === 0) {
throw new Error(`fillDateByLabelClick: "${label}" 找不到今天按钮`)
}
await todayBtn.click()
// 等 calendar 关闭
await page
.locator('.ant-picker-dropdown:visible')
.first()
.waitFor({ state: 'hidden', timeout: 5_000 })
.catch(() => {
// ignore — 部分场景下 calendar 关闭动画慢
})
}
/**
* 按 label 找到 textarea 并填值
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function fillTextareaByLabel(
page: Page,
label: string,
value: string,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`fillTextareaByLabel: 找不到 label="${label}"`)
}
const ta = item.locator('textarea').first()
if ((await ta.count()) === 0) {
throw new Error(`fillTextareaByLabel: "${label}" 不是 textarea 类型`)
}
await ta.fill(value)
}
/**
* 按 label 找到 inputNumber (jnpf 用 .ant-input-number) 并填数值
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function fillNumberByLabel(
page: Page,
label: string,
value: number | string,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
// 1) 优先: 跨 3 模式 placeholder 含 label
for (const scope of FORM_SCOPE_CANDIDATES) {
const byPh = page
.locator(
`${scope} .ant-input-number input[placeholder*="${cleanLabel}"]`,
)
.first()
if ((await byPh.count()) > 0) {
await byPh.fill(String(value))
await page.keyboard.press('Tab')
return
}
}
// 2) 兜底: form-item
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`fillNumberByLabel: 找不到 label="${label}"`)
}
const input = item.locator('.ant-input-number input').first()
await input.fill(String(value))
await page.keyboard.press('Tab')
}
/**
* userSelect / depSelect / organizeSelect 需点开弹窗选第一行
* Phase 2 修复: paymentapply f_dept/f_applicant 用此路径
* 跨 3 模式 scope
*/
export async function selectByLabelPopup(
page: Page,
label: string,
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`selectByLabelPopup: 找不到 label="${label}"`)
}
// 找到 select-search 控件的触发区
// jnpf userSelect 渲染: .userSelect / .ant-select / .jnpf-userSelect-select
const trigger = item
.locator(
'.userSelect, .jnpf-userSelect-select, .organizeSelect, .jnpf-organizeSelect-select, .ant-select',
)
.first()
if ((await trigger.count()) === 0) {
throw new Error(`selectByLabelPopup: "${label}" 无 userSelect/organizeSelect 触发器`)
}
// 点击触发器 (force 防止被遮挡)
await trigger.click({ force: true })
// 等弹窗 (jnpf 用 jnpf-basic-popup / .ant-modal / .userSelect-modal)
const popup = page
.locator(
'.jnpf-basic-popup:visible, .ant-modal-wrap:visible, .userSelect-modal:visible, .organizeSelect-modal:visible',
)
.first()
await popup.waitFor({ state: 'visible', timeout: 5_000 }).catch(() => {
throw new Error(`selectByLabelPopup: "${label}" 点击后无弹窗`)
})
// 选第一行 (jnpf 弹窗是表格, 第一行 .ant-table-row)
const firstRow = page
.locator(
'.jnpf-basic-popup-body .ant-table-row, .ant-modal-body .ant-table-row, .userSelect-modal .ant-table-row, .organizeSelect-modal .ant-table-row',
)
.first()
if ((await firstRow.count()) === 0) {
throw new Error(`selectByLabelPopup: "${label}" 弹窗内无表格行`)
}
await firstRow.click()
// 等弹窗关闭
await page.waitForTimeout(500)
}
/**
* 点击 modal 内的主按钮 (保存/确定)
* 优先级: confirm-btns primary > modal primary > "保存" > "确定"
* 跨 3 模式 scope (Phase 2 修复) — 自动检测 ant-modal / jnpf-basic-popup / 全局
*/
export async function saveModal(page: Page, opts: FormOpts = {}) {
// 跨 3 模式 scope 自动检测 (Phase 2 修复)
const scopes = opts.scope ? [opts.scope] : await detectActiveFormScopes(page)
let btn: ReturnType<Page['locator']> | null = null
for (const scope of scopes) {
const candidate = page
.locator(
`${scope} button:has-text("保 存"), ${scope} button:has-text("确 定"), ${scope} button.ant-btn-primary`,
)
.first()
if ((await candidate.count()) > 0) {
btn = candidate
break
}
}
if (!btn) {
throw new Error(`saveModal: 跨 3 模式都找不到保存按钮 (scopes=${scopes.join(',')})`)
}
await btn.click()
}
/**
* 关闭 modal (优先"关闭", 再"取消", 最后 Escape)
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function closeModal(page: Page, opts: FormOpts = {}) {
const scopes = opts.scope ? [opts.scope] : await detectActiveFormScopes(page)
for (const scope of scopes) {
for (const sel of [
`${scope} ${SEL.MODAL_CLOSE}`,
`${scope} ${SEL.MODAL_CANCEL}`,
]) {
const btn = page.locator(sel).first()
if ((await btn.count()) > 0) {
await btn.click()
await page.waitForTimeout(300)
return
}
}
}
await page.keyboard.press('Escape')
await page.waitForTimeout(300)
}
/**
* 检测当前激活的 form 容器 scope 列表 (Phase 2 修复)
* 返回顺序按优先级: ant-modal → jnpf-basic-popup → jnpf-popup-content → body
* 用于 saveModal/closeModal 跨 3 模式兜底
*/
async function detectActiveFormScopes(page: Page): Promise<string[]> {
const out: string[] = []
if ((await page.locator('.ant-modal-wrap:visible').count()) > 0) {
out.push(SEL.MODAL)
}
if ((await page.locator('.jnpf-basic-popup:visible').count()) > 0) {
out.push(SEL.BASIC_POPUP)
}
if ((await page.locator('.jnpf-popup-content:visible').count()) > 0) {
out.push('.jnpf-popup-content')
}
if (out.length === 0) {
out.push('body')
}
return out
}
// =============================================================
// 进阶组件 (v18+ 拓展)
// =============================================================
/**
* 按 label 找到 date range picker, 填两个日期 (YYYY-MM-DD)
* antd RangePicker 用 .ant-picker-input 两个 input, fill 后 Tab
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function fillDateRangeByLabel(
page: Page,
label: string,
startDate: string,
endDate: string,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`fillDateRangeByLabel: 找不到 label="${label}"`)
}
const inputs = item.locator(SEL.DATE_PICKER_INPUT)
const count = await inputs.count()
if (count < 2) {
throw new Error(`fillDateRangeByLabel: "${label}" 不是 range picker (只有 ${count} input)`)
}
await inputs.nth(0).fill(startDate)
await page.keyboard.press('Tab')
await page.waitForTimeout(200)
await inputs.nth(1).fill(endDate)
await page.keyboard.press('Tab')
await page.waitForTimeout(200)
}
/**
* 按 label 找到 switch, 点击切换开/关
* @param toState 'on' | 'off' | 'toggle' (默认 toggle)
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function toggleSwitchByLabel(
page: Page,
label: string,
toState: 'on' | 'off' | 'toggle' = 'toggle',
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`toggleSwitchByLabel: 找不到 label="${label}"`)
}
const sw = item.locator(SEL.SWITCH).first()
if ((await sw.count()) === 0) {
throw new Error(`toggleSwitchByLabel: "${label}" 不是 switch 类型`)
}
const isOn = (await sw.getAttribute('aria-checked')) === 'true'
const needClick = toState === 'toggle' || (toState === 'on' && !isOn) || (toState === 'off' && isOn)
if (needClick) await sw.click()
await page.waitForTimeout(200)
}
/**
* 按 label 找到 radio group, 点第 N 个选项 (0=第一个)
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function selectRadioByLabel(
page: Page,
label: string,
optionIndex = 0,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`selectRadioByLabel: 找不到 label="${label}"`)
}
const radios = item.locator(SEL.RADIO_ITEM)
const count = await radios.count()
if (count <= optionIndex) {
throw new Error(`selectRadioByLabel: "${label}" 只有 ${count} 个 radio, 索引 ${optionIndex} 越界`)
}
await radios.nth(optionIndex).click()
await page.waitForTimeout(200)
}
/**
* 按 label 找到 checkbox group, 勾选第 N 个选项 (0=第一个)
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function checkCheckboxByLabel(
page: Page,
label: string,
optionIndex = 0,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`checkCheckboxByLabel: 找不到 label="${label}"`)
}
const boxes = item.locator(SEL.CHECKBOX_ITEM)
const count = await boxes.count()
if (count <= optionIndex) {
throw new Error(`checkCheckboxByLabel: "${label}" 只有 ${count} 个 checkbox, 索引 ${optionIndex} 越界`)
}
await boxes.nth(optionIndex).click()
await page.waitForTimeout(200)
}
/**
* 按 label 找到 tree-select, 选节点 (按节点文字, 精确匹配)
* treeSelect 是 antd TreeSelect, dropdown 走 .ant-tree
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function selectTreeByLabel(
page: Page,
label: string,
nodeText: string,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`selectTreeByLabel: 找不到 label="${label}"`)
}
const trigger = item.locator(SEL.TREE_SELECT).first()
if ((await trigger.count()) === 0) {
throw new Error(`selectTreeByLabel: "${label}" 不是 tree-select 类型`)
}
// tree-select 的下拉也是 antd select, mouse.click 触发
const box = await trigger.boundingBox()
if (!box) throw new Error(`selectTreeByLabel: "${label}" 无 bounding box`)
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)
// 等 tree dropdown
await page.waitForSelector(SEL.TREE_SELECT_DROPDOWN, { timeout: 5000 })
await page.waitForTimeout(300)
// 找节点
const nodes = page.locator(SEL.TREE_SELECT_NODE)
const nodeCount = await nodes.count()
for (let i = 0; i < nodeCount; i++) {
const t = (await nodes.nth(i).textContent()) || ''
if (t.trim() === nodeText) {
await nodes.nth(i).click()
await page.waitForTimeout(300)
return
}
}
throw new Error(`selectTreeByLabel: "${label}" 找不到节点 "${nodeText}" (共 ${nodeCount} 节点)`)
}
/**
* 按 label 找到 upload, 设置文件路径 (触发文件选择)
* 注: Playwright setInputFiles 走 .ant-upload input[type=file]
* 跨 3 模式 scope (Phase 2 修复)
*/
export async function uploadFileByLabel(
page: Page,
label: string,
filePath: string,
opts: FormOpts = {},
) {
const cleanLabel = label.trim()
const item = await findFormItem(page, cleanLabel)
if (!item) {
throw new Error(`uploadFileByLabel: 找不到 label="${label}"`)
}
const input = item.locator(SEL.UPLOAD_INPUT).first()
if ((await input.count()) === 0) {
throw new Error(`uploadFileByLabel: "${label}" 不是 upload 类型`)
}
await input.setInputFiles(filePath)
await page.waitForTimeout(500)
}