我在我的网站上添加了视觉上隐藏的跳转链接,当它们被聚焦时会出现(类似于 GitHub,只需在主页上按一次 Tab)。
我想用 Capybara 测试这种行为。我无法检查例如'visibility: true/false',因为链接并没有真正隐藏(否则屏幕阅读器不会看到它们),而只是通过绝对定位从视口(viewport)中移出。当它们被聚焦时,它们被放置在视口(viewport)中的原始位置。
所以我想我必须检查 X 和 Y 坐标,但 Capybara 似乎没有提供获取它们的本地方法?这是真的?如果是这样,我将如何获得它们,例如一个元素'#jump_to_content'?通过执行一些 JavaScript?
更新
我在这里找到了一些灵感:https://content.pivotal.io/blog/testing-accessibility-with-rspec-and-capybara
但这似乎不适用于我的配置:
link.native.location
NoMethodError: undefined method `location' for #<Capybara::Poltergeist::Node tag="a">
最佳答案
你是对的,Capybara 没有提供获取页面中元素位置的本地方法,但如果你可以访问 jQuery,你可以使用 Capybara's page.evaluate_script
方法来轻松确定元素的位置。它看起来像这样:page.evaluate_script("$('.menu > div:nth-child(1)').offset().top")
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent
请注意
While it is possible to get the coordinates of elements with visibility:hidden set, display:none is excluded from the rendering tree and thus has a position that is undefined.
关于javascript - RSpec 和 Capybara : How to get the horizontal and vertical position of an element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29209518/