问题
我正在使用 Java 和 Selenium 为我公司的网站编写自动化测试。现在我正在编写涉及单击链接的测试,并验证该链接是否指向正确的位置。我们有一个时事通讯弹出窗口(来自 BounceExchange)会在非常不可预测的时间出现,并且会导致 ElementClickInterceptedExceptions。这是异常消息:
org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element <li id="menu-item-78096" ... is not clickable at point (x, x). Other element would receive click <div class="bx-slab">...</div>
我尝试过的
使用 JavaScript 点击
我一直在使用 driver.findElement(By...).click()
单击 WebElements ,我读过这是测试 UI 时单击内容的最佳方式。我尝试过像 this 这样的 JavaScript 点击
但这并没有奏效,页面只是挂起,屏幕上弹出窗口。
关闭弹出窗口
这是我最成功的领域,但它仍然没有完全发挥作用。这是我的点击方法:
public void click(By elementBy) {
By bounceExchange = By.className("bx-slab");
By bounceExchangeClose = By.className("bx-close");
//close bouncex if its open
if(elementExists(bounceExchange)) {
WebElement bounceX = driver.findElement(bounceExchange);
if(bounceX.isDisplayed()) {
System.out.println("Closing bounce exchange");
try {
driver.findElement(bounceExchangeClose).click();
}
catch(Exception e) {
//ignore
}
}
}
driver.findElement(elementBy).click();
}
通过查看 HTML,我知道弹出窗口上的关闭按钮有一个类“bx-close”。 此方法有时成功关闭弹出窗口,但随后正在测试的链接从未被单击,并且测试失败。
按退出键
我了解到,当弹出窗口出现在屏幕上时按退出键会使它消失。
我尝试了两种方法来做到这一点
1.使用Actions
Actions actions = new Actions(driver);
actions.keyDown(Keys.ESCAPE).build().perform();
actions.keyUp(Keys.ESCAPE).build().perform();
但是这种方式给了我一个非法参数错误,因为转义键不是修饰键。
我已经尝试过 WebDriver 的 sendKeys
:
driver.findElement(By.tagName("html")).sendKeys(Keys.Escape);
这种方法对我来说也不起作用。
弹出窗口的 HTML
<div class="bx-slab">
<div class="bx-align">
<div class="bx-creative bx-creative-874700" id="bx-creative-874700">
<div class="bx-wrap">
<a id="bx-close-inside-874700" class="bx-close bx-close-link bx-close-inside" href="javascript:void(0)" data-click="close">
<svg class="bx-close-xsvg" viewBox="240 240 20 20">..</svg>
</a>
...
</div>
所以我的问题是,关闭这个不可预测的弹出窗口的可靠方法是什么,这样我就可以停止收到 ElementClickInterceptedExceptions?
最佳答案
对于在执行过程中意外出现的弹出窗口,事件处理程序是最佳选择。这个想法是用 EventFiringWebDriver
包装您的常规驱动程序,然后让您注册某些事件的处理程序;其中有很多可供选择。创建 EventFiringWebDriver
非常简单:
EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver);
EventHandler handler = new EventCaptures();
eventDriver.register(handler);
// Do stuff here
eventDriver.unregister(handler);
handler
是您将在一个单独的类中实现的方法,该类派生自 WebDriverEventListener
,它会重写该类的基方法之一。有很多可供选择,但对于本例来说,beforeClickOn
可能是一个不错的选择。下面是一个示例:
public class EventCaptures implements WebDriverEventListener{
@Override
public void beforeClickOn(WebElement arg0, WebDriver arg1) {
By bounceExchangeClose = By.className("bx-close");
if (arg1.findElements(bounceExchangeClose).size() > 0) {
arg1.findElement(bounceExchangeClose).click();
}
}
// Other listener overrides here...
}
所以基本上,每当您点击某些内容时,该处理程序都会运行并检查以确保弹出窗口不存在(如果存在,则将其关闭)。其他人提到了等待和检查,但是如果弹出窗口不可预测,这会变得非常困惑,因为您必须在代码中的所有地方调用该检查,而使用此方法它会自动发生。使用完处理程序后,只需注销该处理程序即可。
有关更多信息,这是一个很好的资源:https://www.softwaretestingmaterial.com/webdriver-event-listeners/
关于java - 如何阻止电子邮件通讯弹出窗口拦截点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184159/