user-management.page.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import { TIMEOUTS } from '../../utils/timeouts';
  2. import { Page, Locator } from '@playwright/test';
  3. import { selectRadixOptionAsync } from '@d8d/e2e-test-utils';
  4. import { UserType, DisabledStatus } from '@d8d/shared-types';
  5. /**
  6. * API 基础 URL
  7. */
  8. const API_BASE_URL = process.env.E2E_BASE_URL || 'http://localhost:8080';
  9. /**
  10. * 用户状态常量
  11. */
  12. export const USER_STATUS = {
  13. ENABLED: 0,
  14. DISABLED: 1,
  15. } as const;
  16. /**
  17. * 用户状态类型
  18. */
  19. export type UserStatus = typeof USER_STATUS[keyof typeof USER_STATUS];
  20. /**
  21. * 用户状态显示名称映射
  22. */
  23. export const USER_STATUS_LABELS: Record<UserStatus, string> = {
  24. 0: '启用',
  25. 1: '禁用',
  26. } as const;
  27. /**
  28. * 用户数据接口(创建用户)
  29. */
  30. export interface UserData {
  31. /** 用户名(必填) */
  32. username: string;
  33. /** 密码(必填) */
  34. password: string;
  35. /** 昵称(可选) */
  36. nickname?: string | null;
  37. /** 邮箱(可选) */
  38. email?: string | null;
  39. /** 手机号(可选) */
  40. phone?: string | null;
  41. /** 真实姓名(可选) */
  42. name?: string | null;
  43. /** 用户类型(默认:管理员) */
  44. userType?: UserType;
  45. /** 关联公司ID(企业用户必填) */
  46. companyId?: number | null;
  47. /** 关联残疾人ID(人才用户必填) */
  48. personId?: number | null;
  49. /** 是否禁用(默认:启用) */
  50. isDisabled?: DisabledStatus;
  51. }
  52. /**
  53. * 用户更新数据接口(编辑用户)
  54. */
  55. export interface UserUpdateData {
  56. /** 用户名 */
  57. username?: string;
  58. /** 昵称 */
  59. nickname?: string | null;
  60. /** 邮箱 */
  61. email?: string | null;
  62. /** 手机号 */
  63. phone?: string | null;
  64. /** 真实姓名 */
  65. name?: string | null;
  66. /** 新密码(可选) */
  67. password?: string;
  68. /** 用户类型 */
  69. userType?: UserType;
  70. /** 关联公司ID(企业用户必填) */
  71. companyId?: number | null;
  72. /** 关联残疾人ID(人才用户必填) */
  73. personId?: number | null;
  74. /** 是否禁用 */
  75. isDisabled?: DisabledStatus;
  76. }
  77. /**
  78. * 网络响应数据接口
  79. */
  80. export interface NetworkResponse {
  81. /** 请求URL */
  82. url: string;
  83. /** 请求方法 */
  84. method: string;
  85. /** 响应状态码 */
  86. status: number;
  87. /** 是否成功 */
  88. ok: boolean;
  89. /** 响应头 */
  90. responseHeaders: Record<string, string>;
  91. /** 响应体 */
  92. responseBody: unknown;
  93. }
  94. /**
  95. * 表单提交结果接口
  96. */
  97. export interface FormSubmitResult {
  98. /** 提交是否成功 */
  99. success: boolean;
  100. /** 是否有错误 */
  101. hasError: boolean;
  102. /** 是否有成功消息 */
  103. hasSuccess: boolean;
  104. /** 错误消息 */
  105. errorMessage?: string;
  106. /** 成功消息 */
  107. successMessage?: string;
  108. /** 网络响应列表 */
  109. responses?: NetworkResponse[];
  110. }
  111. /**
  112. * 用户管理 Page Object
  113. *
  114. * 用于用户管理功能的 E2E 测试
  115. * 页面路径: /admin/users
  116. *
  117. * 支持三种用户类型:
  118. * - ADMIN:管理员,无关联
  119. * - EMPLOYER:企业用户,需关联公司
  120. * - TALENT:人才用户,需关联残疾人
  121. *
  122. * @example
  123. * ```typescript
  124. * const userPage = new UserManagementPage(page);
  125. * await userPage.goto();
  126. * await userPage.createUser({ username: 'testuser', password: 'password123' });
  127. * ```
  128. */
  129. export class UserManagementPage {
  130. readonly page: Page;
  131. // ===== API 端点常量 =====
  132. /** RESTful API 基础端点 */
  133. private static readonly API_USERS_BASE = `${API_BASE_URL}/api/v1/users`;
  134. /** 获取所有用户列表 API */
  135. private static readonly API_GET_ALL_USERS = `${API_BASE_URL}/api/v1/users`;
  136. /** 删除用户 API(需要拼接 /${userId}) */
  137. private static readonly API_DELETE_USER = `${API_BASE_URL}/api/v1/users`;
  138. // ===== 页面级选择器 =====
  139. /** 页面标题 */
  140. readonly pageTitle: Locator;
  141. /** 创建用户按钮 */
  142. readonly createUserButton: Locator;
  143. /** 搜索输入框 */
  144. readonly searchInput: Locator;
  145. /** 搜索按钮 */
  146. readonly searchButton: Locator;
  147. /** 用户列表表格 */
  148. readonly userTable: Locator;
  149. // ===== 对话框选择器 =====
  150. /** 创建对话框标题 */
  151. readonly createDialogTitle: Locator;
  152. /** 编辑对话框标题 */
  153. readonly editDialogTitle: Locator;
  154. // ===== 表单字段选择器 =====
  155. /** 用户名输入框 */
  156. readonly usernameInput: Locator;
  157. /** 密码输入框 */
  158. readonly passwordInput: Locator;
  159. /** 昵称输入框 */
  160. readonly nicknameInput: Locator;
  161. /** 邮箱输入框 */
  162. readonly emailInput: Locator;
  163. /** 手机号输入框 */
  164. readonly phoneInput: Locator;
  165. /** 真实姓名输入框 */
  166. readonly nameInput: Locator;
  167. /** 用户类型选择器 */
  168. readonly userTypeSelector: Locator;
  169. /** 企业选择器(用于 EMPLOYER 类型) */
  170. readonly companySelector: Locator;
  171. /** 残疾人选择器(用于 TALENT 类型) */
  172. readonly disabledPersonSelector: Locator;
  173. // ===== 按钮选择器 =====
  174. /** 创建提交按钮 */
  175. readonly createSubmitButton: Locator;
  176. /** 更新提交按钮 */
  177. readonly updateSubmitButton: Locator;
  178. /** 取消按钮 */
  179. readonly cancelButton: Locator;
  180. // ===== 删除确认对话框选择器 =====
  181. /** 确认删除按钮 */
  182. readonly confirmDeleteButton: Locator;
  183. constructor(page: Page) {
  184. this.page = page;
  185. // 初始化页面级选择器
  186. // 使用 heading role 精确定位页面标题(避免与侧边栏按钮冲突)
  187. this.pageTitle = page.getByRole('heading', { name: '用户管理' });
  188. // 使用 data-testid 定位创建用户按钮
  189. this.createUserButton = page.getByTestId('create-user-button');
  190. // 搜索相关元素
  191. this.searchInput = page.getByTestId('search-user-input');
  192. this.searchButton = page.getByTestId('search-user-button');
  193. // 用户列表表格
  194. this.userTable = page.locator('table');
  195. // 对话框标题选择器
  196. this.createDialogTitle = page.getByTestId('create-user-dialog-title');
  197. this.editDialogTitle = page.getByTestId('edit-user-dialog-title');
  198. // 表单字段选择器 - 使用 label 定位
  199. this.usernameInput = page.getByLabel('用户名');
  200. this.passwordInput = page.getByLabel('密码');
  201. this.nicknameInput = page.getByLabel('昵称');
  202. this.emailInput = page.getByLabel('邮箱');
  203. this.phoneInput = page.getByLabel('手机号');
  204. this.nameInput = page.getByLabel('真实姓名');
  205. // 用户类型选择器
  206. this.userTypeSelector = page.getByTestId('user-type-select');
  207. // 企业选择器(用于 EMPLOYER 类型)
  208. this.companySelector = page.getByTestId('company-selector');
  209. // 残疾人选择器(用于 TALENT 类型)
  210. this.disabledPersonSelector = page.getByTestId('disabled-person-selector');
  211. // 按钮选择器
  212. this.createSubmitButton = page.getByTestId('create-user-submit-button');
  213. this.updateSubmitButton = page.getByTestId('update-user-submit-button');
  214. this.cancelButton = page.getByRole('button', { name: '取消' });
  215. // 删除确认对话框按钮
  216. this.confirmDeleteButton = page.getByTestId('confirm-delete-user-button');
  217. }
  218. // ===== 导航和基础验证 =====
  219. /**
  220. * 导航到用户管理页面
  221. */
  222. async goto(): Promise<void> {
  223. await this.page.goto('/admin/users');
  224. await this.page.waitForLoadState('domcontentloaded');
  225. // 等待页面标题出现
  226. await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
  227. // 等待表格数据加载
  228. await this.userTable.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD_LONG });
  229. await this.expectToBeVisible();
  230. }
  231. /**
  232. * 验证页面关键元素可见
  233. */
  234. async expectToBeVisible(): Promise<void> {
  235. await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
  236. await this.createUserButton.waitFor({ state: 'visible', timeout: TIMEOUTS.TABLE_LOAD });
  237. }
  238. // ===== 对话框操作 =====
  239. /**
  240. * 打开创建用户对话框
  241. */
  242. async openCreateDialog(): Promise<void> {
  243. await this.createUserButton.click();
  244. // 等待对话框出现
  245. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  246. }
  247. /**
  248. * 打开编辑用户对话框
  249. * @param username 用户名
  250. */
  251. async openEditDialog(username: string): Promise<void> {
  252. // 找到用户行并点击编辑按钮
  253. const userRow = this.userTable.locator('tbody tr').filter({ hasText: username });
  254. // 使用 role + name 组合定位编辑按钮,更健壮
  255. const editButton = userRow.getByRole('button', { name: '编辑用户' });
  256. await editButton.click();
  257. // 等待编辑对话框出现
  258. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  259. }
  260. /**
  261. * 打开删除确认对话框
  262. * @param username 用户名
  263. */
  264. async openDeleteDialog(username: string): Promise<void> {
  265. // 找到用户行并点击删除按钮
  266. const userRow = this.userTable.locator('tbody tr').filter({ hasText: username });
  267. // 使用 role + name 组合定位删除按钮,更健壮
  268. const deleteButton = userRow.getByRole('button', { name: '删除用户' });
  269. await deleteButton.click();
  270. // 等待删除确认对话框出现
  271. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  272. }
  273. /**
  274. * 填写用户表单
  275. * @param data 用户数据
  276. * @param companyName 公司名称(当用户类型为 EMPLOYER 时必须提供)
  277. * @param personName 残疾人姓名(当用户类型为 TALENT 时必须提供)
  278. */
  279. async fillUserForm(data: UserData, companyName?: string, personName?: string): Promise<void> {
  280. // 等待表单出现
  281. await this.page.waitForSelector('form', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  282. // 填写用户名(必填字段)
  283. if (data.username) {
  284. await this.usernameInput.fill(data.username);
  285. }
  286. // 填写密码(必填字段)
  287. if (data.password) {
  288. await this.passwordInput.fill(data.password);
  289. }
  290. // 填写昵称(可选字段)
  291. if (data.nickname !== undefined) {
  292. await this.nicknameInput.fill(data.nickname);
  293. }
  294. // 填写邮箱(可选字段)
  295. if (data.email !== undefined) {
  296. await this.emailInput.fill(data.email);
  297. }
  298. // 填写手机号(可选字段)
  299. if (data.phone !== undefined) {
  300. await this.phoneInput.fill(data.phone);
  301. }
  302. // 填写真实姓名(可选字段)
  303. if (data.name !== undefined) {
  304. await this.nameInput.fill(data.name);
  305. }
  306. // 选择用户类型(如果提供了)
  307. const userType = data.userType || UserType.ADMIN;
  308. if (userType !== UserType.ADMIN) {
  309. // 使用 @d8d/e2e-test-utils 的 selectRadixOptionAsync 选择用户类型
  310. const userTypeLabel = userType === UserType.EMPLOYER ? '企业用户' : '人才用户';
  311. await selectRadixOptionAsync(this.page, '用户类型', userTypeLabel);
  312. }
  313. // 填写企业选择器(当用户类型为 EMPLOYER 时)
  314. if (userType === UserType.EMPLOYER && data.companyId && companyName) {
  315. // 使用 @d8d/e2e-test-utils 的 selectRadixOptionAsync 选择企业
  316. await selectRadixOptionAsync(this.page, '关联企业', companyName);
  317. }
  318. // 填写残疾人选择器(当用户类型为 TALENT 时)
  319. if (userType === UserType.TALENT && data.personId && personName) {
  320. // 使用 @d8d/e2e-test-utils 的 selectRadixOptionAsync 选择残疾人
  321. await selectRadixOptionAsync(this.page, '关联残疾人', personName);
  322. }
  323. }
  324. /**
  325. * 填写编辑用户表单
  326. * @param data 用户更新数据
  327. * @param companyName 公司名称(当用户类型为 EMPLOYER 时必须提供)
  328. * @param personName 残疾人姓名(当用户类型为 TALENT 时必须提供)
  329. */
  330. async fillEditUserForm(data: UserUpdateData, companyName?: string, personName?: string): Promise<void> {
  331. // 等待表单出现
  332. await this.page.waitForSelector('form', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  333. // 填写用户名
  334. if (data.username !== undefined) {
  335. await this.usernameInput.fill(data.username);
  336. }
  337. // 填写新密码(可选)
  338. if (data.password !== undefined) {
  339. await this.passwordInput.fill(data.password);
  340. }
  341. // 填写昵称
  342. if (data.nickname !== undefined) {
  343. await this.nicknameInput.fill(data.nickname);
  344. }
  345. // 填写邮箱
  346. if (data.email !== undefined) {
  347. await this.emailInput.fill(data.email);
  348. }
  349. // 填写手机号
  350. if (data.phone !== undefined) {
  351. await this.phoneInput.fill(data.phone);
  352. }
  353. // 填写真实姓名
  354. if (data.name !== undefined) {
  355. await this.nameInput.fill(data.name);
  356. }
  357. // 选择用户类型(如果提供了)
  358. const userType = data.userType || UserType.ADMIN;
  359. if (userType !== UserType.ADMIN) {
  360. // 使用 @d8d/e2e-test-utils 的 selectRadixOptionAsync 选择用户类型
  361. const userTypeLabel = userType === UserType.EMPLOYER ? '企业用户' : '人才用户';
  362. await selectRadixOptionAsync(this.page, '用户类型', userTypeLabel);
  363. }
  364. // 填写企业选择器(当用户类型为 EMPLOYER 时)
  365. if (userType === UserType.EMPLOYER && data.companyId && companyName) {
  366. // 使用 @d8d/e2e-test-utils 的 selectRadixOptionAsync 选择企业
  367. await selectRadixOptionAsync(this.page, '关联企业', companyName);
  368. }
  369. // 填写残疾人选择器(当用户类型为 TALENT 时)
  370. if (userType === UserType.TALENT && data.personId && personName) {
  371. // 使用 @d8d/e2e-test-utils 的 selectRadixOptionAsync 选择残疾人
  372. await selectRadixOptionAsync(this.page, '关联残疾人', personName);
  373. }
  374. }
  375. /**
  376. * 提交表单
  377. * @returns 表单提交结果
  378. */
  379. async submitForm(): Promise<FormSubmitResult> {
  380. // 收集网络响应
  381. const responses: NetworkResponse[] = [];
  382. // 使用 waitForResponse 捕获特定 API 响应,避免并发测试中的监听器干扰
  383. const createUserPromise = this.page.waitForResponse(
  384. response => response.url().includes('/api/v1/users') && response.request().method() === 'POST',
  385. { timeout: TIMEOUTS.TABLE_LOAD }
  386. ).catch(() => null);
  387. const updateUserPromise = this.page.waitForResponse(
  388. response => response.url().includes('/api/v1/users') && response.request().method() === 'PUT',
  389. { timeout: TIMEOUTS.TABLE_LOAD }
  390. ).catch(() => null);
  391. // 捕获列表刷新响应(表单提交后会刷新用户列表)
  392. const getAllUsersPromise = this.page.waitForResponse(
  393. response => response.url().includes('/api/v1/users') && response.request().method() === 'GET',
  394. { timeout: TIMEOUTS.TABLE_LOAD }
  395. ).catch(() => null);
  396. try {
  397. // 点击提交按钮(优先使用 data-testid 选择器)
  398. let submitButton = this.page.locator('[data-testid="create-user-submit-button"]');
  399. if (await submitButton.count() === 0) {
  400. submitButton = this.page.getByRole('button', { name: /^(创建|更新)用户$/ });
  401. }
  402. await submitButton.click();
  403. // 等待 API 响应并收集
  404. const [createResponse, updateResponse, getAllUsersResponse] = await Promise.all([
  405. createUserPromise,
  406. updateUserPromise,
  407. getAllUsersPromise
  408. ]);
  409. // 处理捕获到的响应(创建或更新)
  410. const mainResponse = createResponse || updateResponse;
  411. if (mainResponse) {
  412. const responseBody = await mainResponse.text().catch(() => '');
  413. let jsonBody = null;
  414. try {
  415. jsonBody = JSON.parse(responseBody);
  416. } catch { }
  417. responses.push({
  418. url: mainResponse.url(),
  419. method: mainResponse.request()?.method() ?? 'UNKNOWN',
  420. status: mainResponse.status(),
  421. ok: mainResponse.ok(),
  422. responseHeaders: await mainResponse.allHeaders().catch(() => ({})),
  423. responseBody: jsonBody || responseBody,
  424. });
  425. }
  426. // 等待网络请求完成
  427. try {
  428. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.DIALOG });
  429. } catch {
  430. console.debug('submitForm: networkidle 超时,继续检查 Toast 消息');
  431. }
  432. } catch (error) {
  433. console.debug('submitForm 异常:', error);
  434. }
  435. // 主动等待 Toast 消息显示(最多等待 5 秒)
  436. const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
  437. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  438. // 等待任一 Toast 出现
  439. await Promise.race([
  440. errorToast.waitFor({ state: 'attached', timeout: TIMEOUTS.DIALOG }).catch(() => false),
  441. successToast.waitFor({ state: 'attached', timeout: TIMEOUTS.DIALOG }).catch(() => false),
  442. new Promise(resolve => setTimeout(() => resolve(false), 5000))
  443. ]);
  444. // 再次检查 Toast 是否存在
  445. let hasError = (await errorToast.count()) > 0;
  446. let hasSuccess = (await successToast.count()) > 0;
  447. // 如果标准选择器找不到,尝试更宽松的选择器
  448. if (!hasError && !hasSuccess) {
  449. // 尝试通过文本内容查找
  450. const allToasts = this.page.locator('[data-sonner-toast]');
  451. const count = await allToasts.count();
  452. for (let i = 0; i < count; i++) {
  453. const text = await allToasts.nth(i).textContent() || '';
  454. if (text.includes('成功') || text.toLowerCase().includes('success')) {
  455. hasSuccess = true;
  456. break;
  457. } else if (text.includes('失败') || text.includes('错误') || text.toLowerCase().includes('error')) {
  458. hasError = true;
  459. break;
  460. }
  461. }
  462. }
  463. let errorMessage: string | null = null;
  464. let successMessage: string | null = null;
  465. if (hasError) {
  466. errorMessage = await errorToast.textContent();
  467. }
  468. if (hasSuccess) {
  469. successMessage = await successToast.textContent();
  470. }
  471. console.debug('submitForm 结果:', {
  472. hasError,
  473. hasSuccess,
  474. errorMessage,
  475. successMessage,
  476. responsesCount: responses.length
  477. });
  478. return {
  479. success: hasSuccess || (!hasError && !hasSuccess && responses.some(r => r.ok)),
  480. hasError,
  481. hasSuccess,
  482. errorMessage: errorMessage ?? undefined,
  483. successMessage: successMessage ?? undefined,
  484. responses,
  485. };
  486. }
  487. /**
  488. * 取消对话框
  489. */
  490. async cancelDialog(): Promise<void> {
  491. await this.cancelButton.click();
  492. await this.waitForDialogClosed();
  493. }
  494. /**
  495. * 等待对话框关闭
  496. */
  497. async waitForDialogClosed(): Promise<void> {
  498. // 首先检查对话框是否已经关闭
  499. const dialog = this.page.locator('[role="dialog"]');
  500. const count = await dialog.count();
  501. if (count === 0) {
  502. console.debug('waitForDialogClosed: 对话框不存在,认为已关闭');
  503. return;
  504. }
  505. // 等待对话框隐藏
  506. await dialog.waitFor({ state: 'hidden', timeout: TIMEOUTS.DIALOG })
  507. .catch(() => {
  508. console.debug('waitForDialogClosed: 对话框关闭超时,可能已经关闭');
  509. });
  510. // 额外等待以确保 DOM 更新完成
  511. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  512. }
  513. /**
  514. * 确认删除操作
  515. */
  516. async confirmDelete(): Promise<void> {
  517. await this.confirmDeleteButton.click();
  518. // 等待确认对话框关闭和网络请求完成
  519. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  520. .catch(() => {
  521. console.debug('confirmDelete: 确认对话框关闭超时,继续执行');
  522. });
  523. try {
  524. await this.page.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.DIALOG });
  525. } catch {
  526. console.debug('confirmDelete: 等待 DOM 加载超时,继续执行');
  527. }
  528. await this.page.waitForTimeout(TIMEOUTS.LONG);
  529. }
  530. /**
  531. * 取消删除操作
  532. */
  533. async cancelDelete(): Promise<void> {
  534. const cancelButton = this.page.locator('[role="alertdialog"]').getByRole('button', { name: '取消' });
  535. await cancelButton.click();
  536. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  537. .catch(() => {
  538. // 继续执行
  539. });
  540. }
  541. // ===== CRUD 操作方法 =====
  542. /**
  543. * 创建用户(完整流程)
  544. * @param data 用户数据
  545. * @param companyName 公司名称(当用户类型为 EMPLOYER 时必须提供)
  546. * @param personName 残疾人姓名(当用户类型为 TALENT 时必须提供)
  547. * @returns 表单提交结果
  548. */
  549. async createUser(data: UserData, companyName?: string, personName?: string): Promise<FormSubmitResult> {
  550. await this.openCreateDialog();
  551. await this.fillUserForm(data, companyName, personName);
  552. const result = await this.submitForm();
  553. await this.waitForDialogClosed();
  554. return result;
  555. }
  556. /**
  557. * 编辑用户(完整流程)
  558. * @param username 用户名
  559. * @param data 更新的用户数据
  560. * @param companyName 公司名称(当用户类型为 EMPLOYER 时必须提供)
  561. * @param personName 残疾人姓名(当用户类型为 TALENT 时必须提供)
  562. * @returns 表单提交结果
  563. */
  564. async editUser(username: string, data: UserUpdateData, companyName?: string, personName?: string): Promise<FormSubmitResult> {
  565. await this.openEditDialog(username);
  566. await this.fillEditUserForm(data, companyName, personName);
  567. const result = await this.submitForm();
  568. await this.waitForDialogClosed();
  569. return result;
  570. }
  571. /**
  572. * 删除用户(使用 API 直接删除,绕过 UI)
  573. * @param username 用户名
  574. * @returns 是否成功删除
  575. */
  576. async deleteUser(username: string): Promise<boolean> {
  577. try {
  578. // 使用 API 直接删除,添加超时保护
  579. const result = await Promise.race([
  580. this.page.evaluate(async ({ username, apiGetAll, apiDelete }) => {
  581. // 尝试获取 token(使用标准键名)
  582. let token = localStorage.getItem('token') ||
  583. localStorage.getItem('auth_token') ||
  584. localStorage.getItem('accessToken');
  585. if (!token) {
  586. return { success: false, noToken: true };
  587. }
  588. try {
  589. // 先获取用户列表,找到用户的 ID(限制 100 条)
  590. const listResponse = await fetch(`${apiGetAll}?skip=0&take=100`, {
  591. headers: { 'Authorization': `Bearer ${token}` }
  592. });
  593. if (!listResponse.ok) {
  594. return { success: false, notFound: false };
  595. }
  596. const listData = await listResponse.json();
  597. // 根据用户名查找用户 ID
  598. const user = listData.data?.find((u: { username: string }) =>
  599. u.username === username
  600. );
  601. if (!user) {
  602. // 用户不在列表中,可能已被删除或在其他页
  603. return { success: false, notFound: true };
  604. }
  605. // 使用用户 ID 删除 - DELETE 方法
  606. const deleteResponse = await fetch(`${apiDelete}/${user.id}`, {
  607. method: 'DELETE',
  608. headers: {
  609. 'Authorization': `Bearer ${token}`,
  610. 'Content-Type': 'application/json'
  611. }
  612. });
  613. if (!deleteResponse.ok && deleteResponse.status !== 204) {
  614. return { success: false, notFound: false };
  615. }
  616. return { success: true };
  617. } catch (error) {
  618. return { success: false, notFound: false };
  619. }
  620. }, {
  621. username,
  622. apiGetAll: UserManagementPage.API_GET_ALL_USERS,
  623. apiDelete: UserManagementPage.API_DELETE_USER
  624. }),
  625. // 10 秒超时
  626. new Promise((resolve) => setTimeout(() => resolve({ success: false, timeout: true }), 10000))
  627. ]) as any;
  628. // 如果超时:打印警告但返回 true(允许测试继续)
  629. if (result.timeout) {
  630. console.debug(`删除用户 "${username}" 超时,但允许测试继续`);
  631. return true;
  632. }
  633. // 如果用户找不到:认为删除成功(可能已被其他测试删除)
  634. if (result.notFound) {
  635. console.debug(`删除用户 "${username}": 用户不存在,认为已删除`);
  636. return true;
  637. }
  638. if (result.noToken) {
  639. console.debug('删除用户失败: 未找到认证 token');
  640. return false;
  641. }
  642. if (!result.success) {
  643. console.debug(`删除用户 "${username}" 失败: 未知错误`);
  644. return false;
  645. }
  646. // 删除成功后刷新页面,确保列表更新
  647. await this.page.reload();
  648. await this.page.waitForLoadState('domcontentloaded');
  649. return true;
  650. } catch (error) {
  651. console.debug(`删除用户 "${username}" 异常:`, error);
  652. // 发生异常时返回 true,避免阻塞测试
  653. return true;
  654. }
  655. }
  656. // ===== 搜索和验证方法 =====
  657. /**
  658. * 按用户名搜索
  659. * @param keyword 搜索关键词
  660. * @returns 搜索结果是否包含目标用户
  661. */
  662. async searchUsers(keyword: string): Promise<boolean> {
  663. await this.searchInput.fill(keyword);
  664. await this.searchButton.click();
  665. await this.page.waitForLoadState('domcontentloaded');
  666. await this.page.waitForTimeout(TIMEOUTS.LONG);
  667. // 验证搜索结果
  668. return await this.userExists(keyword);
  669. }
  670. /**
  671. * 验证用户是否存在(使用精确匹配)
  672. * @param username 用户名
  673. * @returns 用户是否存在
  674. */
  675. async userExists(username: string): Promise<boolean> {
  676. const userRow = this.userTable.locator('tbody tr').filter({ hasText: username });
  677. const count = await userRow.count();
  678. if (count === 0) return false;
  679. // 进一步验证用户名列的文本是否完全匹配
  680. // 表格列顺序:头像(0), 用户名(1), 昵称(2), 邮箱(3), 真实姓名(4), ...
  681. const nameCell = userRow.locator('td').nth(1);
  682. const actualText = await nameCell.textContent();
  683. return actualText?.trim() === username;
  684. }
  685. /**
  686. * 获取用户数量
  687. * @returns 用户数量
  688. */
  689. async getUserCount(): Promise<number> {
  690. const rows = await this.userTable.locator('tbody tr').count();
  691. return rows;
  692. }
  693. /**
  694. * 根据用户名获取用户行
  695. * @param username 用户名
  696. * @returns 用户行定位器
  697. */
  698. getUserByUsername(username: string): Locator {
  699. return this.userTable.locator('tbody tr').filter({ hasText: username });
  700. }
  701. /**
  702. * 期望用户存在
  703. * @param username 用户名
  704. */
  705. async expectUserExists(username: string): Promise<void> {
  706. const exists = await this.userExists(username);
  707. if (!exists) {
  708. throw new Error(`期望用户 "${username}" 存在,但未找到`);
  709. }
  710. }
  711. /**
  712. * 期望用户不存在
  713. * @param username 用户名
  714. */
  715. async expectUserNotExists(username: string): Promise<void> {
  716. const exists = await this.userExists(username);
  717. if (exists) {
  718. throw new Error(`期望用户 "${username}" 不存在,但找到了`);
  719. }
  720. }
  721. }