【问题标题】:moveToElement mouse hovering function in Selenium WebDriver using Java not stable使用 Java 的 Selenium WebDriver 中的 moveToElement 鼠标悬停功能不稳定
【发布时间】:2016-11-23 15:41:37
【问题描述】:

我正在使用 Selenium 3.0.1 使用 TestNG 运行自动化测试。 在一项测试中,我尝试将鼠标悬停在操作菜单上,然后单击该菜单中的选项:

Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();

但是测试不稳定。我可以看到菜单打开但立即关闭,因此测试失败,因为它不再找到该选项。 我收到此错误:

java.lang.IllegalArgumentException: Must provide a location for a move action.
at org.openqa.selenium.interactions.MoveMouseAction.<init>(MoveMouseAction.java:30)
at org.openqa.selenium.interactions.Actions.moveToElement(Actions.java:251)

如何检查菜单是否打开? perform() 方法返回 void。 我注意到如果我两次调用 moveToElement,那么测试会更加稳定。这样做有什么优雅的选择吗?

Actions builder = new Actions(getWebDriver());
builder.moveToElement(actionButton).build().perform();
builder.moveToElement(actionButton).build().perform();

当我们将鼠标悬停在菜单上时,它的外观如下:

我发现了这个问题: https://sqa.stackexchange.com/questions/3467/issue-with-losing-focus-of-hover-command-when-the-mouse-is-outside-of-the-acti 这最好地解释了我的问题。不幸的是,仍然没有解决方案。

【问题讨论】:

    标签: java selenium selenium-webdriver


    【解决方案1】:

    如果您不需要打开菜单,请尝试使用 JavascriptExecutor 单击选项。 JavascriptExecutor 也可以单击隐藏元素,使用 JavascriptExecutor 触发单击所需的只是该元素存在于 DOM 上。

    片段(Java):

    ((JavascriptExecutor)driver).executeScript("arguments[0].click()", driver.findElement(By.cssSelector("hiddenOptionFromMenu")));
    

    【讨论】:

      【解决方案2】:

      您可以在悬停后使用FluentWait 等待菜单出现,如下所示:

      FluentWait<> wait = new FluentWait<>(getWebDriver())
                  .withTimeout(driverTimeoutSeconds, TimeUnit.SECONDS)
                  .pollingEvery(500, TimeUnit.MILLISECONDS)
                  .ignoring(StaleElementReferenceException.class)
                  .ignoring(NoSuchElementException.class)
                  .ignoring(ElementNotVisibleException.class)
      
      wait.until(x -> { return driver.findElement(menuElementBy); } );
      

      如果鼠标悬停成功 - 菜单开始出现 - 你没有理由需要调用它两次。

      【讨论】:

      • 这里的问题是菜单确实打开了,但在 Selenium 可以找到子菜单按钮之前立即关闭。我认为 FluentWait 在这里没有帮助,因为菜单已经关闭,所以它只会等待。如果我错了,请纠正我。我正在寻找的是一种在打开下拉菜单后冻结它的方法,但无需单击它。
      • 如果没有看到漏洞场景和网站本身,很难说您是否错了......所以我鼓励您先尝试等待。
      • 它也不能与 JavascriptExecutor 一起使用吗? ((JavascriptExecutor)driver).executeScript("$('element_selector').hover();");
      【解决方案3】:

      这似乎是一个时间问题。

      如果菜单有过渡效果,则添加效果持续时间的延迟:

      new Actions(driver)
        .moveToElement(menu)
        .pause(100) // duration of the transition effect in ms
        .perform();
      
      submenu.click();
      

      您也可以等待目标元素变得可见且稳定(同一位置连续返回两次)。

      【讨论】:

        猜你喜欢
        • 2013-06-22
        • 2013-10-17
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 2013-09-22
        • 2011-07-07
        相关资源
        最近更新 更多