不稳定性测试探测器 是做什么的?
识别、诊断并消除不稳定性测试。多次运行您的测试套件,隔离非确定性失败,分类根本原因,并应用针对性修复。
流程
- 检测 运行器与配置
- 收集 通过多次运行获取不稳定性候选测试
- 分析 失败模式以识别根本原因
- 修复 针对每种不稳定性类别应用经过验证的策略
- 验证 通过重新运行检测循环来确认修复
阶段 1:检测运行器和配置
读取项目设置:
cat package.json
识别测试运行器:
| 指示符 | 运行器 | 基础命令 |
|---|---|---|
"vitest" 在 devDependencies 中 | Vitest | npx vitest |
"jest" 在 devDependencies 中 | Jest | npx jest |
"react-scripts" 在 devDependencies 中 | react-scripts | npx react-scripts test |
"@playwright/test" 在 devDependencies 中 | Playwright | npx playwright test |
"cypress" 在 devDependencies 中 | Cypress | npx cypress run |
"mocha" 在 devDependencies 中 | Mocha | npx mocha |
"ava" 在 devDependencies 中 | AVA | npx ava |
检查现有的重试/不稳定配置:
- Vitest:
vitest.config.ts中的retry - Jest:
jest.config.ts中的testRetry或 setup 文件中的jest.retryTimes() - Playwright:
playwright.config.ts中的retries - Cypress:
cypress.config.ts中的retries
阶段 2:收集不稳定性候选测试
多次运行完整套件并收集失败信息:
# 运行 3 次以上,记录每次结果
for i in 1 2 3; do
echo "=== 运行 $i ==="
npx vitest --reporter=json 2>/dev/null | tee ".flaky-run-$i.json"
done
快速检查上一次失败运行的不稳定性:
npx vitest --reporter=json 2>/dev/null | tee ".flaky-last-run.json"
对于 Jest:
for i in 1 2 3; do
echo "=== 运行 $i ==="
npx jest --json 2>/dev/null | tee ".flaky-run-$i.json"
done
对于 Playwright:
for i in 1 2 3; do
echo "=== 运行 $i ==="
npx playwright test --reporter=json 2>/dev/null | tee ".flaky-run-$i.json"
done
收集跨运行的测试结果并识别:
- 始终通过 — 稳定,从分析中排除
- 始终失败 — 有缺陷的测试,单独报告
- 有时通过,有时失败 — 不稳定性候选测试
阶段 3:分析根本原因
对于每个不稳定性候选测试,根据症状进行分类:
类别 A:异步时序
症状:
- 测试本地通过但在 CI 上失败(较慢的环境)
- 失败信息提及超时、
setTimeout、setInterval、requestAnimationFrame - 浏览器测试中 DOM 断言间歇性失败
诊断:
# 在测试文件中 grep 异步模式
grep -n "setTimeout\|setInterval\|waitFor\|delay\|sleep\|requestAnimationFrame\|transition\|animation" <test-file>
查找:
- 固定超时而非轮询/重试
- 在 Vitest 中缺少
waitFor或expect.poll - 在 Testing Library 中缺少
waitFor/findBy* - 异步操作完成前进行断言
类别 B:共享可变状态
症状:
- 失败取决于测试顺序(使用
--shard或--bail 1运行会改变结果) - 测试在隔离运行时通过但在完整套件中失败
- 模块级变量、单例、全局变量
诊断:
# 检查共享状态模式
grep -n "let [a-z]* = \|var [a-z]* = \|const [a-z]* = \|global\." <test-file> | head -20
查找:
- 测试间未重置的测试级变量
- 泄漏的模拟状态(
vi.fn()/jest.fn()未清除) - 未恢复的环境变量修改
- 未清理的文件系统或数据库状态
类别 C:测试隔离
症状:
- 测试使用
--testPathPattern=<single-file>通过,但在完整套件中失败 - 特定其他测试在其之前运行时测试失败
诊断: 以随机顺序运行测试以确认:
# Vitest(顺序 + 随机)
npx vitest --sequence=sequential --reporter=json 2>/dev/null
npx vitest --sequence=random --reporter=json 2>/dev/null
查找:
- 缺少
beforeEach/afterEach清理 - 测试修改 DOM 或全局变量而未恢复
- 数据库/种子数据未按测试隔离
- 泄漏的模拟实现(缺少
vi.restoreAllMocks()/jest.restoreAllMocks())
类别 D:环境敏感性
症状:
- 仅在 CI 上失败(从未在本地)
- 在某些操作系统/浏览器组合上失败
- 在特定时间失败(时区、日期依赖)
诊断: 查找:
- 硬编码的时间/日期值
- 特定于区域设置的格式化
- 时区相关的断言
- 屏幕分辨率、视口大小假设
- 特定于 Node.js/Python 版本的行为
- 网络相关的测试(API 调用、速率限制)
类别 E:竞态条件
症状:
- 失败涉及并发操作、Web Workers 或并行请求
Promise.all、Promise.race、延迟为 0ms 的setTimeout- 共享发射器上的事件监听器
诊断:
grep -n "Promise\.all\|Promise\.race\|Promise\.any\|Promise\.allSettled\|setTimeout\|setImmediate\|process\.nextTick" <test-file>
阶段 4:应用修复
根据检测到的类别应用修复:
修复 A:异步时序
替换脆弱的定时模式:
- await new Promise(r => setTimeout(r, 1000))
- expect(screen.getByText('Loaded')).toBeInTheDocument()
+ await waitFor(() => {
+ expect(screen.getByText('Loaded')).toBeInTheDocument()
+ }, { timeout: 5000, interval: 100 })
对于 Vitest,使用 expect.poll 或 waitFor:
import { waitFor } from '@testing-library/react'
// 或 Vitest 内置:
await expect.poll(() => getStatus(), { timeout: 5000, interval: 100 }).toBe('done')
对于 Playwright,使用自动等待定位器:
// 糟糕:
await page.waitForTimeout(2000)
expect(await page.textContent('.status')).toBe('done')
// 良好:
await expect(page.locator('.status')).toHaveText('done', { timeout: 10000 })
修复 B:共享可变状态
+ import { vi } from 'vitest'
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
重置模块级状态:
beforeEach(() => {
// 重置计数器、缓存、单例
counter = 0
cache.clear()
})
隔离运行时配置修改:
const ORIGINAL_RUNTIME_MODE = getRuntimeMode()
afterEach(() => {
setRuntimeMode(ORIGINAL_RUNTIME_MODE)
})
修复 C:测试隔离
+ beforeEach(() => {
+ document.body.innerHTML = ''
+ localStorage.clear()
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ })
对于数据库支持的测试:
beforeEach(async () => {
await db.migrate.latest()
await db.seed.run()
})
afterEach(async () => {
await db.migrate.rollback()
})
修复 D:环境敏感性
模拟时间相关的代码:
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2024-01-15T12:00:00Z'))
})
afterEach(() => {
vi.useRealTimers()
})
对于区域设置敏感的测试:
import { locale } from '../i18n'
beforeEach(() => {
locale.set('en-US')
})
对于网络相关的测试,模拟所有外部调用:
vi.mock('../api/client')
// 或
global.fetch = vi.fn()
修复 E:竞态条件
确保测试中的顺序处理:
// 使用 Promise.all 替代方案,顺序测试
await operation1()
await operation2()
对于事件发射器测试:
const events: string[] = []
emitter.on('data', (d) => events.push(d))
emitter.emit('data', 'a')
emitter.emit('data', 'b')
await vi.waitFor(() => {
expect(events).toEqual(['a', 'b'])
})
阶段 5:添加重试配置
在修复根本原因后,添加重试作为安全网。优先使用 CI 特定的配置文件或 CI 作业命令,并包含字面重试值,而不是在测试配置中读取运行时环境变量。
Vitest — vitest.ci.config.ts:
import baseConfig from './vitest.config'
export default defineConfig({
...baseConfig,
test: {
...baseConfig.test,
retry: 2,
// 不稳定测试的顺序执行:
sequence: {
seed: 123,
shuffle: false,
},
},
})
在 CI 中使用 vitest --config vitest.ci.config.ts 运行。
或者使用 vi.retry() 按测试/文件进行:
vi.retry(2)
describe('flaky file', () => { ... })
Jest — jest.ci.config.ts(需要 jest-retry):
const baseConfig = require('./jest.config')
export default {
...baseConfig,
setupFilesAfterSetup: ['jest-retry'],
retryTimes: 2,
}
在 CI 中使用 jest --config jest.ci.config.ts 运行。
Playwright — playwright.ci.config.ts:
import baseConfig from './playwright.config'
export default defineConfig({
...baseConfig,
retries: 2,
})
在 CI 中使用 playwright test --config playwright.ci.config.ts 运行。
阶段 6:验证
重新运行不稳定性检测循环:
for i in 1 2 3; do
echo "=== 运行 $i ==="
npx vitest --reporter=json 2>/dev/null | tee ".flaky-verify-$i.json"
done
比较跨运行的结果:
- 零个不稳定测试 — 成功,报告修复数量
- 剩余不稳定测试 — 返回到阶段 3 进行更深入的分析
FLAKY_REPORT.md 生成
在修复后,生成摘要报告:
# 不稳定性测试报告
| 测试 | 运行器 | 类别 | 状态 | 应用的修复 |
|------|--------|----------|--------|-------------|
| `auth.test.ts` | Vitest | 异步时序 | 已修复 | 将 `setTimeout` 替换为 `waitFor` |
| `api.test.ts` | Jest | 共享状态 | 已修复 | 添加了 `beforeEach` 清理 |
| `login.spec.ts` | Playwright | 环境 | 隔离中 | 需要 API 模拟设置 |
**稳定率:** 98/100 个测试 (98%)
**下一步:** 手动审查剩余的不可靠测试
示例
用户:"我们的 CI 充满了不稳定性测试,我们使用 vitest"
AI 智能体操作:
- 使用循环运行
npx vitest --reporter=json3 次 - 检测到 4 个测试在运行中不一致地通过/失败
- 对于
auth.test.ts:grep 显示断言前有setTimeout(500) - 替换为
waitFor—auth.test.ts现在在 3 次运行中保持一致 - 对于
api.test.ts:模块级的认证令牌在测试间泄漏 - 添加
beforeEach(() => localStorage.clear())— 稳定 - 在
vitest.config.ts中配置 CI 重试 = 2 - 验证:所有 4 个之前不稳定的测试持续通过
- 显示报告
用户:"playwright e2e 测试在 CI 上不稳定"
AI 智能体操作:
- 运行
npx playwright test --reporter=json3 次,识别login.spec.ts不稳定 - 分析:使用
page.waitForTimeout(3000)— 异步时序问题 - 替换为
await expect(page.locator('.dashboard')).toBeVisible({ timeout: 15000 }) - 在
playwright.config.ts中为 CI 设置retries: 2 - 同时检测到
user-profile.spec.ts— 环境敏感性(时区) - 在测试设置中模拟时区
- 验证:两个测试的 3/3 次运行均通过