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

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

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

如何验证元素在视口中?

qkjqkj000 回答:使用Cypress验证元素是否在视口中

我整理了以下似乎到目前为止可以使用的命令,但惊讶的是没有现成的解决方案:

Cypress.Commands.add(`topIsInWithinViewport`,{ 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`,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
})
本文链接:https://www.f2er.com/3158833.html

大家都在问