Root Causes of Flakiness
1.
Shared State: Test B depends on data created by Test A. Always use isolated contexts.
2.
Fragile Locators: Non-deterministic IDs (
#btn_4829_x). Always use
getByRole or
getByLabel.
3.
Hardcoded Waits: Thread.sleep(3000) will fail when CI servers experience CPU spikes.
4.
Network Jitter: Use
page.waitForResponse() rather than waiting for DOM side effects.
// Diagnostic retry execution:
public static void retryOnFailure(Runnable testAction, int maxAttempts) {
int attempts = 0;
while (attempts < maxAttempts) {
try {
testAction.run();
return;
} catch (RuntimeException e) {
attempts++;
if (attempts >= maxAttempts) throw e;
System.out.println("Test attempt " + attempts + " failed. Retrying...");
}
}
}