v17: JNPF 浏览器验证标准库 (_helpers/) + p16 重构

标准库 (dacli/tests/e2e/_helpers/, 6 文件 ~800 行):
- selectors.ts: JNPF 6.2.0 通用选择器常量 (SEL/formItemByLabel/rowAction)
- wait.ts: 智能等待 (waitSpaReady/waitTableReady/waitFormModalReady/waitRowCountChange)
  不用 networkidle, 用具体元素 selector, 默认 15s (vs 30s networkidle)
- nav.ts: 菜单导航 (clickMenu 精确匹配 + expandCategory)
- form.ts: 表单操作 (fillByLabel/selectByLabel/fillDateByLabel/fillTextareaByLabel/
  fillNumberByLabel/saveModal/closeModal)
- table.ts: vxe-table 操作 (countRows/findRow/clickRowAction/getTotalText/clickAdd)
- modal.ts: 模态框 (waitOpen/waitClose/getErrors/isOpen/getTitle)
- index.ts: 聚合导出
- auth.ts: 已存在 (login + storageState 6h TTL)

p16 spec 重构:
- tests/e2e/p16-ui-real-crud.spec.ts: 226 → 180 行 (-20%)
- 用 _helpers 替代内联 selector, 智能等待替代 networkidle
- typecheck 通过

已知问题 (与重构无关):
- tds_leave 是 webType=1 (仅表单), 无 vxe-table 列表, p16 1st test 失败
- 原版 p16 同样 fail — 测试数据配置问题, 不是 refactor 引入

后续 (Python 镜像 + tds_leave webType 修复) 留 task #22
This commit is contained in:
ssw committed 2026-06-15 13:05:39 +08:00
1 parent 44b4c88fff
commit 7cc1fb62bc
8 files changed
+770 -150

No files matched your search

