auth.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import type { Page } from '@playwright/test';
  2. import { expect } from '@playwright/test';
  3. export async function authLogin(page: Page) {
  4. // 确保登录表单正常
  5. const usernameInput = await page.locator(`input[name='username']`);
  6. await expect(usernameInput).toBeVisible();
  7. const passwordInput = await page.locator(`input[name='password']`);
  8. await expect(passwordInput).toBeVisible();
  9. const sliderCaptcha = await page.locator(`div[name='captcha']`);
  10. const sliderCaptchaAction = await page.locator(`div[name='captcha-action']`);
  11. await expect(sliderCaptcha).toBeVisible();
  12. await expect(sliderCaptchaAction).toBeVisible();
  13. // 拖动验证码滑块
  14. // 获取拖动按钮的位置
  15. const sliderCaptchaBox = await sliderCaptcha.boundingBox();
  16. if (!sliderCaptchaBox) throw new Error('滑块未找到');
  17. const actionBoundingBox = await sliderCaptchaAction.boundingBox();
  18. if (!actionBoundingBox) throw new Error('要拖动的按钮未找到');
  19. // 计算起始位置和目标位置
  20. const startX = actionBoundingBox.x + actionBoundingBox.width / 2; // div 中心的 x 坐标
  21. const startY = actionBoundingBox.y + actionBoundingBox.height / 2; // div 中心的 y 坐标
  22. const targetX = startX + sliderCaptchaBox.width + actionBoundingBox.width; // 向右拖动容器的宽度
  23. const targetY = startY; // y 坐标保持不变
  24. // 模拟鼠标拖动
  25. await page.mouse.move(startX, startY); // 移动到 action 的中心
  26. await page.mouse.down(); // 按下鼠标
  27. await page.mouse.move(targetX, targetY, { steps: 20 }); // 拖动到目标位置
  28. await page.mouse.up(); // 松开鼠标
  29. // 在拖动后进行断言,检查action是否在预期位置,
  30. const newActionBoundingBox = await sliderCaptchaAction.boundingBox();
  31. expect(newActionBoundingBox?.x).toBeGreaterThan(actionBoundingBox.x);
  32. // 到这里已经校验成功,点击进行登录
  33. await page.waitForTimeout(300);
  34. await page.getByRole('button', { name: 'login' }).click();
  35. }