java - 使用 Java Selenium 真正验证元素的存在

标签 java selenium selenium-webdriver automation testng

所以我今天遇到了一些奇怪的事情..我有一个测试来验证主页上页脚元素的存在。我使用一个非常基本的方法使用 WebDriverWait(driverWait)..

public boolean verifyCarResearchLnkIsClickable() {
        return driverWait.until(ExpectedConditions.elementToBeClickable(selector.getCarResearch())).isDisplayed();
    }

然后我使用 TestNG 的 Assert 在测试步骤中验证这一点。

Assert.assertTrue(homePage.verifyCarResearchLnkIsClickable());

今天,我的测试通过了,但该元素未显示在屏幕上。我在 Chrome 中使用 jquery 来查看是否可以在检查器中找到该元素,确实如此,但是该元素不在屏幕上。所以发生的事情是我从检查器获得的代码包含我的链接,这就是为什么我的测试通过了,但实际上它没有出现在屏幕上。真正检查这一点的方法是什么?这是正确的方法吗?难道这种情况不会发生吗?在构建过程中可能会发生一些奇怪的事情吗?

最佳答案

ExpectedConditions.elementToBeClickable(loc) 检查:

  • 元素存在
  • 元素的可见性,是否显示
  • 是否已启用,即未主动禁用。

即是否可以点击,无论点击的结果是什么。它可以是一个链接、一个按钮或只是一段静态文本。

当然,您可能应该用功能术语来思考,而不是检查元素的状态来确定“真相”:实际上单击元素并验证侧面-详细效果。

<小时/>

WebDriver 规范 has a lot to say关于“显示性”:

Although WebDriver does not define a primitive to ascertain the visibility of an element in the viewport, we acknowledge that it is an important feature for many users. Here we include a recommended approach which will give a simplified approximation of an element’s visibility, but please note that it relies only on tree-traversal, and only covers a subset of visibility checks.

The visibility of an element is guided by what is perceptually visible to the human eye. In this context, an element's displayedness does not relate to the visibility or display style properties

The approach recommended to implementors to ascertain an element's visibility is based on crude approximations about its nature and relationship in the tree. An element is in general to be considered visible if any part of it is drawn on the canvas within the bounderies (sic) of the viewport. [...]

low-level code演示实际的“显示?”使用的逻辑。看起来很复杂,但评论只是说:

Determines whether an element is what a user would call "shown". This means that the element is shown in the viewport of the browser, and only has height and width greater than 0px, and that its visibility is not "hidden" and its display property is not "none" [...]

在我看来,这些都不能保证该元素一定是人眼可见的,但这对您来说真的很重要吗?

如果我在 headless 浏览器中过夜运行连续的自动化测试,对我来说并不重要。我可能只关心单击元素加载页面、将商品添加到购物车等,这样我就可以验证实际的效果

关于java - 使用 Java Selenium 真正验证元素的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36070298/

相关文章:

java.io.IOException : No space left on device Android 异常

java - 在 Windows 上安装 Eclipse IDE 时出错

java - 失败 - 上下文路径/j2eeapplication 中的应用程序无法启动

javascript - 通过 node.js 和 webdriver 点击随机链接

java - 我如何在 Selenium 中点击这个 href 链接?

java - (Android) 使用 HttpUrlConnection 编写 curl POST 命令

testing - 要有效地使用 Selenium 工具进行自动化测试,应该了解哪些脚本语言

internet-explorer - IE 的 Selenium WebDriver 错误

selenium-webdriver - 网络驱动程序管理器更新引发未处理的错误

selenium - 以另一种方式检查 'checkBox' -> xPath