region-management.page.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import { Page, Locator } from '@playwright/test';
  2. /**
  3. * 区域层级常量
  4. */
  5. export const REGION_LEVEL = {
  6. PROVINCE: 1,
  7. CITY: 2,
  8. DISTRICT: 3,
  9. } as const;
  10. /**
  11. * 区域层级类型
  12. */
  13. export type RegionLevel = typeof REGION_LEVEL[keyof typeof REGION_LEVEL];
  14. /**
  15. * 区域状态常量
  16. */
  17. export const REGION_STATUS = {
  18. ENABLED: 0,
  19. DISABLED: 1,
  20. } as const;
  21. /**
  22. * 区域数据接口
  23. */
  24. export interface RegionData {
  25. /** 区域名称 */
  26. name: string;
  27. /** 行政区划代码 */
  28. code?: string;
  29. /** 区域层级(1=省, 2=市, 3=区) */
  30. level?: RegionLevel;
  31. /** 父级区域ID */
  32. parentId?: number | null;
  33. /** 状态(0=启用, 1=禁用) */
  34. isDisabled?: typeof REGION_STATUS[keyof typeof REGION_STATUS];
  35. }
  36. /**
  37. * 网络响应数据
  38. */
  39. export interface NetworkResponse {
  40. url: string;
  41. method: string;
  42. status: number;
  43. ok: boolean;
  44. responseHeaders: Record<string, string>;
  45. responseBody: unknown;
  46. }
  47. /**
  48. * 表单提交结果
  49. */
  50. export interface FormSubmitResult {
  51. /** 提交是否成功 */
  52. success: boolean;
  53. /** 是否有错误 */
  54. hasError: boolean;
  55. /** 是否有成功消息 */
  56. hasSuccess: boolean;
  57. /** 错误消息 */
  58. errorMessage?: string;
  59. /** 成功消息 */
  60. successMessage?: string;
  61. /** 网络响应列表 */
  62. responses?: NetworkResponse[];
  63. }
  64. /**
  65. * 区域管理 Page Object
  66. *
  67. * 用于管理省市区树形结构的 E2E 测试
  68. * 页面路径: /admin/areas
  69. *
  70. * @example
  71. * ```typescript
  72. * const regionPage = new RegionManagementPage(page);
  73. * await regionPage.goto();
  74. * await regionPage.createProvince({ name: '测试省', code: '110000' });
  75. * ```
  76. */
  77. export class RegionManagementPage {
  78. readonly page: Page;
  79. // 页面级选择器
  80. readonly pageTitle: Locator;
  81. readonly addProvinceButton: Locator;
  82. readonly treeContainer: Locator;
  83. constructor(page: Page) {
  84. this.page = page;
  85. // 使用精确文本匹配获取页面标题
  86. this.pageTitle = page.getByText('省市区树形管理', { exact: true });
  87. // 使用 role + name 组合获取新增按钮(比单独 text 更健壮)
  88. this.addProvinceButton = page.getByRole('button', { name: '新增省', exact: true });
  89. // 使用 Card 组件的结构来定位树形容器(比 Tailwind 类更健壮)
  90. // 根据实际 DOM: Card > CardContent > AreaTreeAsync > div.border.rounded-lg.bg-background
  91. this.treeContainer = page.locator('.border.rounded-lg').first();
  92. }
  93. /**
  94. * 导航到区域管理页面
  95. */
  96. async goto() {
  97. await this.page.goto('/admin/areas');
  98. await this.page.waitForLoadState('domcontentloaded');
  99. // 等待页面标题出现
  100. await this.pageTitle.waitFor({ state: 'visible', timeout: 15000 });
  101. // 等待树形结构加载
  102. await this.treeContainer.waitFor({ state: 'visible', timeout: 20000 });
  103. await this.expectToBeVisible();
  104. }
  105. /**
  106. * 验证页面关键元素可见
  107. */
  108. async expectToBeVisible() {
  109. await this.pageTitle.waitFor({ state: 'visible', timeout: 15000 });
  110. await this.addProvinceButton.waitFor({ state: 'visible', timeout: 10000 });
  111. }
  112. /**
  113. * 打开新增省对话框
  114. */
  115. async openCreateProvinceDialog() {
  116. await this.addProvinceButton.click();
  117. // 等待对话框出现
  118. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: 5000 });
  119. }
  120. /**
  121. * 打开新增子区域对话框
  122. * @param parentName 父级区域名称
  123. * @param childType 子区域类型('市' 或 '区')
  124. */
  125. async openAddChildDialog(parentName: string, childType: '市' | '区') {
  126. // 找到父级节点并点击对应的"新增市"或"新增区"按钮
  127. const button = this.treeContainer.getByText(parentName)
  128. .locator('../../..')
  129. .getByRole('button', { name: childType === '市' ? '新增市' : '新增区' });
  130. await button.click();
  131. // 等待对话框出现
  132. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: 5000 });
  133. }
  134. /**
  135. * 打开编辑区域对话框
  136. * @param regionName 区域名称
  137. */
  138. async openEditDialog(regionName: string) {
  139. // 找到区域节点并点击"编辑"按钮
  140. const button = this.treeContainer.getByText(regionName)
  141. .locator('../../..')
  142. .getByRole('button', { name: '编辑' });
  143. await button.click();
  144. // 等待对话框出现
  145. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: 5000 });
  146. }
  147. /**
  148. * 打开删除确认对话框
  149. * @param regionName 区域名称
  150. */
  151. async openDeleteDialog(regionName: string) {
  152. // 找到区域节点并点击"删除"按钮
  153. const button = this.treeContainer.getByText(regionName)
  154. .locator('../../..')
  155. .getByRole('button', { name: '删除' });
  156. await button.click();
  157. // 等待删除确认对话框出现
  158. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: 5000 });
  159. }
  160. /**
  161. * 打开状态切换确认对话框
  162. * @param regionName 区域名称
  163. */
  164. async openToggleStatusDialog(regionName: string) {
  165. // 找到区域节点并点击"启用"或"禁用"按钮
  166. // 使用更精确的选择器:在节点行内查找操作按钮组中的状态切换按钮
  167. const regionRow = this.treeContainer.getByText(regionName, { exact: true }).locator('xpath=ancestor::div[contains(@class, "group")][1]');
  168. // 在操作按钮组中查找状态切换按钮(第3个按钮:编辑、状态切换、删除)
  169. const statusButton = regionRow.getByRole('button').filter({ hasText: /^(启用|禁用)$/ }).and(
  170. regionRow.locator('xpath=./div[contains(@class, "flex") and contains(@class, "gap")]//button[position()=3]')
  171. );
  172. await statusButton.click();
  173. // 等待状态切换确认对话框出现
  174. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: 5000 });
  175. }
  176. /**
  177. * 填写区域表单
  178. * @param data 区域数据
  179. */
  180. async fillRegionForm(data: RegionData) {
  181. // 等待表单出现
  182. await this.page.waitForSelector('form', { state: 'visible', timeout: 5000 });
  183. // 填写区域名称
  184. if (data.name) {
  185. await this.page.getByLabel('区域名称').fill(data.name);
  186. }
  187. // 填写行政区划代码
  188. if (data.code) {
  189. await this.page.getByLabel('行政区划代码').fill(data.code);
  190. }
  191. }
  192. /**
  193. * 提交表单
  194. * @returns 表单提交结果
  195. */
  196. async submitForm(): Promise<FormSubmitResult> {
  197. // 收集网络响应
  198. const responses: NetworkResponse[] = [];
  199. // 监听所有网络请求
  200. const responseHandler = async (response: Response) => {
  201. const url = response.url();
  202. // 监听区域管理相关的 API 请求
  203. if (url.includes('/areas') || url.includes('area')) {
  204. const requestBody = response.request()?.postData();
  205. const responseBody = await response.text().catch(() => '');
  206. let jsonBody = null;
  207. try {
  208. jsonBody = JSON.parse(responseBody);
  209. } catch {
  210. // 不是 JSON 响应
  211. }
  212. responses.push({
  213. url,
  214. method: response.request()?.method() ?? 'UNKNOWN',
  215. status: response.status(),
  216. ok: response.ok(),
  217. responseHeaders: await response.allHeaders().catch(() => ({})),
  218. responseBody: jsonBody || responseBody,
  219. });
  220. }
  221. };
  222. this.page.on('response', responseHandler);
  223. // 点击提交按钮(创建或更新)
  224. const submitButton = this.page.getByRole('button', { name: /^(创建|更新)$/ });
  225. await submitButton.click();
  226. // 等待网络请求完成
  227. await this.page.waitForLoadState('networkidle', { timeout: 10000 });
  228. // 移除监听器
  229. this.page.off('response', responseHandler);
  230. // 等待 Toast 消息显示
  231. await this.page.waitForTimeout(2000);
  232. // 检查 Toast 消息
  233. const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
  234. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  235. const hasError = await errorToast.count() > 0;
  236. const hasSuccess = await successToast.count() > 0;
  237. let errorMessage: string | null = null;
  238. let successMessage: string | null = null;
  239. if (hasError) {
  240. errorMessage = await errorToast.first().textContent();
  241. }
  242. if (hasSuccess) {
  243. successMessage = await successToast.first().textContent();
  244. }
  245. return {
  246. success: hasSuccess || (!hasError && !hasSuccess),
  247. hasError,
  248. hasSuccess,
  249. errorMessage: errorMessage ?? undefined,
  250. successMessage: successMessage ?? undefined,
  251. responses,
  252. };
  253. }
  254. /**
  255. * 取消对话框
  256. */
  257. async cancelDialog() {
  258. const cancelButton = this.page.getByRole('button', { name: '取消' });
  259. await cancelButton.click();
  260. await this.waitForDialogClosed();
  261. }
  262. /**
  263. * 等待对话框关闭
  264. */
  265. async waitForDialogClosed() {
  266. const dialog = this.page.locator('[role="dialog"]');
  267. await dialog.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});
  268. await this.page.waitForTimeout(500);
  269. }
  270. /**
  271. * 确认删除操作
  272. */
  273. async confirmDelete() {
  274. const confirmButton = this.page.getByRole('button', { name: /^确认删除$/ });
  275. await confirmButton.click();
  276. // 等待确认对话框关闭和网络请求完成
  277. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: 5000 }).catch(() => {});
  278. await this.page.waitForLoadState('networkidle', { timeout: 10000 });
  279. await this.page.waitForTimeout(1000);
  280. }
  281. /**
  282. * 取消删除操作
  283. */
  284. async cancelDelete() {
  285. const cancelButton = this.page.getByRole('button', { name: '取消' }).and(
  286. this.page.locator('[role="alertdialog"]')
  287. );
  288. await cancelButton.click();
  289. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: 5000 }).catch(() => {});
  290. }
  291. /**
  292. * 确认状态切换操作
  293. */
  294. async confirmToggleStatus() {
  295. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', { name: '确认' });
  296. await confirmButton.click();
  297. // 等待确认对话框关闭和网络请求完成
  298. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: 5000 }).catch(() => {});
  299. await this.page.waitForLoadState('networkidle', { timeout: 10000 });
  300. await this.page.waitForTimeout(1000);
  301. }
  302. /**
  303. * 取消状态切换操作
  304. */
  305. async cancelToggleStatus() {
  306. const cancelButton = this.page.locator('[role="alertdialog"]').getByRole('button', { name: '取消' });
  307. await cancelButton.click();
  308. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: 5000 }).catch(() => {});
  309. }
  310. /**
  311. * 验证区域是否存在
  312. * @param regionName 区域名称
  313. * @returns 区域是否存在
  314. */
  315. async regionExists(regionName: string): Promise<boolean> {
  316. const regionElement = this.treeContainer.getByText(regionName);
  317. return (await regionElement.count()) > 0;
  318. }
  319. /**
  320. * 展开区域节点
  321. * @param regionName 区域名称
  322. */
  323. async expandNode(regionName: string) {
  324. // 找到区域节点的展开按钮
  325. // 使用更健壮的选择器:在节点行内查找第一个小尺寸按钮(展开/收起按钮总是第一个)
  326. const regionRow = this.treeContainer.getByText(regionName, { exact: true }).locator('xpath=ancestor::div[contains(@class, "group")][1]');
  327. const expandButton = regionRow.locator('button').filter({ has: regionRow.locator('svg') }).first();
  328. const count = await expandButton.count();
  329. if (count > 0) {
  330. await expandButton.click();
  331. await this.page.waitForTimeout(500);
  332. }
  333. }
  334. /**
  335. * 收起区域节点
  336. * @param regionName 区域名称
  337. */
  338. async collapseNode(regionName: string) {
  339. // 找到区域节点的收起按钮
  340. const regionRow = this.treeContainer.getByText(regionName, { exact: true }).locator('xpath=ancestor::div[contains(@class, "group")][1]');
  341. const collapseButton = regionRow.locator('button').filter({ has: regionRow.locator('svg') }).first();
  342. const count = await collapseButton.count();
  343. if (count > 0) {
  344. await collapseButton.click();
  345. await this.page.waitForTimeout(500);
  346. }
  347. }
  348. /**
  349. * 获取区域的状态
  350. * @param regionName 区域名称
  351. * @returns 区域状态('启用' 或 '禁用')
  352. */
  353. async getRegionStatus(regionName: string): Promise<'启用' | '禁用' | null> {
  354. const regionRow = this.treeContainer.getByText(regionName, { exact: true }).locator('xpath=ancestor::div[contains(@class, "group")][1]');
  355. // 使用更精确的选择器:查找包含"启用"或"禁用"文本的 Badge
  356. // 根据 Badge 变体:启用=variant="default",禁用=variant="secondary"
  357. const statusBadge = regionRow.locator('.badge').filter({ hasText: /^(启用|禁用)$/ });
  358. const count = await statusBadge.count();
  359. if (count === 0) return null;
  360. const text = await statusBadge.first().textContent();
  361. return text === '启用' || text === '禁用' ? text : null;
  362. }
  363. /**
  364. * 创建省
  365. * @param data 省份数据
  366. * @returns 表单提交结果
  367. */
  368. async createProvince(data: RegionData): Promise<FormSubmitResult> {
  369. await this.openCreateProvinceDialog();
  370. await this.fillRegionForm(data);
  371. const result = await this.submitForm();
  372. await this.waitForDialogClosed();
  373. return result;
  374. }
  375. /**
  376. * 创建子区域(市或区)
  377. * @param parentName 父级区域名称
  378. * @param childType 子区域类型
  379. * @param data 子区域数据
  380. * @returns 表单提交结果
  381. */
  382. async createChildRegion(
  383. parentName: string,
  384. childType: '市' | '区',
  385. data: RegionData
  386. ): Promise<FormSubmitResult> {
  387. await this.openAddChildDialog(parentName, childType);
  388. await this.fillRegionForm(data);
  389. const result = await this.submitForm();
  390. await this.waitForDialogClosed();
  391. return result;
  392. }
  393. /**
  394. * 编辑区域
  395. * @param regionName 区域名称
  396. * @param data 更新的区域数据
  397. * @returns 表单提交结果
  398. */
  399. async editRegion(regionName: string, data: RegionData): Promise<FormSubmitResult> {
  400. await this.openEditDialog(regionName);
  401. await this.fillRegionForm(data);
  402. const result = await this.submitForm();
  403. await this.waitForDialogClosed();
  404. return result;
  405. }
  406. /**
  407. * 删除区域
  408. * @param regionName 区域名称
  409. * @returns 是否成功(true = 成功删除, false = 删除失败或取消)
  410. */
  411. async deleteRegion(regionName: string): Promise<boolean> {
  412. await this.openDeleteDialog(regionName);
  413. await this.confirmDelete();
  414. // 等待并检查 Toast 消息
  415. await this.page.waitForTimeout(1000);
  416. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  417. const hasSuccess = await successToast.count() > 0;
  418. return hasSuccess;
  419. }
  420. /**
  421. * 切换区域状态(启用/禁用)
  422. * @param regionName 区域名称
  423. * @returns 是否成功
  424. */
  425. async toggleRegionStatus(regionName: string): Promise<boolean> {
  426. await this.openToggleStatusDialog(regionName);
  427. await this.confirmToggleStatus();
  428. // 等待并检查 Toast 消息
  429. await this.page.waitForTimeout(1000);
  430. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  431. const hasSuccess = await successToast.count() > 0;
  432. return hasSuccess;
  433. }
  434. /**
  435. * 等待树形结构加载完成
  436. */
  437. async waitForTreeLoaded() {
  438. await this.treeContainer.waitFor({ state: 'visible', timeout: 20000 });
  439. // 等待加载文本消失(使用更健壮的选择器)
  440. // 加载文本位于 CardContent 中,带有 text-muted-foreground 类
  441. await this.page.locator('.text-muted-foreground', { hasText: '加载中' }).waitFor({ state: 'hidden', timeout: 10000 }).catch(() => {});
  442. }
  443. }