Reputation: 313
I am stuck at point where i want my script to wait until ajax request is completed.
I tried : 1. Running application in slow network mode, click create button and checked JQuery.active returns 1. There is only ajax call happening.
Problem is whole page is not refreshed.Its just some data on page that is updated everytime.
I used explicit wait to wait until loader/progress bar disappears but i am asked to specifically wait for ajax to complete as UI might change soon.
I tried implementing:
public boolean waitForJSandJQueryToLoad() {
WebDriverWait wait = new WebDriverWait(driver, 30);
// wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return ((Long)((JavascriptExecutor)getDriver()).executeScript("return jQuery.active") == 0);
}
catch (Exception e) {
// no jQuery present
return true;
}
}
};
// wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)getDriver()).executeScript("return document.readyState")
.toString().equals("complete");
}
};
return wait.until(jQueryLoad) && wait.until(jsLoad);
}
But its not working. My test are failing because assertions are called before ajax is completed and data is updated.
Can someone give me working solution to : 1. Check AJAX is running. 2. Wait until ajax is completed. 3. Wait until data is updated/refreshed, not whole page.
Thanks !!
Upvotes: 0
Views: 7426
Reputation: 2836
Here's the code I use to wait for Ajax to finish:
public static void waitForAjaxToFinish() {
WebDriverWait wait = new WebDriverWait(driver, 5000);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wdriver) {
return ((JavascriptExecutor) driver).executeScript("return jQuery.active == 0").equals(true);
}
});
}
and the code I use to wait until JQuery is active:
public static void waitForJQueryToBeActive() {
Boolean isJqueryUsed = (Boolean) ((JavascriptExecutor) driver)
.executeScript("return (typeof(jQuery) != 'undefined')");
if (isJqueryUsed) {
while (true) {
// JavaScript test to verify jQuery is active or not
Boolean ajaxIsComplete = (Boolean) (((JavascriptExecutor) driver)
.executeScript("return jQuery.active == 0"));
if (ajaxIsComplete)
break;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
Hope this helps.
Upvotes: 5