简体   繁体   中英

Cypress, how to iterate through elements?

cy.get('div.infoTextCarousel').find('a.ProductInfoAnchor').should('have.attr', 'href', url)

There are many divs with the same name 'div.infoTextCarousel' and within each there is 'a.ProductInfoAnchor' one of them contains matching href. So what I want is that cypress keep looking for the matching href until it'll be found, but the problem is that it only checks first 'div.infoTextCarousel' and within 'a.ProductInfoAnchor' when it's not able to found the matching href it fails.

You can pass a callback function to a should() in case you need some more sophisticated behaviour. In the below code I am extracting the href attributes, and expecting the list of attributes to contain a specific url:

const url = '/something'
cy.get('div.infoTextCarousel')
 .find('a')
 .should($a => {
     let hrefs = $a.map((i, el) => {
      return Cypress.$(el).attr('href')})

      expect(hrefs.get()).to.contain(url)
  })

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM