You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright(TS/JS)中捕获加载Spinner的截图?

解决按钮点击后加载Spinner的UI测试截图问题

你的核心问题是:点击按钮后页面跳转速度快于Spinner的750ms延迟显示,导致固定等待时间还没到就跳转到下一页,无法捕获Spinner。以下是几种可行的解决方案:


1. 精准拦截跳转请求并延迟响应

不要拦截所有请求,只针对点击按钮后触发的跳转请求(比如提交接口、目标页面路由)做延迟,确保Spinner有足够时间显示:

// 替换为实际的跳转请求路径,比如/api/user/login或目标页面URL
await page.route('/api/submit', async (route) => {
  // 延迟2秒响应,确保Spinner能稳定显示
  await new Promise(resolve => setTimeout(resolve, 2000));
  await route.continue();
});

2. 监听Spinner元素出现后立即截图

放弃固定等待时间,改为等待Spinner元素可见后立刻截图,结合请求拦截确保元素能正常出现:

await continueButton.click();
// 替换为你项目中Spinner的实际选择器
const spinnerLocator = page.locator('.btn-loading-spinner');
// 等待Spinner元素变为可见状态
await spinnerLocator.waitFor({ state: 'visible' });
// 捕获Spinner的截图,也可以选择捕获按钮区域
await expect(spinnerLocator).toHaveScreenshot(testName('spinner', testInfo), {
  animations: 'allow',
});

3. 阻止页面跳转(仅测试Spinner显示逻辑)

如果只需要验证Spinner是否会显示,不需要完成后续跳转流程,可以直接阻止表单提交或页面跳转行为:

// 给目标表单添加提交阻止事件
await page.$eval('form[data-form-primary]', form => {
  form.addEventListener('submit', e => e.preventDefault());
});

await continueButton.click();
// 等待Spinner延迟显示的750ms
await page.waitForTimeout(750);
await expect(continueButton).toHaveScreenshot(testName('spinner', testInfo));

修改后的完整测试代码示例

test.only('should show loading spinner for continue button', async ({ page }, testInfo) => {
  // 拦截提交请求,延迟响应
  await page.route('/api/submit', async (route) => {
    await new Promise(resolve => setTimeout(resolve, 2000));
    await route.continue();
  });

  const inputs = page.locator('#username');
  const continueButton = page.locator('form[data-form-primary] button[type=submit]');
  const spinnerLocator = page.locator('.btn-loading-spinner'); // 替换为实际Spinner选择器

  await continueButton.click();
  await expect(continueButton).toHaveScreenshot(testName('invalid', testInfo));

  await inputs.focus();
  await inputs.type('fake@email.com');
  await expect(inputs).toHaveScreenshot(testName('typing', testInfo));

  await continueButton.click();
  await spinnerLocator.waitFor({ state: 'visible' });
  await expect(spinnerLocator).toHaveScreenshot(testName('spinner', testInfo), {
    animations: 'allow',
  });
});

注意事项

  • 务必将代码中的Spinner选择器替换为你项目中的实际定位符
  • 请求拦截尽量精准,避免影响其他无关请求导致测试效率下降
  • 若不需要验证完整跳转流程,使用阻止提交的方法会更高效

内容的提问来源于stack exchange,提问作者keqing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:20:10