This document discusses strategies for waiting for Ajax calls to complete when testing dynamic web pages using Selenium. It explains that the naive approach of hardcoded sleeps does not work well. Instead, it recommends using implicit waits to ignore Ajax timing inconsistencies or explicit waits via WebDriverWait when waiting for a specific element to appear. The key is to avoid sleeps and instead wait for an observable element or condition.
3. The DOM and asynchronicity – Challenges
Existing elements may change values
New elements may appear
Not all Ajax calls have observable side effects
3
4. The naive approach doesn’t work
It’s ugly
Different loads on the target host make setting
the correct interval difficult
Time lost! Imagine 1000+ tests where each test
spends 2 seconds sleeping...
4
5. Home-made wait
timeToWait = 10s
loop while timeToWait > 0
if element is found then exit loop
sleep
decrease timeToWait
end loop
5
6. Implicit waits
interface Timeouts {
Timeouts implicitlyWait(long time, TimeUnit unit);
Timeouts setScriptTimeout(long time, TimeUnit unit);
Timeouts pageLoadTimeout(long time, TimeUnit unit);
}
6
7. Finders and timeout
findElement()
Throws NoSuchElementException
Respects implicit waits
findElements()
Returns an empty collection
Respects implicit waits
7
8. WebDriverWait
new WebDriverWait(webDriver, 5).until(new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver webDriver) {
return webDriver.findElement(By.id("some id"));
}
});
Parameters: timeout, polling interval, ignored
exceptions, error message
Ignores exceptions by default
8
9. Zero side effect validation
validate(invalid)
“invalid”
C S
DOML
changes E
I R
validate(valid)
E V
N “valid” E
T R
Nothing
9
10. How to wait – Conclusion
Method When
Sleep Never
Home-made sleep Once – and remove it
Implicit waits When you really, really don’t
care about Ajax
WebDriverWait Whenever you can
Poll an ”Ajax status” variable When there are no observable
side effects
10