What's the difference between `visible?` and `present?`?

假装没事ソ 提交于 2019-12-01 20:47:21

The difference between visible? and present? is when the element does not exist in the HTML.

When the element is not in the HTML (ie exists? is false):

  • visible? will throw an exception.
  • present? will return false.

I tend to stick with present? since I only care if a user can see the element. I do not care if it cannot be seen due to it being hidden via style, eg display:none;, or not being in the DOM, eg it got deleted. I would only use visible? if the application actually treats the element not being in the DOM as a different meaning than being in the DOM but not visible.

For example, given the page:

<html>
  <body>
    <div id="1" style="block:display;">This text is displayed</div>
    <div id="2" style="block:none;">This text is not displayed</div>
  </body>
</html>

You can see the difference when looking for a div that is not on the page:

browser.div(:id => '3').visible?
#=> Watir::Exception::UnknownObjectException

browser.div(:id => '3').present?
#=> false

For elements on the page, the two methods will be the same:

browser.div(:id => '1').visible?
#=> true
browser.div(:id => '1').present?
#=> true

browser.div(:id => '2').visible?
#=> false
browser.div(:id => '2').present?
#=> false

A comparison of these two methods along with exists? can be found in the Watirways book.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!