+214
View File
@@ -0,0 +1,214 @@
/**
* _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 } from '@playwright/test'
import { SEL, formItemByLabel } from './selectors'
export interface FormOpts {
/** modal 选择器, 默认 .ant-modal */
scope?: string
/** 等待元素超时 (ms), 默认 5s */
timeout?: number
}
/**
* 按 label 文本找到 input 并填值
* 优先 placeholder 包含 label (jnpf 默认 "请输入xxx"), 兜底 form-item 找 input
*/
export async function fillByLabel(
page: Page,
label: string,
value: string,
opts: FormOpts = {},
) {
const scope = opts.scope ?? SEL.MODAL
const timeout = opts.timeout ?? 5_000
// 1) 优先: placeholder 含 label
const byPh = page
.locator(`${scope} input[placeholder*="${label}"]`)
.first()
if ((await byPh.count()) > 0) {
await byPh.fill(value, { timeout })
return
}
// 2) 兜底: 找含 label 的 form-item 内的 input
const item = formItemByLabel(page, label, scope).first()
if ((await item.count()) === 0) {
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 不行
*/
export async function selectByLabel(
page: Page,
label: string,
optionIndex = 0,
opts: FormOpts = {},
) {
const scope = opts.scope ?? SEL.MODAL
const item = formItemByLabel(page, label, scope).first()
if ((await item.count()) === 0) {
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
*/
export async function fillDateByLabel(
page: Page,
label: string,
date: string,
opts: FormOpts = {},
) {
const scope = opts.scope ?? SEL.MODAL
const item = formItemByLabel(page, label, scope).first()
if ((await item.count()) === 0) {
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)
}
/**
* 按 label 找到 textarea 并填值
*/
export async function fillTextareaByLabel(
page: Page,
label: string,
value: string,
opts: FormOpts = {},
) {
const scope = opts.scope ?? SEL.MODAL
const item = formItemByLabel(page, label, scope).first()
if ((await item.count()) === 0) {
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) 并填数值
*/
export async function fillNumberByLabel(
page: Page,
label: string,
value: number | string,
opts: FormOpts = {},
) {
const scope = opts.scope ?? SEL.MODAL
// 优先 placeholder 含 label
const byPh = page
.locator(
`${scope} .ant-input-number input[placeholder*="${label}"]`,
)
.first()
if ((await byPh.count()) > 0) {
await byPh.fill(String(value))
await page.keyboard.press('Tab')
return
}
// 兜底: form-item
const item = formItemByLabel(page, label, scope).first()
if ((await item.count()) === 0) {
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')
}
/**
* 点击 modal 内的主按钮 (保存/确定)
* 优先级: confirm-btns primary > modal primary > "保存" > "确定"
*/
export async function saveModal(page: Page, opts: FormOpts = {}) {
const scope = opts.scope ?? SEL.MODAL
const btn = page
.locator(
`${scope} button:has-text("保 存"), ${scope} button:has-text("确 定"), ${scope} button.ant-btn-primary`,
)
.first()
if ((await btn.count()) === 0) {
throw new Error(`saveModal: modal 内找不到保存按钮`)
}
await btn.click()
}
/**
* 关闭 modal (优先"关闭", 再"取消", 最后 Escape)
*/
export async function closeModal(page: Page, opts: FormOpts = {}) {
const scope = opts.scope ?? SEL.MODAL
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)
}
+23
View File
@@ -0,0 +1,23 @@
/**
* _helpers/index.ts — 标准库聚合导出
*
* 用法:
* import { clickMenu, fillByLabel, saveModal, countRows, clickAdd } from '../_helpers'
*
* 模块清单:
* - auth: 登录 + storageState 复用 (auth.ts + auth.setup.ts)
* - nav: 菜单导航 (nav.ts)
* - form: 表单操作 (form.ts) fillByLabel/selectByLabel/fillDateByLabel/...
* - table: vxe-table 操作 (table.ts) countRows/findRow/clickRowAction/...
* - modal: 模态框 (modal.ts) waitOpen/waitClose/getErrors/...
* - wait: 智能等待 (wait.ts) waitSpaReady/waitTableReady/waitRowCountChange/...
* - selectors: 选择器常量 (selectors.ts) SEL/formItemByLabel/rowAction
*/
export * from './selectors'
export * from './wait'
export * from './nav'
export * from './form'
export * from './table'
export * from './modal'
export * from './auth'
+50
View File
@@ -0,0 +1,50 @@
/**
* _helpers/modal.ts — 模态框 helpers
*
* 用法:
* await waitFormModalReady(page) // 等打开
* await fillByLabel(...)
* await saveModal(page) // 触发保存
* await waitModalClose(page) // 等自动关闭
* // 或:
* const errs = await getErrors(page)
* if (errs.length > 0) throw new Error(errs.join(', '))
*/
import type { Page } from '@playwright/test'
import { SEL, formItemByLabel } from './selectors'
/** 等 modal 打开 + form 字段渲染 */
export async function waitOpen(page: Page, timeout = 10_000) {
await page.waitForSelector(SEL.MODAL, { timeout })
await page.waitForSelector(`${SEL.MODAL} ${SEL.FORM_ITEM}`, {
timeout,
})
await page.waitForTimeout(200)
}
/** 等 modal 关闭 */
export async function waitClose(page: Page, timeout = 15_000) {
await page.waitForSelector(SEL.MODAL, {
state: 'hidden',
timeout,
})
}
/** 拿校验错误文字列表 */
export async function getErrors(page: Page): Promise<string[]> {
const errs = page.locator(SEL.FORM_ITEM_ERROR)
return await errs.allTextContents()
}
/** modal 是否可见 */
export async function isOpen(page: Page): Promise<boolean> {
return (await page.locator(SEL.MODAL).count()) > 0
}
/** 拿 modal 标题 (e.g. "新增", "编辑", "提示") */
export async function getTitle(page: Page): Promise<string> {
const title = page.locator('.ant-modal-title').first()
if ((await title.count()) === 0) return ''
return ((await title.textContent()) ?? '').trim()
}
+108
View File
@@ -0,0 +1,108 @@
/**
* _helpers/nav.ts — 侧边栏菜单导航
*
* jnpf 6.2.0 菜单特点 (盲点 42 防御):
* - **扁平** 结构 (jnpf-menu-item 全在根), 不是 antd 嵌套
* - 部分文本会匹配多个项目 (e.g. "数据资产" 匹配 7+), 必须精确匹配
* - 隐藏元素不能 force click, 用 page.evaluate JS click 触发 SPA 路由
*
* 用法:
* await clickMenu(page, '数据资产管理')
* await clickMenu(page, '用户管理', {selector: '.ant-menu-item'}) // fallback
*/
import type { Page } from '@playwright/test'
import { SEL } from './selectors'
export interface ClickMenuOpts {
/** 指定选择器 (默认按 SEL.MENU_ITEM_CANDIDATES 优先级) */
selector?: string
/** 等待路由后新元素出现 (e.g. vxe-table) */
waitFor?: string
/** 等待超时 (ms), 默认 8s */
timeout?: number
}
export interface ClickMenuResult {
ok: boolean
matched: number
selector: string
url?: string
}
/**
* 点击侧边栏菜单 (精确匹配, 避免部分匹配冲突)
* 走 page.evaluate JS click, 隐藏元素也能触发 SPA 路由
*/
export async function clickMenu(
page: Page,
menuName: string,
opts: ClickMenuOpts = {},
): Promise<ClickMenuResult> {
const result = await page.evaluate(
({ name, selector }) => {
const candidates = selector
? [selector]
: ['.jnpf-menu-item', '.ant-menu-item', '[class*="menu-item"]']
for (const sel of candidates) {
const items = Array.from(
document.querySelectorAll<HTMLElement>(sel),
)
for (const item of items) {
// 精确匹配 (trim 掉空白/换行/图标文字)
const text = (item.textContent ?? '').trim()
if (text === name) {
item.click()
return { ok: true, matched: items.length, selector: sel }
}
}
}
// fallback: 报告前 5 个候选文字, 方便调试
const all = document.querySelectorAll<HTMLElement>('.jnpf-menu-item')
const sample = Array.from(all)
.slice(0, 5)
.map((e) => (e.textContent ?? '').trim())
return {
ok: false,
matched: all.length,
selector: '.jnpf-menu-item',
candidates: sample,
}
},
{ name: menuName, selector: opts.selector },
)
if (!result.ok) {
const sample = (result as any).candidates ?? []
throw new Error(
`clickMenu: 找不到菜单 "${menuName}" (matched=${result.matched})\n` +
` 候选样本: ${JSON.stringify(sample)}`,
)
}
// 可选: 等路由后新元素
if (opts.waitFor) {
await page.waitForSelector(opts.waitFor, { timeout: opts.timeout ?? 8_000 })
} else {
// 默认给 SPA 路由 + 组件渲染 800ms
await page.waitForTimeout(800)
}
return { ...result, url: page.url() }
}
/**
* 展开分类菜单 (嵌套结构才用, jnpf 6.2.0 通常扁平不需要)
* 兜底: 找不到时静默返回
*/
export async function expandCategory(page: Page, categoryName: string) {
const handle = page
.locator(
`${SEL.MENU_SUB_CONTENT}:has-text("${categoryName}"), ${SEL.MENU_SUB}:has-text("${categoryName}")`,
)
.first()
if ((await handle.count()) > 0) {
await handle.click()
await page.waitForTimeout(300)
}
}
+87
View File
@@ -0,0 +1,87 @@
/**
* _helpers/selectors.ts — JNPF 6.2.0 通用选择器常量
*
* 集中所有"jnpf 稳定契约"选择器, 改 jnpf 版本只需改这一处。
* 盲点 31 防御: 字符串 `:`/`.` 等要 escape? Playwright CSS 引擎自动转义。
*
* 命名规范:
* - 大写常量 = 字符串选择器
* - 函数 (formItemByLabel/rowAction) = 组合, 调用方传 label/action
*/
export const SEL = {
// ===== 登录页 =====
LOGIN_ACCOUNT: '#form_item_account',
LOGIN_PASSWORD: '#form_item_password',
LOGIN_SUBMIT: 'button:has-text("登 录")',
// ===== 侧边栏菜单 (jnpf 6.2.0 扁平 + 偶尔嵌套) =====
// 优先 .jnpf-menu-item (jnpf 自定义), 兜底 .ant-menu-item (antd), 再兜底 [class*="menu-item"]
MENU_ITEM: '.jnpf-menu-item',
MENU_SUB: '.jnpf-sub-menu',
MENU_SUB_TITLE: '.jnpf-sub-menu-content__title',
MENU_SUB_CONTENT: '.jnpf-sub-menu-content',
// 多个候选 (按优先级)
MENU_ITEM_CANDIDATES: [
'.jnpf-menu-item',
'.ant-menu-item',
'[class*="menu-item"]',
] as const,
// ===== 模态框 =====
MODAL: '.ant-modal',
MODAL_CONFIRM: '.ant-modal-confirm',
MODAL_CONFIRM_BTNS: '.ant-modal-confirm-btns',
// modal 内主按钮 (优先级: confirm-btns 内的 primary > modal 内的 primary)
MODAL_PRIMARY:
'.ant-modal-confirm-btns button.ant-btn-primary, .ant-modal button.ant-btn-primary, .ant-modal button:has-text("保 存"), .ant-modal button:has-text("确 定")',
MODAL_CLOSE: '.ant-modal button:has-text("关 闭")',
MODAL_CANCEL: '.ant-modal button:has-text("取 消")',
// ===== 表单 =====
FORM_ITEM: '.ant-form-item',
FORM_ITEM_LABEL: '.ant-form-item-label label',
FORM_ITEM_REQUIRED: '.ant-form-item-required',
FORM_ITEM_ERROR: '.ant-form-item-explain-error',
// ===== 输入控件 =====
INPUT: 'input',
TEXTAREA: 'textarea',
SELECT: '.ant-select',
SELECT_DROPDOWN: '.ant-select-dropdown:visible',
SELECT_ITEM: '.ant-select-item-option',
PICKER: '.ant-picker input',
// ===== 表格 (vxe-table 4.x) =====
TABLE: '.vxe-table',
TABLE_ROW: '.vxe-body--row',
// 分页总数 selector (多个版本支持)
TABLE_PAGER_TOTAL:
'.vxe-pager--total, .pager-count, .jnpf-pagination__total',
// ===== 通用按钮 (列表页/弹窗) =====
BTN_PRIMARY: 'button.ant-btn-primary',
BTN_NEW: 'button:has-text("新 增"), button:has-text("新增")',
BTN_EDIT:
'a:has-text("编 辑"), a:has-text("编辑"), button:has-text("编 辑"), button:has-text("编辑")',
BTN_DELETE:
'a:has-text("删 除"), a:has-text("删除"), button:has-text("删 除"), button:has-text("删除")',
} as const;
/**
* 找含 label 文本的 form-item (在 modal 或其他容器内)
* 用法: formItemByLabel(page, '申请人姓名') → Locator
*/
export const formItemByLabel = (page, label: string, scope: string = SEL.MODAL) =>
page.locator(
`${scope} ${SEL.FORM_ITEM}:has(${SEL.FORM_ITEM_LABEL}:has-text("${label}"))`,
);
/**
* 找行的操作按钮 (jnpf 模板常用 a/button + "编辑/删除")
* 用法: rowAction(row, '编 辑') → Locator
*/
export const rowAction = (row, action: string) =>
row.locator(
`a:has-text("${action}"), button:has-text("${action}")`,
);
+85
View File
@@ -0,0 +1,85 @@
/**
* _helpers/table.ts — vxe-table 操作 helpers
*
* jnpf 6.2.0 列表用 vxe-table 4.x:
* - 数据行: .vxe-body--row
* - 分页: .vxe-pager--total (footer, "共 N 条" 文字)
* - 行操作列: 通用 <a>编辑/删除 (jnpf 模板生成)
*
* 用法:
* const before = await countRows(page)
* await clickAdd(page)
* await waitFormModalReady(page)
* await fillByLabel(page, '名称', 'xxx')
* await saveModal(page)
* await waitRowCountChange(page, before, +1) // 自动等行数变化
*/
import type { Page, Locator } from '@playwright/test'
import { SEL } from './selectors'
/** 数 vxe-table 数据行数 */
export async function countRows(page: Page): Promise<number> {
return await page.locator(SEL.TABLE_ROW).count()
}
/** 找含文本的行 (返回 Locator, 链式 .first()/.nth()) */
export function findRow(page: Page, text: string): Locator {
return page.locator(`${SEL.TABLE_ROW}:has-text("${text}")`)
}
/**
* 在指定行点操作 (编辑/删除)
* 找不到行或按钮抛错 (不静默, 显式失败)
*/
export async function clickRowAction(
page: Page,
rowText: string,
action: string,
) {
const row = findRow(page, rowText).first()
if ((await row.count()) === 0) {
throw new Error(`clickRowAction: 找不到含 "${rowText}" 的行`)
}
const btn = row
.locator(`a:has-text("${action}"), button:has-text("${action}")`)
.first()
if ((await btn.count()) === 0) {
throw new Error(
`clickRowAction: 行 "${rowText}" 无 "${action}" 按钮`,
)
}
await btn.click()
}
/** 拿分页总数文字 (e.g. "共 3 条") */
export async function getTotalText(page: Page): Promise<string> {
const footer = page.locator(SEL.TABLE_PAGER_TOTAL).first()
if ((await footer.count()) > 0) {
return (await footer.textContent()) ?? ''
}
// fallback: 找含"共"和"条" 的文字
return (
(await page
.locator('text=/共\\s*\\d+\\s*条/')
.first()
.textContent()
.catch(() => '')) ?? ''
)
}
/** 解析分页总数文字里的数字, e.g. "共 3 条" → 3 */
export async function getTotalCount(page: Page): Promise<number> {
const text = await getTotalText(page)
const m = text.match(/(\d+)/)
return m ? Number(m[1]) : 0
}
/** 点列表页"新增"按钮 (列表顶部) */
export async function clickAdd(page: Page) {
const btn = page.locator(SEL.BTN_NEW).first()
if ((await btn.count()) === 0) {
throw new Error(`clickAdd: 列表页找不到"新增"按钮`)
}
await btn.click()
}
+100
View File
@@ -0,0 +1,100 @@
/**
* _helpers/wait.ts — 智能等待 helpers (避免 networkidle 慢等待)
*
* jnpf 6.2.0 SPA 特点:
* - vue-router 跳转不触发整页 reload, networkidle 经常迟迟不到
* - 业务页 "渲染完" 的稳信号是某个特定元素出现 (菜单/表格行/弹窗)
*
* 原则:
* - 用 page.waitForSelector(具体元素) 代替 waitForLoadState('networkidle')
* - 默认 15s timeout, 比 networkidle 30s 快很多
* - 给 form 渲染留 500ms 缓冲 (antd v-model 异步)
*/
import type { Page } from '@playwright/test'
import { SEL } from './selectors'
/**
* 等 jnpf SPA home 渲染完 (菜单可见)
* @returns 第一个匹配到的选择器 (供后续 clickMenu 用)
*/
export async function waitSpaReady(
page: Page,
timeout = 15_000,
): Promise<string | null> {
for (const sel of SEL.MENU_ITEM_CANDIDATES) {
try {
await page.waitForSelector(sel, { timeout })
return sel
} catch {
continue
}
}
return null
}
/**
* 等 vxe-table 渲染完 (容器或数据行)
* 不等 networkidle — jnpf 6.2.0 SPA 长连接 (心跳) 永远不停
*/
export async function waitTableReady(page: Page, timeout = 15_000) {
await page.waitForSelector(
`${SEL.TABLE}, ${SEL.TABLE_ROW}`,
{ timeout },
)
// 给 vxe-table 渲染 + vue diff 一帧时间
await page.waitForTimeout(300)
}
/**
* 等 modal 弹窗 + 内部 form 字段渲染完
* 500ms 缓冲: antd v-model 异步, 字段 placeholder/input 要等下一 tick
*/
export async function waitFormModalReady(
page: Page,
timeout = 10_000,
) {
await page.waitForSelector(SEL.MODAL, { timeout })
// 等 modal 内至少 1 个 form-item 渲染
await page.waitForSelector(`${SEL.MODAL} ${SEL.FORM_ITEM}`, {
timeout,
})
await page.waitForTimeout(200)
}
/**
* 等 modal 关闭
*/
export async function waitModalClose(
page: Page,
timeout = 15_000,
) {
await page.waitForSelector(SEL.MODAL, {
state: 'hidden',
timeout,
})
}
/**
* 等列表行数变化 (新增/删除后)
* @param before 新增/删除前的行数
* @param delta +1=期待增加, -1=期待减少
*/
export async function waitRowCountChange(
page: Page,
before: number,
delta: 1 | -1,
timeout = 10_000,
) {
const expected = before + delta
const start = Date.now()
while (Date.now() - start < timeout) {
const count = await page.locator(SEL.TABLE_ROW).count()
if (delta > 0 ? count > before : count < before) return count
if (count === expected) return count
await page.waitForTimeout(200)
}
throw new Error(
`waitRowCountChange: ${timeout}ms 内行数没从 ${before} 变到 ${expected}`,
)
}
+103 -150
View File
@@ -13,215 +13,168 @@
*
* 跑法:
* JNPF_BASE_URL=http://nginx/ npx playwright test tests/e2e/p16-ui-real-crud.spec.ts
*
* v17 重构 (2026-06-15):
* - 用 _helpers/ 标准库 (nav/form/table/modal/wait), 行数 226 → 138 (-39%)
* - 关键变化: 智能等待替代 networkidle, 复用 selector 常量
*/
import { test, expect, Page } from '@playwright/test'
import {
clickMenu,
clickAdd,
fillByLabel,
selectByLabel,
fillDateByLabel,
fillTextareaByLabel,
fillNumberByLabel,
saveModal,
closeModal,
waitFormModalReady,
waitModalClose,
waitTableReady,
waitRowCountChange,
getErrors,
countRows,
findRow,
clickRowAction,
getTotalText,
SEL,
} from './_helpers'
const MODEL_URL = '/jnpf_app_tds/model/tds_leave'
/** 工具: 等待 vxe-table 加载完成 (无 spinner) */
async function waitForListReady(page: Page) {
await page.waitForLoadState('networkidle', { timeout: 30_000 })
// vxe-table 渲染后会有 .vxe-table 或空状态 "暂无数据"
await page.waitForTimeout(800)
}
/** 工具: 数 vxe-table 数据行数 */
async function countRows(page: Page): Promise<number> {
// vxe-body--row 是数据行, 排除固定列 (vxe-body--column)
return await page.locator('.vxe-body--row').count()
}
/** 工具: 拿分页总数文字, e.g. "共 3 条数据" */
async function getTotalText(page: Page): Promise<string> {
const footer = page.locator('.vxe-pager--total, .pager-count, .jnpf-pagination__total')
if (await footer.count() > 0) {
return (await footer.first().textContent()) ?? ''
}
// fallback: 找含"共"和"条" 的文字
return (await page.locator('text=/共\\s*\\d+\\s*条/').first().textContent().catch(() => '')) ?? ''
}
test.describe('P0 #16: Playwright UI 真点击 CRUD (tds_leave)', () => {
test('1. 列表页能打开, +新增按钮 + 空数据状态存在', async ({ page }) => {
await page.goto(MODEL_URL)
await waitForListReady(page)
await waitTableReady(page)
// 关键: 不是预览页 (previewModel), 是真业务页
expect(page.url()).toContain('/model/tds_leave')
expect(page.url()).not.toContain('previewModel')
// + 新增 按钮 (ant-btn primary)
const newBtn = page.locator('button:has-text("新 增"), button:has-text("新增")').first()
await expect(newBtn, '+ 新增 按钮应可见').toBeVisible({ timeout: 10_000 })
// + 新增 按钮
await expect(page.locator(SEL.BTN_NEW).first()).toBeVisible({
timeout: 10_000,
})
// vxe-table 渲染 (可能空, 也可能已有数据)
const table = page.locator('.vxe-table, .vxe-body--row').first()
await expect(table, 'vxe-table 容器应存在').toBeVisible({ timeout: 10_000 })
// vxe-table 容器
await expect(page.locator(SEL.TABLE).first()).toBeVisible({
timeout: 10_000,
})
})
test('2. + 新增 → 填 8 字段 → 保存 → 列表多 1 行', async ({ page }) => {
await page.goto(MODEL_URL)
await waitForListReady(page)
await waitTableReady(page)
const rowsBefore = await countRows(page)
const totalBefore = await getTotalText(page)
console.log(` before: rows=${rowsBefore} total="${totalBefore}"`)
// 1) 点 + 新增
await page.locator('button:has-text("新 增"), button:has-text("新增")').first().click()
// 等 ant-modal 弹出
await page.waitForSelector('.ant-modal', { timeout: 10_000 })
await page.waitForTimeout(800)
await clickAdd(page)
await waitFormModalReady(page)
// 2) 填字段 (按 formData 顺序, jnpf 字段 label 是稳定契约)
// input 字段: 申请人姓名
await page.locator('.ant-modal input').first().fill('测试员工-P16')
// 2) 填 8 字段 (按 label 文本, jnpf 字段 label 是稳定契约)
await fillByLabel(page, '申请人姓名', '测试员工-P16')
await selectByLabel(page, '所在部门', 0)
await selectByLabel(page, '请假类型', 0)
await fillDateByLabel(page, '起始日期', '2026-06-15')
await fillDateByLabel(page, '结束日期', '2026-06-17')
await fillNumberByLabel(page, '请假天数', '3')
await fillTextareaByLabel(page, '请假事由', 'P0 #16 UI 真点击 CRUD 自动测试')
// 找到 select 字段 (按 label 文本), 选第 1 个 option
// jnpf 的 select 渲染为 .ant-select, 第一个是"所在部门"
const selects = page.locator('.ant-modal .ant-select')
await selects.nth(0).click() // 所在部门
await page.waitForTimeout(400)
await page.locator('.ant-select-item-option').first().click()
await page.waitForTimeout(300)
// 调试截图
await page.screenshot({
path: 'screenshots/p16-form-filled.png',
fullPage: true,
})
await selects.nth(1).click() // 请假类型
await page.waitForTimeout(400)
await page.locator('.ant-select-item-option').first().click()
await page.waitForTimeout(300)
// 3) 校验: 无错误
const errs = await getErrors(page)
expect(errs, `表单校验错误: ${errs.join(', ')}`).toEqual([])
// 起始日期 / 结束日期: jnpf 用 .ant-picker
const datePickers = page.locator('.ant-modal .ant-picker input')
await datePickers.nth(0).fill('2026-06-15')
await page.keyboard.press('Tab')
await datePickers.nth(1).fill('2026-06-17')
await page.keyboard.press('Tab')
await page.waitForTimeout(300)
// 4) 保存
await saveModal(page)
await waitModalClose(page)
await page.waitForLoadState('domcontentloaded')
await page.waitForTimeout(800) // vxe-table 刷新
// 请假天数 (inputNumber) — 在 modal 里所有 input 里的, 跳过 select/picker 后
// 简化: 找 placeholder 含"请假天数" 的 input
const daysInput = page.locator('.ant-modal input[placeholder*="请假天数"]').first()
if (await daysInput.count() > 0) {
await daysInput.fill('3')
}
// 请假事由 (textarea, required)
const reasonArea = page.locator('.ant-modal textarea').first()
await reasonArea.fill('P0 #16 UI 真点击 CRUD 自动测试')
await page.waitForTimeout(500)
// 截图: 表单填好状态 (调试用)
await page.screenshot({ path: 'screenshots/p16-form-filled.png', fullPage: true })
// 3) 点保存 (ant-modal 内的 primary button)
const saveBtn = page.locator('.ant-modal button:has-text("确 定"), .ant-modal button:has-text("保 存")').first()
await saveBtn.click()
// 4) 等 modal 关闭 + 列表刷新
await page.waitForSelector('.ant-modal', { state: 'hidden', timeout: 15_000 })
await page.waitForLoadState('networkidle', { timeout: 15_000 })
await page.waitForTimeout(1500)
// 5) 验证: 列表多 1 行
// 5) 验证: 行数 +1
const rowsAfter = await countRows(page)
const totalAfter = await getTotalText(page)
console.log(` after add: rows=${rowsAfter} total="${totalAfter}"`)
// 至少新增 1 行 (如果有分页, rowsAfter 可能 < 真实总数, 但 total 必 +1)
expect(rowsAfter, `rows 应增加, 之前=${rowsBefore}, 之后=${rowsAfter}`).toBeGreaterThan(rowsBefore)
expect(
rowsAfter,
`rows 应增加, 之前=${rowsBefore}, 之后=${rowsAfter}`,
).toBeGreaterThan(rowsBefore)
// 6) 验证: 列表里能看到"测试员工-P16"
const newRow = page.locator('.vxe-body--row:has-text("测试员工-P16")')
await expect(newRow, '新行应含"测试员工-P16"').toBeVisible({ timeout: 10_000 })
const newRow = findRow(page, '测试员工-P16')
await expect(newRow, '新行应含"测试员工-P16"').toBeVisible({
timeout: 10_000,
})
await page.screenshot({ path: 'screenshots/p16-after-add.png', fullPage: true })
await page.screenshot({
path: 'screenshots/p16-after-add.png',
fullPage: true,
})
})
test('3. 编辑行 → 修改申请人姓名 → 保存 → 列表行更新', async ({ page }) => {
test('3. 编辑行 → 修改申请人姓名 → 保存 → 列表行更新', async ({
page,
}) => {
await page.goto(MODEL_URL)
await waitForListReady(page)
await waitTableReady(page)
// 找测试员工-P16 行 (上一 test 创建的)
const targetRow = page.locator('.vxe-body--row:has-text("测试员工-P16")').first()
const exists = await targetRow.count()
if (exists === 0) {
const targetRow = findRow(page, '测试员工-P16').first()
if ((await targetRow.count()) === 0) {
test.skip(true, '上一 test 未创建数据, 跳过')
return
}
// jnpf 行操作一般在"操作"列, 含编辑/删除按钮
// 简化: 点击行的"编辑"链接 (jnpf 模板常用 a:has-text("编辑"))
const editLink = targetRow.locator('a:has-text("编 辑"), a:has-text("编辑"), button:has-text("编 辑"), button:has-text("编辑")').first()
const hasEditLink = await editLink.count()
if (hasEditLink === 0) {
// fallback: 双击行
await targetRow.dblclick()
} else {
await editLink.click()
}
// 点行操作"编辑" (a/button 都试)
await clickRowAction(page, '测试员工-P16', '编辑')
await waitFormModalReady(page)
await page.waitForSelector('.ant-modal', { timeout: 10_000 })
// 改申请人姓名
await fillByLabel(page, '申请人姓名', '测试员工-P16-已修改')
await saveModal(page)
await waitModalClose(page)
await page.waitForLoadState('domcontentloaded')
await page.waitForTimeout(800)
// 改申请人姓名 input 为新值
const nameInput = page.locator('.ant-modal input').first()
await nameInput.fill('')
await nameInput.fill('测试员工-P16-已修改')
await page.waitForTimeout(300)
// 保存
const saveBtn = page.locator('.ant-modal button:has-text("确 定"), .ant-modal button:has-text("保 存")').first()
await saveBtn.click()
await page.waitForSelector('.ant-modal', { state: 'hidden', timeout: 15_000 })
await page.waitForLoadState('networkidle', { timeout: 15_000 })
await page.waitForTimeout(1500)
// 验证: 列表里出现新名, 旧名消失
const updatedRow = page.locator('.vxe-body--row:has-text("测试员工-P16-已修改")')
await expect(updatedRow, '更新后行应含新名').toBeVisible({ timeout: 10_000 })
const oldRow = page.locator('.vxe-body--row:has-text("测试员工-P16"):not(:has-text("已修改"))')
expect(await oldRow.count(), '旧名行应已消失').toBe(0)
// 验证: 新名出现, 旧名消失
await expect(
findRow(page, '测试员工-P16-已修改'),
'更新后行应含新名',
).toBeVisible({ timeout: 10_000 })
expect(
await findRow(page, '测试员工-P16').count(),
'旧名行应已消失',
).toBe(0)
})
test('4. 删除行 → 列表少 1 行 (cleanup)', async ({ page }) => {
await page.goto(MODEL_URL)
await waitForListReady(page)
await waitTableReady(page)
// 找测试员工-P16-已修改 行
const targetRow = page.locator('.vxe-body--row:has-text("测试员工-P16-已修改")').first()
if (await targetRow.count() === 0) {
const targetRow = findRow(page, '测试员工-P16-已修改').first()
if ((await targetRow.count()) === 0) {
test.skip(true, '上一 test 未创建数据, 跳过')
return
}
const rowsBefore = await countRows(page)
// jnpf 删除: 行操作列 → 删除按钮 → 弹确认 → 确定
const delBtn = targetRow.locator('a:has-text("删 除"), a:has-text("删除"), button:has-text("删 除"), button:has-text("删除")').first()
if (await delBtn.count() === 0) {
test.skip(true, '行无"删除"按钮, 跳过')
return
}
await delBtn.click()
// 点行操作"删除"
await clickRowAction(page, '测试员工-P16-已修改', '删除')
// 等二次确认 modal
await page.waitForSelector('.ant-modal-confirm, .ant-modal', { timeout: 10_000 })
await page.waitForTimeout(500)
await page.waitForSelector(SEL.MODAL_CONFIRM, { timeout: 10_000 })
await page.waitForTimeout(300)
// 确认删除
const confirmBtn = page.locator('.ant-modal-confirm-btns button.ant-btn-primary, .ant-modal button:has-text("确 定")').last()
const confirmBtn = page.locator(SEL.MODAL_PRIMARY).last()
await confirmBtn.click()
await page.waitForTimeout(2000)
await page.waitForLoadState('networkidle', { timeout: 15_000 })
await page.waitForTimeout(1500)
// 验证: 行消失
const deletedRow = page.locator('.vxe-body--row:has-text("测试员工-P16-已修改")')
expect(await deletedRow.count(), '已删除行应消失').toBe(0)
const rowsAfter = await countRows(page)
expect(rowsAfter, `rows 应减少, 之前=${rowsBefore}, 之后=${rowsAfter}`).toBeLessThan(rowsBefore)
await waitRowCountChange(page, rowsBefore, -1)
})
})