Expected Conditions in Selenium
JustAcademy Selenium Training: JustAcademy Selenium Training Course
JustAcademy Demo Registration: Register for Selenium Course Demo
Expected Conditions are predefined conditions provided by Selenium that are commonly used with explicit waits to synchronize automated test execution with the current state of a web application. Instead of making Selenium wait for a fixed amount of time, Expected Conditions allow the script to wait for a specific condition such as an element becoming visible, clickable, selected, present, invisible, or containing specific text.
Expected Conditions are especially important when testing modern web applications where elements can be loaded or updated asynchronously through JavaScript, AJAX requests, API calls, animations, dynamic DOM changes, and other browser-side operations.
JustAcademy's Selenium curriculum includes waits, synchronization, and dynamic elements, including implicit wait, explicit wait, Fluent Wait, page-load synchronization, handling dynamic elements, and stable test execution strategies. Selenium Training Course | Selenium Course Demo
1. What are Expected Conditions?
Expected Conditions are ready-to-use conditions that can be passed to Selenium's explicit wait mechanism. They help the automation script wait until a particular state is achieved before continuing with the next operation.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("username")));
In this example, Selenium waits until the username element is visible before returning the WebElement.
2. Why are Expected Conditions Required?
Selenium commands can execute faster than a web application can update its user interface. A page may still be loading, an AJAX request may still be running, a button may still be disabled, or a dynamic element may not yet exist in the DOM.
Without proper synchronization, Selenium tests can fail even when the application is functioning correctly.
Test Starts
↓
Open Application
↓
Application Loads
↓
JavaScript Executes
↓
API/AJAX Request
↓
DOM Updates
↓
Element Becomes Ready
↓
Selenium Performs Action
3. Expected Conditions and Explicit Wait
Expected Conditions are most commonly used with WebDriverWait, which provides explicit waiting for a particular condition.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login")));
The wait checks the specified condition until it succeeds or the maximum timeout is reached.
4. Required Imports
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Alert;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
5. Basic Syntax
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")));
6. How Expected Conditions Work
Create WebDriverWait
↓
Set Maximum Timeout
↓
Specify Expected Condition
↓
Check Condition
↓
Condition Satisfied?
/ \
Yes No
↓ ↓
Continue Check Again
↓
Timeout Reached?
/ \
No Yes
↓ ↓
Repeat TimeoutException
7. ExpectedConditions Class
Selenium provides the ExpectedConditions class containing commonly used conditions for synchronizing browser automation.
| Expected Condition | Purpose |
| presenceOfElementLocated() | Waits for an element to be present in the DOM. |
| visibilityOfElementLocated() | Waits for an element to be located and visible. |
| visibilityOf() | Waits for an existing WebElement to become visible. |
| elementToBeClickable() | Waits for an element to be visible and enabled. |
| invisibilityOfElementLocated() | Waits for an element to become invisible or unavailable. |
| textToBePresentInElementLocated() | Waits for specific text to appear. |
| textToBePresentInElement() | Waits for specific text in an existing element. |
| attributeToBe() | Waits for an attribute to have a specific value. |
| attributeContains() | Waits for an attribute to contain specific text. |
| elementToBeSelected() | Waits for an element to become selected. |
| elementSelectionStateToBe() | Waits for a selected or unselected state. |
| alertIsPresent() | Waits for a JavaScript alert. |
| frameToBeAvailableAndSwitchToIt() | Waits for a frame and switches into it. |
| stalenessOf() | Waits for an old element to become detached from the DOM. |
| titleContains() | Waits for text to appear in the page title. |
| titleIs() | Waits for the exact page title. |
| urlContains() | Waits for text to appear in the URL. |
| urlToBe() | Waits for the URL to exactly match a value. |
| numberOfWindowsToBe() | Waits for a specific number of browser windows or tabs. |
8. presenceOfElementLocated()
presenceOfElementLocated() waits until an element is present in the DOM. The element does not necessarily need to be visible.
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(
By.id("username")));
Example
WebElement searchBox = wait.until(
ExpectedConditions.presenceOfElementLocated(
By.id("search")));
searchBox.sendKeys("Selenium");
9. Presence vs Visibility
| Presence | Visibility |
| Element exists in the DOM. | Element is displayed. |
| Element may still be hidden. | Element is rendered and has meaningful dimensions. |
| Useful when DOM existence is enough. | Useful before visible interaction. |
| Does not guarantee user visibility. | Does not automatically guarantee successful clicking. |
10. visibilityOfElementLocated()
visibilityOfElementLocated() waits until the element can be located and is visible.
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")));
username.sendKeys("admin");
11. visibilityOf()
visibilityOf() is useful when the WebElement has already been located and the test needs to wait until it becomes visible.
WebElement message = driver.findElement(By.id("message"));
WebElement visibleMessage = wait.until(
ExpectedConditions.visibilityOf(message));
12. visibilityOfElementLocated() vs visibilityOf()
| Method | Input | Purpose |
| visibilityOfElementLocated() | By locator | Locates and waits for visibility. |
| visibilityOf() | WebElement | Waits for an already located element to become visible. |
13. elementToBeClickable()
elementToBeClickable() waits until an element is visible and enabled. It is commonly used before clicking buttons, links, checkboxes, menus, and other interactive controls.
WebElement loginButton = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("login")));
loginButton.click();
14. What Does Clickable Mean?
For Selenium's expected condition, an element is considered clickable when it is visible and enabled. This condition does not guarantee that a click will always succeed because another element, overlay, animation, layout change, or dynamic DOM update may still interfere.
15. elementToBeClickable() with WebElement
WebElement button = driver.findElement(By.id("submit"));
WebElement clickableButton = wait.until(
ExpectedConditions.elementToBeClickable(button));
clickableButton.click();
16. invisibilityOfElementLocated()
invisibilityOfElementLocated() is useful when the test needs to wait until a temporary element such as a loader, spinner, overlay, or progress indicator becomes invisible or is no longer present.
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
By.id("loader")));
17. Waiting for Loading Spinner
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
By.cssSelector(".loading-spinner")));
WebElement dashboard = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("dashboard")));
18. textToBePresentInElementLocated()
This condition waits until the specified text is present inside an element located by the given locator.
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("status"),
"Completed"));
19. Dynamic Status Example
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("orderStatus"),
"Delivered"));
System.out.println("Order completed");
20. textToBePresentInElement()
This condition can be used when the WebElement has already been located.
WebElement message = driver.findElement(By.id("message"));
wait.until(
ExpectedConditions.textToBePresentInElement(
message,
"Success"));
21. textToBePresentInElementValue()
This condition can be used to wait until the value of a form element contains the expected text.
wait.until(
ExpectedConditions.textToBePresentInElementValue(
By.id("search"),
"Selenium"));
22. attributeToBe()
attributeToBe() waits until an element's specified attribute has the expected value.
wait.until(
ExpectedConditions.attributeToBe(
By.id("status"),
"data-state",
"complete"));
23. attributeContains()
attributeContains() waits until an attribute contains a specified value.
wait.until(
ExpectedConditions.attributeContains(
By.id("order"),
"class",
"completed"));
24. Waiting for Dynamic CSS Class
wait.until(
ExpectedConditions.attributeContains(
By.id("submit"),
"class",
"active"));
25. elementToBeSelected()
elementToBeSelected() waits until an element becomes selected. It is useful for checkboxes, radio buttons, and selectable elements.
wait.until(
ExpectedConditions.elementToBeSelected(
By.id("terms")));
26. elementSelectionStateToBe()
elementSelectionStateToBe() waits until an element reaches the specified selected or unselected state.
wait.until(
ExpectedConditions.elementSelectionStateToBe(
By.id("terms"),
true));
27. Waiting for Checkbox Selection
wait.until(
ExpectedConditions.elementSelectionStateToBe(
By.id("terms"),
true));
28. Waiting for Checkbox to Become Unselected
wait.until(
ExpectedConditions.elementSelectionStateToBe(
By.id("subscribe"),
false));
29. alertIsPresent()
alertIsPresent() waits until a JavaScript alert is present.
Alert alert = wait.until(
ExpectedConditions.alertIsPresent());
alert.accept();
30. Handling Alert with Expected Condition
driver.findElement(By.id("delete")).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent());
System.out.println(alert.getText());
alert.accept();
31. Handling Confirmation Alert
Alert alert = wait.until(
ExpectedConditions.alertIsPresent());
if (alert.getText().contains("Are you sure")) {
alert.accept();
}
32. frameToBeAvailableAndSwitchToIt()
frameToBeAvailableAndSwitchToIt() waits until a frame becomes available and switches the WebDriver context into that frame.
wait.until(
ExpectedConditions.frameToBeAvailableAndSwitchToIt(
By.id("paymentFrame")));
driver.findElement(By.id("cardNumber"))
.sendKeys("1234");
33. Switching Back from Frame
wait.until(
ExpectedConditions.frameToBeAvailableAndSwitchToIt(
By.id("paymentFrame")));
driver.findElement(By.id("cardNumber"))
.sendKeys("1234");
driver.switchTo().defaultContent();
34. stalenessOf()
stalenessOf() waits until a previously located WebElement is no longer attached to the current DOM.
WebElement oldElement = driver.findElement(
By.id("dynamicElement"));
driver.findElement(By.id("refresh")).click();
wait.until(
ExpectedConditions.stalenessOf(oldElement));
35. Why stalenessOf() is Useful
Modern web applications may replace existing DOM elements after an action. The original WebElement can then become stale. Waiting for the old element to become stale can help synchronize the test before locating the newly rendered element.
36. titleContains()
titleContains() waits until the browser page title contains specified text.
wait.until(
ExpectedConditions.titleContains("Dashboard"));
37. titleIs()
titleIs() waits until the page title exactly matches the expected title.
wait.until(
ExpectedConditions.titleIs("Dashboard - Home"));
38. urlContains()
urlContains() waits until the current URL contains the specified text.
wait.until(
ExpectedConditions.urlContains("/dashboard"));
39. urlToBe()
urlToBe() waits until the current URL exactly matches the expected URL.
wait.until(
ExpectedConditions.urlToBe(
"https://example.com/dashboard"));
40. urlMatches()
urlMatches() can be used when the URL needs to match a regular expression pattern.
wait.until(
ExpectedConditions.urlMatches(
".*/dashboard.*"));
41. numberOfWindowsToBe()
numberOfWindowsToBe() waits until the browser has the specified number of windows or tabs.
String parentWindow = driver.getWindowHandle();
driver.findElement(By.id("openWindow")).click();
wait.until(
ExpectedConditions.numberOfWindowsToBe(2));
42. Switching to New Window
wait.until(
ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parentWindow)) {
driver.switchTo().window(handle);
break;
}
}
43. presenceOfAllElementsLocatedBy()
presenceOfAllElementsLocatedBy() waits until matching elements are present in the DOM and returns the collection of matching elements.
List<WebElement> products = wait.until(
ExpectedConditions.presenceOfAllElementsLocatedBy(
By.cssSelector(".product")));
44. visibilityOfAllElementsLocatedBy()
visibilityOfAllElementsLocatedBy() waits until all matching elements are visible.
List<WebElement> products = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.cssSelector(".product")));
45. visibilityOfAllElements()
This condition can be used when a collection of WebElements has already been located and the test needs to wait for their visibility.
List<WebElement> products =
driver.findElements(By.cssSelector(".product"));
wait.until(
ExpectedConditions.visibilityOfAllElements(products));
46. Expected Conditions for Dynamic Applications
Expected Conditions are particularly useful when working with dynamic applications where the state of the page changes after user actions or background operations.
- AJAX requests
- API responses
- Dynamic tables
- Search results
- Loading spinners
- Modal dialogs
- Dynamic dropdowns
- Autocomplete suggestions
- Dynamic buttons
- Changing status messages
- Single Page Applications
47. Expected Conditions for AJAX
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("ajaxResult")));
Instead of using a fixed delay, the test waits for the UI state that indicates the AJAX operation has produced its result.
48. Expected Conditions for Search Results
driver.findElement(By.id("search"))
.sendKeys("Selenium");
driver.findElement(By.id("searchButton")).click();
List<WebElement> results = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.cssSelector(".search-result")));
49. Expected Conditions for Dynamic Button
WebElement submit = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit")));
submit.click();
50. Expected Conditions for Loading Spinner
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
By.cssSelector(".spinner")));
WebElement result = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("result")));
51. Expected Conditions for Modal Dialog
WebElement modal = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("confirmationModal")));
WebElement confirm = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("confirm")));
confirm.click();
52. Expected Conditions for Login
driver.findElement(By.id("username"))
.sendKeys("admin");
driver.findElement(By.id("password"))
.sendKeys("admin123");
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("login"))).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("dashboard")));
53. Expected Conditions for E-Commerce
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("addToCart"))).click();
wait.until(
ExpectedConditions.attributeContains(
By.id("cart"),
"data-count",
"1"));
54. Expected Conditions for Checkout
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("checkout"))).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("paymentPage")));
55. Expected Conditions for Registration
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("register"))).click();
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("registrationSuccess")));
56. Expected Conditions with TestNG
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void verifyDashboard() {
WebElement dashboard = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("dashboard")));
Assert.assertTrue(dashboard.isDisplayed());
}
57. Expected Conditions in Page Object Model
public class LoginPage {
private WebDriver driver;
private WebDriverWait wait;
private By username = By.id("username");
private By password = By.id("password");
private By loginButton = By.id("login");
private By dashboard = By.id("dashboard");
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(
driver,
Duration.ofSeconds(10));
}
public void login(String user, String pass) {
wait.until(
ExpectedConditions.visibilityOfElementLocated(
username)).sendKeys(user);
wait.until(
ExpectedConditions.visibilityOfElementLocated(
password)).sendKeys(pass);
wait.until(
ExpectedConditions.elementToBeClickable(
loginButton)).click();
}
public boolean isDashboardDisplayed() {
return wait.until(
ExpectedConditions.visibilityOfElementLocated(
dashboard)).isDisplayed();
}
}
58. Reusable Wait Utility
public class WaitUtils {
private WebDriverWait wait;
public WaitUtils(WebDriver driver) {
wait = new WebDriverWait(
driver,
Duration.ofSeconds(10));
}
public WebElement waitForVisible(By locator) {
return wait.until(
ExpectedConditions.visibilityOfElementLocated(
locator));
}
public WebElement waitForClickable(By locator) {
return wait.until(
ExpectedConditions.elementToBeClickable(
locator));
}
public void waitForInvisible(By locator) {
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
locator));
}
}
59. Using Wait Utility
WaitUtils waitUtils = new WaitUtils(driver);
WebElement username =
waitUtils.waitForVisible(By.id("username"));
username.sendKeys("admin");
waitUtils.waitForClickable(
By.id("login")).click();
60. Custom Expected Condition with Lambda
When Selenium's predefined conditions do not exactly match the application's state, a custom lambda condition can be used with wait.until().
Boolean completed = wait.until(driver -> {
WebElement status = driver.findElement(By.id("status"));
return "Completed".equals(status.getText());
});
61. Waiting for an Element to Become Enabled
Boolean enabled = wait.until(driver -> {
return driver.findElement(By.id("submit")).isEnabled();
});
If the requirement is both visibility and enabled state before clicking, elementToBeClickable() is often a more appropriate condition.
62. Waiting for a Specific Number of Elements
List<WebElement> products = wait.until(driver -> {
List<WebElement> elements =
driver.findElements(By.cssSelector(".product"));
return elements.size() >= 5 ? elements : null;
});
63. Expected Conditions and TimeoutException
If the required condition is not satisfied before the configured timeout expires, Selenium's explicit wait fails with a TimeoutException.
try {
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("result")));
} catch (TimeoutException e) {
System.out.println(
"Element did not become visible");
throw e;
}
64. Expected Conditions and StaleElementReferenceException
Dynamic applications can replace DOM elements. If a previously stored WebElement is replaced, the reference can become stale.
WebElement oldElement = driver.findElement(
By.id("dynamic"));
driver.findElement(By.id("refresh")).click();
wait.until(
ExpectedConditions.stalenessOf(oldElement));
WebElement newElement = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("dynamic")));
65. Expected Conditions vs Thread.sleep()
| Expected Conditions | Thread.sleep() |
| Condition-based synchronization. | Fixed delay. |
| Checks application state. | Does not check application state. |
| Can continue as soon as the condition succeeds. | Always waits the complete duration. |
| Suitable for dynamic applications. | Not a good general synchronization strategy. |
| Provides reusable conditions. | Provides no application-specific condition. |
66. Expected Conditions vs Implicit Wait
| Feature | Implicit Wait | Expected Conditions |
| Scope | Element lookup. | Specific application state. |
| Visibility | No specific visibility condition. | Supported. |
| Clickability | No. | Supported. |
| Alerts | No. | Supported. |
| Frames | No. | Supported. |
| Text | No. | Supported. |
| Attributes | No. | Supported. |
67. Expected Conditions vs Fluent Wait
| Feature | Expected Conditions | Fluent Wait |
| Purpose | Predefined synchronization conditions. | Flexible waiting mechanism. |
| Timeout | Configured through WebDriverWait. | Configurable. |
| Polling | Handled by the wait implementation. | Polling interval can be customized. |
| Custom Conditions | Can be combined with custom lambda conditions. | Designed for custom waiting behavior. |
| Exception Handling | Depends on wait configuration. | Selected exceptions can be configured. |
68. Presence vs Visibility vs Clickable
| Condition | Meaning | Typical Use |
| Presence | Element exists in DOM. | DOM existence. |
| Visibility | Element is displayed. | Visible UI interaction. |
| Clickable | Element is visible and enabled. | Click operations. |
69. Choosing the Correct Expected Condition
| Requirement | Condition |
| Element exists | presenceOfElementLocated() |
| Element is visible | visibilityOfElementLocated() |
| Button is ready to click | elementToBeClickable() |
| Loader disappears | invisibilityOfElementLocated() |
| Text appears | textToBePresentInElementLocated() |
| Attribute changes | attributeToBe() or attributeContains() |
| Checkbox is selected | elementToBeSelected() |
| Alert appears | alertIsPresent() |
| Frame becomes available | frameToBeAvailableAndSwitchToIt() |
| Old element is replaced | stalenessOf() |
| Title changes | titleContains() or titleIs() |
| URL changes | urlContains() or urlToBe() |
| New tab opens | numberOfWindowsToBe() |
70. Expected Conditions for AJAX Workflow
Click Search
↓
AJAX Request
↓
Loading Spinner
↓
Wait for Spinner to Disappear
↓
Wait for Search Results
↓
Verify Results
↓
Continue Test
71. Expected Conditions for Login Workflow
Open Login Page
↓
Wait for Username
↓
Enter Username
↓
Wait for Password
↓
Enter Password
↓
Wait for Login Button
↓
Click Login
↓
Wait for Dashboard
↓
Verify Dashboard
72. Expected Conditions for E-Commerce Workflow
Open Product Page
↓
Wait for Product
↓
Wait for Add to Cart
↓
Click Add to Cart
↓
Wait for Cart Update
↓
Wait for Checkout
↓
Click Checkout
↓
Wait for Payment Page
↓
Verify Order
73. Expected Conditions with Dynamic Dropdown
WebElement dropdown = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("country")));
dropdown.click();
WebElement option = wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//option[text()='India']")));
option.click();
74. Expected Conditions with Autocomplete
driver.findElement(By.id("city"))
.sendKeys("Mum");
WebElement suggestion = wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//li[contains(text(),'Mumbai')]")));
suggestion.click();
75. Expected Conditions with Dynamic Table
List<WebElement> rows = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.cssSelector("table tbody tr")));
for (WebElement row : rows) {
System.out.println(row.getText());
}
76. Expected Conditions with Modal
WebElement modal = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("modal")));
WebElement close = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("closeModal")));
close.click();
wait.until(
ExpectedConditions.invisibilityOfElementLocated(
By.id("modal")));
77. Expected Conditions with Navigation
driver.findElement(By.id("profile")).click();
wait.until(
ExpectedConditions.urlContains("/profile"));
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("profilePage")));
78. Expected Conditions with Multiple Windows
String parent = driver.getWindowHandle();
driver.findElement(By.id("open")).click();
wait.until(
ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
break;
}
}
79. Expected Conditions with Alerts
driver.findElement(By.id("delete")).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent());
System.out.println(alert.getText());
alert.accept();
80. Expected Conditions with Frames
wait.until(
ExpectedConditions.frameToBeAvailableAndSwitchToIt(
By.id("paymentFrame")));
driver.findElement(By.id("cardNumber"))
.sendKeys("123456");
driver.switchTo().defaultContent();
81. Expected Conditions with XPath
WebElement button = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//button[@id='login']")));
button.click();
82. Expected Conditions with CSS Selector
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(
By.cssSelector("#login")));
button.click();
83. Expected Conditions with ID
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")));
84. Common Mistake: Using Presence When Visibility is Required
If the test needs to interact with a visible element, DOM presence alone may not be sufficient.
wait.until(
ExpectedConditions.presenceOfElementLocated(
By.id("login")));
When visibility is required, use:
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("login")));
85. Common Mistake: Using Visibility When a Click is Required
Visibility does not check whether an element is enabled. For a click operation, elementToBeClickable() can be more appropriate.
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit"))).click();
86. Common Mistake: Using Thread.sleep()
Thread.sleep(5000);
driver.findElement(By.id("result")).click();
A condition-based approach is generally more suitable:
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("result"))).click();
87. Common Mistake: Very Long Timeout
Extremely long timeouts can make failed tests slow to diagnose. Timeout values should be realistic for the application's expected response time and the test environment.
88. Common Mistake: Very Short Timeout
A very short timeout can produce false failures when the application normally requires more time because of network latency, server processing, or browser performance.
89. Common Mistake: Waiting for the Wrong Condition
A test may fail when the selected condition does not represent the actual application state.
Need the element in DOM?
→ presenceOfElementLocated()
Need the element visible?
→ visibilityOfElementLocated()
Need the element ready for click?
→ elementToBeClickable()
Need the loader gone?
→ invisibilityOfElementLocated()
90. Common Mistake: Unstable Locators
Expected Conditions cannot fix an incorrect or unstable locator. Stable IDs, data attributes, reliable CSS selectors, and carefully designed XPath expressions should be preferred.
91. Best Practice: Use the Correct Condition
Always determine the exact state required by the test before selecting an Expected Condition.
DOM Presence
↓
presenceOfElementLocated()
Visibility
↓
visibilityOfElementLocated()
Clickable State
↓
elementToBeClickable()
Disappearance
↓
invisibilityOfElementLocated()
Text State
↓
textToBePresentInElementLocated()
Attribute State
↓
attributeToBe() / attributeContains()
92. Best Practice: Use Stable Locators
By loginButton =
By.cssSelector("[data-testid='login-button']");
wait.until(
ExpectedConditions.elementToBeClickable(
loginButton)).click();
93. Best Practice: Keep Waits Reusable
In large automation frameworks, reusable wait utilities reduce duplicated synchronization code and make the framework easier to maintain.
94. Best Practice: Use Page Object Model
Synchronization logic can be maintained inside Page Object methods so that test cases focus on business workflows and validations.
95. Best Practice: Wait for Real Application State
Instead of waiting for an arbitrary number of seconds, wait for the actual condition that indicates the application is ready.
- Wait for a button to become clickable.
- Wait for a result to appear.
- Wait for a loader to disappear.
- Wait for text to change.
- Wait for a modal to become visible.
- Wait for an attribute to change.
- Wait for a new window to open.
- Wait for a frame to become available.
96. Best Practice: Avoid Unnecessary Waits
Do not add explicit waits before every Selenium command. Use synchronization where the application has asynchronous or dynamic behavior that requires it.
97. Best Practice: Use Realistic Timeout Values
Timeouts should provide enough time for expected application behavior without unnecessarily delaying failed tests.
98. Expected Conditions Quick Reference
| Condition | Purpose |
| presenceOfElementLocated() | Wait for DOM presence. |
| visibilityOfElementLocated() | Wait for visible element. |
| visibilityOf() | Wait for an existing element to become visible. |
| elementToBeClickable() | Wait for visible and enabled element. |
| invisibilityOfElementLocated() | Wait for element to disappear or become invisible. |
| textToBePresentInElementLocated() | Wait for specific text. |
| textToBePresentInElement() | Wait for text in an existing element. |
| attributeToBe() | Wait for exact attribute value. |
| attributeContains() | Wait for partial attribute value. |
| elementToBeSelected() | Wait for selected element. |
| elementSelectionStateToBe() | Wait for selected/unselected state. |
| alertIsPresent() | Wait for JavaScript alert. |
| frameToBeAvailableAndSwitchToIt() | Wait for frame and switch into it. |
| stalenessOf() | Wait for old element to become stale. |
| titleContains() | Wait for title text. |
| titleIs() | Wait for exact title. |
| urlContains() | Wait for URL text. |
| urlToBe() | Wait for exact URL. |
| numberOfWindowsToBe() | Wait for required window count. |
99. Interview Question: What are Expected Conditions?
Answer: Expected Conditions are predefined Selenium conditions used with explicit waits to synchronize test execution with specific application states such as visibility, presence, clickability, text, attributes, alerts, frames, windows, titles, URLs, and selection.
100. Interview Question: Why are Expected Conditions Used?
Answer: They are used to synchronize automation scripts with dynamic web applications and reduce failures caused by timing differences between Selenium commands and application state changes.
101. Interview Question: What is presenceOfElementLocated()?
Answer: It waits until an element is present in the DOM. It does not require the element to be visible.
102. Interview Question: What is visibilityOfElementLocated()?
Answer: It waits until an element is located and is visible on the page.
103. Interview Question: What is elementToBeClickable()?
Answer: It waits until an element is visible and enabled, making it suitable for many click operations.
104. Interview Question: Does elementToBeClickable() Guarantee a Successful Click?
Answer: No. Overlays, animations, layout changes, stale elements, or other application behavior can still interfere with an actual click.
105. Interview Question: What is invisibilityOfElementLocated()?
Answer: It waits until an element becomes invisible or is no longer present according to the condition's behavior.
106. Interview Question: What is alertIsPresent()?
Answer: It waits until a JavaScript alert is present and returns the Alert object.
107. Interview Question: What is stalenessOf()?
Answer: It waits until a previously located WebElement is no longer attached to the current DOM.
108. Interview Question: What is frameToBeAvailableAndSwitchToIt()?
Answer: It waits for a frame to become available and automatically switches the WebDriver context into that frame.
109. Interview Question: Can Expected Conditions Handle Dynamic Elements?
Answer: Yes. Conditions such as presence, visibility, clickability, text, attribute changes, selection, and invisibility are useful for dynamic elements.
110. Interview Question: Can Expected Conditions Be Used with XPath?
Answer: Yes. Expected Conditions can be used with XPath through By.xpath().
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//button[@id='login']")));
111. Interview Question: Can Expected Conditions Be Used with CSS Selectors?
Answer: Yes. CSS selectors can be passed through By.cssSelector().
wait.until(
ExpectedConditions.elementToBeClickable(
By.cssSelector("#login")));
112. Interview Question: What Happens When an Expected Condition Times Out?
Answer: If the condition is not satisfied within the configured timeout, the explicit wait fails with a TimeoutException.
113. Practical Project Using Expected Conditions
A Selenium e-commerce automation project can use Expected Conditions throughout the complete workflow.
- Launch the browser.
- Open the application.
- Wait for the login form.
- Enter username and password.
- Wait for the login button to become clickable.
- Click Login.
- Wait for the dashboard.
- Search for a product.
- Wait for search results.
- Select the product.
- Wait for product details.
- Add the product to the cart.
- Wait for the cart count to update.
- Wait for checkout.
- Complete checkout.
- Wait for order confirmation.
- Verify order status.
114. Practical Project Flow
Launch Browser
↓
Open Application
↓
Wait for Login Form
↓
Enter Credentials
↓
Wait for Login Button
↓
Click Login
↓
Wait for Dashboard
↓
Search Product
↓
Wait for Search Results
↓
Select Product
↓
Wait for Product Page
↓
Add to Cart
↓
Wait for Cart Update
↓
Wait for Checkout
↓
Complete Checkout
↓
Wait for Confirmation
↓
Validate Order
115. Advantages of Expected Conditions
- Provides condition-based synchronization.
- Reduces dependency on fixed delays.
- Improves handling of dynamic web applications.
- Provides reusable predefined conditions.
- Supports visibility and presence checks.
- Supports clickability checks.
- Supports text and attribute conditions.
- Supports alerts and frames.
- Supports windows and tabs.
- Supports selection states.
- Can be combined with custom lambda conditions.
- Works well with Page Object Model frameworks.
116. Limitations of Expected Conditions
- The wrong condition can still cause synchronization failures.
- Very short timeouts can cause false failures.
- Very long timeouts can slow test execution.
- Expected Conditions cannot fix incorrect locators.
- Expected Conditions cannot fix application defects.
- Clickable does not guarantee that an overlay will not intercept a click.
- Complex application-specific states may require custom conditions.
- Unnecessary waits can increase execution time.
117. Expected Conditions Checklist
- Use
presenceOfElementLocated() when DOM presence is sufficient.
- Use
visibilityOfElementLocated() when visibility is required.
- Use
elementToBeClickable() before many click operations.
- Use
invisibilityOfElementLocated() for loaders and temporary overlays.
- Use text conditions for dynamic status messages.
- Use attribute conditions for dynamic application state represented through attributes.
- Use
alertIsPresent() for JavaScript alerts.
- Use frame conditions for dynamic iframes.
- Use window conditions for dynamic tabs and windows.
- Use
stalenessOf() when an old DOM element is replaced.
- Use realistic timeout values.
- Use stable locators.
- Avoid unnecessary
Thread.sleep().
- Keep wait logic reusable.
- Choose conditions according to the actual application state.
118. Final Summary
Expected Conditions are an important part of Selenium synchronization and explicit waits. They allow automation scripts to wait for specific application states instead of relying on arbitrary fixed delays.
The most commonly used conditions include presenceOfElementLocated(), visibilityOfElementLocated(), visibilityOf(), elementToBeClickable(), invisibilityOfElementLocated(), textToBePresentInElementLocated(), attributeToBe(), attributeContains(), elementToBeSelected(), alertIsPresent(), frameToBeAvailableAndSwitchToIt(), stalenessOf(), titleContains(), urlContains(), and numberOfWindowsToBe().
The key to effective Selenium synchronization is selecting the condition that represents the actual state required by the test. Presence, visibility, clickability, selection, text, attributes, alerts, frames, URLs, and windows are different states and should be handled with the appropriate Expected Condition.
119. Selenium Training Resource
Learn Selenium WebDriver, Java automation, locators, WebElements, waits, synchronization, dynamic elements, TestNG, Page Object Model, framework development, and real-world automation testing through the Selenium Training Course.
For a course demonstration, visit the Selenium Course Demo.