Home > Mobile >  Accessing href attribute using invoke() in each() Cypress
Accessing href attribute using invoke() in each() Cypress

Time:03-05

I am new to Cypress and I'm trying to access the href attribute for each div tag from a group using invoke() but it gives error. Can someone suggest how you do it?

cy.get('.bms-scoreboard__game-tile--mls').each(($el,index,$list) => {
            $el.get('a')
                .invoke('attr','href')
                .then(href => {
                    cy.request(href)
                        .its('status')
                        .should('eq',200)
                })
        })

CodePudding user response:

I don't think .get() is appropriate - it only works from the <body> not from each '.bms-scoreboard__game-tile--mls'.

Try .find() instead

With jQuery operators

cy.get('.bms-scoreboard__game-tile--mls')
  .each(($el,index,$list) => {
    const href = $el.find('a').attr('href')
    cy.request(href)
      .its('status')
      .should('eq', 200)
  })
})

or with Cypress operators

cy.get('.bms-scoreboard__game-tile--mls')
  .each(($el,index,$list) => {
    cy.wrap($el).find('a')
      .invoke('attr','href')
      .then(href => {
        cy.request(href)
           .its('status')
           .should('eq',200)
      })
  })
})

or move "find" into first selector

cy.get('.bms-scoreboard__game-tile--mls a')
  .each($a => {
    const href = $a.attr('href')
    cy.request(href)
      .its('status')
      .should('eq', 200)
  })
})

CodePudding user response:

$el is a JQuery element, and not itself in the Cypress chain. You'll need to use cy.wrap() to use it in a Cypress chain.

cy.get('.bms-scoreboard__game-tile--mls').each(($el,index,$list) => {
            cy.wrap($el)
                .get('a')
                .invoke('attr','href')
                .then(href => {
                    cy.request(href)
                        .its('status')
                        .should('eq',200)
                })
        })
  • Related