使用 Playwright 防止 flaky 测试

发布: (2026年1月9日 GMT+8 21:55)
2 min read
原文: Dev.to

Source: Dev.to

Cover image for Prevent flaky tests with Playwright

不稳定的测试是技术债务。
在端到端测试中要慎用循环和手动延迟。

Loop .all()

可以利用 locator.all() 获取匹配定位器选择器的所有元素的 Locator 对象数组。这对于检查计数和其他相关值非常有帮助。

避免使用天真的 for 循环 ❌:

const items = await page.locator('.myselector').all();
for (item in items) { // or for (let i = 0; ... )
  // …
}

此类循环可能导致不稳定性并且对异步定位器处理不当。

推荐的做法 ✅:

  • 使用批量操作助手,如 allInnerTexts()allTextContents()count()filter()
  • 如果真的需要循环,请这样写:
for (const item of items) {
  await item.scrollIntoViewIfNeeded();
  await expect(item).toBeVisible();
}

Playwright 通常在定位器上提供批量操作,因此显式循环往往是不必要的。

Timing Violations

由于动态 DOM 变化或页面尚未准备好,测试可能会错过目标。即使 Playwright 添加了一些自动等待,仍然建议将断言写得明确。

不要依赖隐式等待 ❌:

const anchor = await expect(page.locator('#anchor'));

更倾向于显式检查 ✅:

await expect(page.locator('#target')).toBeVisible();
await page.locator('#target').scrollIntoViewIfNeeded();

Source: Playwright – Auto‑waiting

Convenient Configuration

Playwright 可以自动重试不稳定的测试:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  retries: 5,
});

Test Result Categories

  • Passed – 首次尝试即成功
  • Flaky – 初次失败但在重试后通过
  • Failed – 所有尝试均失败

不要使用重试来忽视不稳定的测试 ❌。
标记不稳定的测试并修复它们 ✅。

Back to Blog

相关文章

阅读更多 »