Câu hỏi phỏng vấn #20: Cách handle flaky tests trong Playwright?
Trả lời mẫu:
1. Test retry configuration:
// playwright.config.js
export default { retries: 2, // Retry failed tests up to 2 times workers: 1, // Run serially to avoid race conditions
} // Per test retry
test('flaky test', async ({ page }) => { test.info().annotations.push({ type: 'issue', description: 'JIRA-123' }); // test code
});
2. Improve waits:
// ❌ Bad - fixed timeout
await page.waitForTimeout(2000); // ✅ Good - wait for condition
await page.waitForLoadState('networkidle');
await expect(page.locator('.spinner')).toBeHidden();
3. Test isolation:
test.beforeEach(async ({ page }) => { // Fresh context for each test await page.goto('/'); await page.evaluate(() => localStorage.clear());
});
4. Stabilize animations:
// Disable animations
const context = await browser.newContext({ reducedMotion: 'reduce', // or globally extraHTTPHeaders: { 'X-Disable-Animations': '1' }
});
5. Debug flaky tests:
// Trace on retry
export default { use: { trace: 'on-first-retry', video: 'on-first-retry', screenshot: 'only-on-failure' }
} // Slow mode for debugging
test.slow(); // Triple the timeout
6. Handle timing issues:
// Wait for stable state
await page.waitForFunction(() => { const element = document.querySelector('#dynamic-content'); return element && element.innerText.length > 0;
});
💡 Tips:
- Analyze test reports để identify patterns
- Use
test.fixme()
cho known flaky tests - Mock external dependencies
- Run tests locally nhiều lần:
--repeat-each=10
- Monitor flakiness trends trong CI
Lời Kết
Playwright đang trở thành một trong những automation frameworks phổ biến nhất cho web testing. Thông qua series này, hy vọng bạn sẽ:
- Nắm vững kiến thức từ cơ bản đến nâng cao
- Tự tin trong các buổi phỏng vấn
- Áp dụng hiệu quả vào dự án thực tế
- Trở thành một phần của cộng đồng Playwright Việt Nam năng động
📚 Bắt đầu hành trình của bạn với: Bài 1: Playwright vs Selenium
💬 Có câu hỏi? Tham gia group Facebook của chúng mình!
⭐ Theo dõi series để không bỏ lỡ bài viết mới!