JQuery’s ajax calls can make an automated tester’s life miserable if you don’t know how to handle them.

The quickest way to handle all of the Jquery ajax calls is to wait for the jQuery.active property to be null. We can easily construct a sample code trough the JavasscriptExecutor class.It sends out JavaScript code which can be used for testing the property.

public void waitForAjaxToFinish() {
int timeout = 0;

while(timeout < 80) {
	boolean ajaxFinished = (boolean) ((JavascriptExecutor) driver)
			.executeScript("return !!jQuery && jQuery.active == 0");
	if(ajaxFinished) 
		return;
	timeout++;
	waitFor(500);
	}

throw new AssertionError("Ajax haven't finished its job in 40 sec");
}

The above showed code is best for a single Ajax requests, but when we have multiple Ajax requests there can be problems. Multiple Ajax requests have different completion time and there is no guarantee that there is no fancy Ajax refresher gadget used, which can make previous wait function timeout.

For those cases we have to look into the JQuery documentation, identify the appropriate property or hook which signals if the animation is in progress then construct a custom wait around it.

In the current situation we had a loading animation which moves one of the elements for some pixels, and to ensure the components functionality we have to wait for the animation to finish. From the JQuery documentation we learned that the hook to check if the element is moving called :animated and it is an JQuery extension. The custom wait is based upon the selenium documentation, we only had to override the apply function of the ExpectedCondition function.

public void waitUntilAnimationIsDone(final String cssLocator)
	{
		WebDriverWait wdw = new WebDriverWait(driver, 20);
		ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
			@Override
			public Boolean apply(WebDriver driver) {
				String temp = ((JavascriptExecutor)driver)
				.executeScript("return jQuery('"+cssLocator+"').is(':animated')").toString();				
				return  temp.equalsIgnoreCase("false");
			}
		};

		try{
			wdw.until(expectation);
		}catch(TimeoutException e){
			throw new AssertionError("Element animation is not finished in time. Css locator: " + cssLocator); 
		}
	}	

Additional information for creating custom explicit waits:
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
Description of the Animated Selector

Similar Posts from the author:

2 thoughts to “Wedbriver wait for ajax to finish and JQuery animation

  • Sarapaul

    create generate my past experience is not good about php website develop now a day word press making better and easy understandable as compare

  • Sarapaul

    create generate my past experience is not good about php website develop now a day word press making better and easy understandable as compare

Comments are closed.