java - 如何等待按钮内的加载程序完成加载?

标签 java selenium testing selenium-webdriver automated-tests

按下按钮后,我需要等待特定的加载程序完成加载,请看下面的图片: enter image description here

如上图所示,按下按钮后,ajax 加载程序就会出现在按钮内。

我创建了以下选择器来定位按钮:

//form[contains(@id, 'messageform')]//button/span

当前接受请求(单击按钮)使我的测试用例失败,因为脚本继续执行下一个测试步骤而不等待加载程序完成。

我已经尝试了以下以及更多,但没有成功:

  • 注入(inject) JS 以等待页面完全加载。

    ExpectedCondition<Boolean> expectation = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
    
  • ExpectedConditions.invisibilityOf(元素)

    WebDriver driver = getDriver();
    
    WebDriverWait exists = new WebDriverWait(driver, timer);
    exists.until(ExpectedConditions.refreshed(
            ExpectedConditions.invisibilityOf(element)));
    

有什么想法吗?

最佳答案

您应该使用 .stalenessOf() 来等待元素不再附加到 DOM。

像这样(根据您的情况调整):

WebElement somePageElement = driver.findElement(By.id("someId"));
WebDriverWait wait = new WebDriverWait(webDriver, 10);
// do something that changes state of somePageElement
wait.until(ExpectedConditions.stalenessOf(somePageElement));

好处是您不必处理任何异常。

或者,您也可以创建一个方法并像这样处理异常:

public static void WaitForCommission (WebDriver driver) throws Exception {
    for (int second = 0; second++) {
        if (second >= 30) fail("timeout");
        try { 
            if (IsElementActive(By.id("someElementID"), driver)) 
                break; 
            } catch (Exception e) {}
        Thread.sleep(1000);
    }
}

private static boolean IsElementActive(By id, WebDriver driver) {
    WebElement we =  driver.findElement(id);        
    if(we.isEnabled())
        return true;
    return false;
}

关于java - 如何等待按钮内的加载程序完成加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55969702/

相关文章:

java - 在 catch block 中编写的任何代码是否会导致使用更多资源?

java - 通过 Jython 使用/创建 Python 对象

java - 如何点击 Selenium 中网页元素的特定位置?

java - 测试游戏算法速度

java - headless /CLI LibGDX

java - 在 hibernate 状态下替换父级的最佳方法

java - 如何参数化java方法来迭代表中的元素?

Ruby:Phantom.js 在特定站点上被阻止?

testing - VirtualBox可以在Amazon EC2实例下执行吗?

C# - 如何检查用户是否使用 HttpWebRequest 登录到 Web