Back to All Scenarios
Scenario 9 of 100
Synchronization
Advanced
Flakiness Caused by Network Latency and API Delays
πScenario Overview
Flakiness Caused by Network Latency and API Delays
Key Takeaways & Cheat Sheet
- βAbolish static Thread.sleep() sleeps across the entire framework
- βUse WebDriverWait to apply non-blocking waits for specific conditions
- βImplement FluentWait to ignore exceptions and customize polling rates
- βConfigure appropriate global implicit timeouts with caution
Short Direct Answer
Slow backend services or network delay will cause automation scripts to fail if they look for elements before they exist. Using static Thread.sleep() delays is a poor solution that increases execution times. Implementing dynamic Explicit and Fluent waits allows the framework to poll the DOM frequently, immediately resuming as soon as the element is ready.
β οΈ Senior Warning (Red Flag)
Mixing implicit and explicit waits in the same framework is strongly discouraged by the Selenium team. Doing so causes unpredictable wait durations, sometimes turning a 10-second timeout into a 90-second delay.
π‘ STAR Deep Dive Explanation & Pro Tip
Explicit waits are active, non-blocking conditions. If an API responds in 50 milliseconds, the test proceeds instantly, ensuring maximum suite speed compared to hardcoded sleeps.
SeleniumAutomation.java
Selenium 4 + Javaimport org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import java.util.NoSuchElementException;
// β
Build a customized Fluent Wait ignoring specific exceptions
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofMillis(500)) // Poll DOM every 500ms
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
// β
Dynamic condition: Wait until element is loaded and contains non-empty text
WebElement dynamicValue = fluentWait.until(d -> {
WebElement el = d.findElement(By.id("dashboard-metrics"));
String val = el.getText();
return (!val.isEmpty() && !val.equals("Loading...")) ? el : null;
});