How to synchronize the Selenium test with the element state
You probably heard of the ExpectedConditions class of the Selenium library.
It provides a lot of out-of-the-box expected conditions that can be used to synchronize your test with the page.
These conditions do not apply only to web elements but also to
page state
frames
windows
list of elements
alerts
java script
Let’s focus on expected conditions for web elements.
There are so many of them in this class.
The most popular conditions for web elements are:
elementToBeClickable(By locator)
presenceOfElementLocated(By locator)
visibilityOfElementLocated(By locator)
Which one should you use before finding an element?
Let’s look first at the definitions of these conditions from the link above:
ExpectedCondition<WebElement> elementToBeClickable(By locator)
An expectation for checking an element is visible and enabled such that you can click it.
ExpectedCondition<WebElement> presenceOfElementLocated(By locator)
An expectation for checking that an element is present on the DOM of a page.
ExpectedCondition<WebElement> visibilityOfElementLocated(By locator)
An expectation for checking that an element is present on the DOM of a page and visible.
In short,
elementToBeClickable(By locator)
for checking an element is visible and enabled
presenceOfElementLocated(By locator)
for checking that an element is present on the DOM of a page.
visibilityOfElementLocated(By locator)
for checking that an element is present on the DOM of a page and visible.
What does this mean, actually?
The expected condition to be used depends on what you will do next with the web element.
If you will interact with the element by clicking, selecting, typing in it, the element needs to be enabled so you use elementToBeClickable.
If you need the text of the element, the element needs to be visible so you use visibilityOfElementLocated.
If the element is not visible but is in the DOM, you use presenceOfElementLocated.
That is all for today.