Wait for an Ajax call to complete with Selenium 2 WebDriver
I'm using Selenium 2 WebDriver to test an UI which uses AJAX.
Is there a way to make the driver to wait for a bit that the Ajax request will complete.
Basically I have this :
d.FindElement(By.XPath("//div[8]/div[3]/div/button")).Click();
// This click trigger an ajax request which will fill the below ID with content.
// So I need to make it wait for a bit.
Assert.IsNotEmpty(d.FindElement(By.Id("Hobbies")).Text);
Solution 1:
If you're using jQuery for your ajax requests, you can wait until the jQuery.active
property is zero. Other libraries might have similar options.
public void WaitForAjax()
{
while (true) // Handle timeout somewhere
{
var ajaxIsComplete = (bool)(driver as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0");
if (ajaxIsComplete)
break;
Thread.Sleep(100);
}
}
Solution 2:
You could also use the Selenium explicit wait here. Then you don't need to handle timeout yourself
public void WaitForAjax()
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0"));
}