Chapter 3: Handling Waits and Synchronization
Explicit wait is the industry gold standard for test synchronization. With WebDriverWait, you tell the driver to wait for a specific condition on a specific element before proceeding. It evaluates conditions dynamically, returning the instant the condition is satisfied.
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// 1. Wait until element is VISIBLE (drawn on screen, non-zero height/width)
WebElement welcomeMsg = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("welcome-message"))
);
// 2. Wait until button is CLICKABLE (visible AND enabled)
WebElement submitBtn = wait.until(
ExpectedConditions.elementToBeClickable(By.id("confirm-transfer-btn"))
);
submitBtn.click();
// 3. Wait until dynamic text updates
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("transaction-status"), "Transfer Completed Successfully"
)
);| Condition Method | Evaluates | Return Type | Production Use Case |
|---|---|---|---|
| elementToBeClickable(locator) | Visible AND enabled in DOM | WebElement | Buttons, links, checkboxes before click() |
| visibilityOfElementLocated(locator) | Visible in DOM (height/width > 0) | WebElement | Reading text, labels, verifying headers |
| invisibilityOfElementLocated(locator) | Hidden or detached from DOM | Boolean | Waiting for loading spinners or progress modals to close |
| presenceOfElementLocated(locator) | Present in DOM (may be hidden) | WebElement | Extracting hidden CSRF tokens or input values |
| textToBePresentInElementLocated(loc, text) | Element contains specific string | Boolean | Waiting for asynchronous currency conversions or totals |
| urlContains(fraction) | Current browser URL contains substring | Boolean | Verifying successful page redirects after login |
// Logical AND — Wait until element is visible AND URL has redirected to dashboard
wait.until(ExpectedConditions.and(
ExpectedConditions.visibilityOfElementLocated(By.id("account-summary")),
ExpectedConditions.urlContains("/banking/dashboard")
));
// Logical OR — Wait for either success banner OR error notification
wait.until(ExpectedConditions.or(
ExpectedConditions.visibilityOfElementLocated(By.id("transfer-success")),
ExpectedConditions.visibilityOfElementLocated(By.id("transfer-failed"))
));
// Logical NOT — Wait until loading bar is NOT visible
wait.until(ExpectedConditions.not(
ExpectedConditions.visibilityOfElementLocated(By.className("loading-bar"))
));Key Point: WebDriverWait + ExpectedConditions provides precise, targeted synchronization. Use visibilityOfElementLocated for reading and elementToBeClickable for clicking.