πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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 + Java
import 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;
});