如何return一个元素在网页上出现的次数

How to return the number of occurences of an element on a webpage

网页上有很多图片显示.img 我想知道如何获取出现的图像数量 return 作为用于其他测试的变量

我写了这个,但这不会产生任何东西,只是一个空变量

cy.get('.img').then(($img) => {
   cy.wrap($img).its('length').then((val)=>{
      return val;
   });
})

如何 return 出现的次数(不使用任何断言,如应该有长度)?我尝试的其他解决方案产生了 sync/async 个错误

你会想要做这样的事情。

// maybe have this in beforeEach()
cy.get('.img').its('length').as('numImgs')


// later in a test
cy.get('@numImgs') // to get number of occurrences 

如果你想在同一个测试套件或其他测试套件中的其他测试中使用长度值,你可以将值保存在 Cypress.env 中,然后像这样在任何你想使用的地方使用它:

cy.get('.img')
  .its('length')
  .then((len) => {
    Cypress.env('imgLen', len)
  })

那么在你的测试中,你可以这样使用它:

Cypress.env('imgLen')
cy.log(Cypress.env('imgLen')) //logs img length
cy.get('selector').should('have.length', Cypress.env('imgLen')) //Asserts the length