【问题标题】:Verify Element Is Within Viewport With Cypress使用 Cypress 验证元素是否在视口内
【发布时间】:2019-11-05 14:25:20
【问题描述】:

Cypress 的 visible 匹配器根据各种因素将元素视为可见,但它没有考虑视口,因此滚动到屏幕外的元素仍被视为可见。

我需要测试指向页面锚点的链接是否正常运行。单击链接后,页面将滚动到链接的 href (example/#some-id) 中定义的 id 元素。

如何验证元素是否在视口内?

【问题讨论】:

标签: javascript testing cypress end-to-end


【解决方案1】:

我拼凑了以下命令,这些命令到目前为止似乎可以工作,但很惊讶没有开箱即用的解决方案:

Cypress.Commands.add('topIsWithinViewport', { prevSubject: true }, subject => {
  const windowInnerWidth = Cypress.config(`viewportWidth`);

  const bounding = subject[0].getBoundingClientRect();

  const rightBoundOfWindow = windowInnerWidth;

  expect(bounding.top).to.be.at.least(0);
  expect(bounding.left).to.be.at.least(0);
  expect(bounding.right).to.be.lessThan(rightBoundOfWindow);

  return subject;
})

Cypress.Commands.add('isWithinViewport', { prevSubject: true }, subject => {
  const windowInnerWidth = Cypress.config(`viewportWidth`);
  const windowInnerHeight = Cypress.config(`viewportHeight`);

  const bounding = subject[0].getBoundingClientRect();

  const rightBoundOfWindow = windowInnerWidth;
  const bottomBoundOfWindow = windowInnerHeight;

  expect(bounding.top).to.be.at.least(0);
  expect(bounding.left).to.be.at.least(0);
  expect(bounding.right).to.be.lessThan(rightBoundOfWindow);
  expect(bounding.bottom).to.be.lessThan(bottomBoundOfWindow);

  return subject;
})
猜你喜欢
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 2015-09-05
相关资源
最近更新 更多