javascript - 单击按钮捕获滚动

标签 javascript testing protractor end-to-end

我有一个网页,点击一个按钮就会滚动到网页的下一部分。有人可以建议如何捕获该卷轴吗?代码在 anchor 标记中,href 指向 # 以滚动到页面中的下一部分。我不确定如何验证滚动是否真的有效?

最佳答案

您可以通过使用 getBoundingClientRect() 检查相对于视口(viewport)的位置来检查 anchor 是否在窗口顶部滚动:

browser.get('https://www.w3.org/TR/webdriver');
$("[href='#capabilities']").click();

// assert that the position of the anchor relative to the top border of the window is less than 16 pixels.
var anchor = $('#h-capabilities');
var isCloseToTop = browser.executeScript(e => !(e.getBoundingClientRect().top >> 4), anchor);
expect(isCloseToTop).toBeTruthy();

请注意,如果 anchor 位于文档的最底部,则 anchor 不会位于窗口的顶部,而是位于其中的某个位置。 因此,您还应该使用更通用的解决方案来考虑这种情况:

browser.get('https://www.w3.org/TR/webdriver');

$("[href='#informative-references']").click();
expect(isScrolledTop($('#h-informative-references'))).toBeTruthy();

function isScrolledTop(element) {
  return browser.executeScript(function(elem) {
    var doc = elem.ownerDocument,
      viewHeight = doc.defaultView.innerHeight,
      docBottom = doc.documentElement.getBoundingClientRect().bottom,
      box = elem.getBoundingClientRect();
    return box.top > -1 && (box.top < 25 || (docBottom - viewHeight) < 25);
  }, element);
}

关于javascript - 单击按钮捕获滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39967543/

相关文章:

java - Quarkus 在@QuarkusTest 套件中没有@Inject beans

ruby-on-rails - 用should测试多个关联,应该属于使用外键

javascript - 我找不到使用 Protractor 选择此链接的方法

node.js - 在 TFS 上构建想要从 Node.js 测试项目复制可执行文件

javascript - TypeScript - 将多个接口(interface)组合成一个

javascript - Dojo Twitter Bootstrap 和 Dijits

javascript - 单击按钮时运行函数

javascript - 将 "this"传递给 .on 函数似乎不起作用

loops - 使用 Selenium WebDriver 在一次测试中遍历多个浏览器是个好主意吗?

javascript - 在 Protractor 中加载页面之前单击对话框