使用 Cypress 验证元素是否在视口内

Und*_*ion 9 javascript testing end-to-end cypress

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

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

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

Und*_*ion 11

我已经拼凑了以下似乎可以工作的命令,但很惊讶没有开箱即用的解决方案:

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;
})
Run Code Online (Sandbox Code Playgroud)