Selenium is not brittle, you’re just using it wrong!

Exhibit A: clicking an element with Selenium

What if the element we’re trying to click doesn’t exist just yet?

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(locator));

What if the element is disabled or not visible?

wait.until(ExpectedConditions.elementToBeClickable(element));

What if our element is covered by something else?

public class CustomConditions {
public static ExpectedCondition<Boolean> elementWasClicked(
final WebElement element) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
element.click();
return true;
} catch (Exception ex) {
return false;
}
}
@Override
public String toString() {
return "element to be clicked: " +
element.toString();
}
};
}
}
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(locator));
wait.until(ExpectedConditions.elementToBeClickable(element));
wait.until(CustomConditions.elementWasClicked(element));

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrian Theodorescu

Adrian Theodorescu

16 Followers

Passionate software engineer, proud parent of two, author of the OpenTest functional testing tool for web, mobile and APIs.