等待Ajax调用以完成Selenium 2 WebDriver

Omu*_*Omu 53 c# ajax selenium selenium-webdriver

我正在使用Selenium 2 WebDriver来测试使用AJAX的UI.

有没有办法让驱动程序等待Ajax请求完成.

基本上我有这个:

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);
Run Code Online (Sandbox Code Playgroud)

Mor*_*sen 76

如果你正在为你的ajax请求使用jQuery,你可以等到jQuery.active属性为零.其他库可能有类似的选项.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 解决了我的坏'睡觉`:-) (5认同)
  • 这是什么语言? (2认同)

小智 41

你也可以在这里使用Selenium显式等待.那你就不需要自己处理超时了

public void WaitForAjax()
{
    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
    wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0"));
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法为不使用JQuery的AJAX执行此操作? (6认同)

Hak*_*kin 15

var wait = new WebDriverWait(d, TimeSpan.FromSeconds(5));
var element = wait.Until(driver => driver.FindElement(By.Id("Hobbies")));
Run Code Online (Sandbox Code Playgroud)

  • @Omu,WebDriver的设计使它只显示真实用户看到的内容.如果用户看不到它,那么webdriver也看不到它. (2认同)
  • @hhastekin 很好,它看到了输入类型的 value 属性:隐藏 (2认同)

she*_*rif 7

基于Morten Christiansens的Java解决方案回答

    public void WaitForAjax() throws InterruptedException
    {

        while (true)
        {

            Boolean ajaxIsComplete = (Boolean) ((JavascriptExecutor)driver).executeScript("return jQuery.active == 0");
            if (ajaxIsComplete){
                break;
            }
            Thread.sleep(100);
        }
    }