I'm trying to find all the affiliate links on the page and the links should have the ff: attributes: target="_blank"
rel="nofollow noopener sponsored"
also I need to check the status of each link. and it should be 200
.
Appreciate all the help.
I'm trying to find all the affiliate links on the page and the links should have the ff: attributes: target="_blank"
rel="nofollow noopener sponsored"
also I need to check the status of each link. and it should be 200
.
Appreciate all the help.
If you can add a data-testid
attribute to your affiliate links, that would make query cleaner and easier to maintain. Otherwise:
cy.get('[target=_blank] [rel="nofollow noopener sponsored"]') // could be simplier with data-test-ids for affiliate links only
.each( $affiliateLink => {
// check links have attributes
expect($affiliateLink).to.have.attr('target', '_blank')
expect($affiliateLink).to.have.attr('rel', 'nofollow noopener sponsored')
// make a request to presumably external domains
cy.request($affiliateLink.prop('href')) // may need to pass some options for request
.its('status')
.should('eq', 200)
})
You can do something like this. Using each()
you can iterate over all the links and then check whether they are broken or not and also check that the links have target="_blank"
and rel="nofollow noopener sponsored"
.
cy.get('a').each(($ele) => {
cy.wrap($ele)
.invoke('attr', 'href')
.then((href) => {
cy.request(href).then((response) => {
expect(response.status).to.eq(200)
})
})
cy.wrap($ele)
.should('have.attr', 'target', '_blank')
.and('have.attr', 'rel', 'nofollow noopener sponsored')
})
Now, If you just want to check that the links have the attributes target
and rel
and then check whether those links return 200, then you can do like:
cy.get('a').each(($ele) => {
if (
$ele.attr('target') == '_blank' &&
$ele.attr('rel') == 'nofollow noopener sponsored'
) {
cy.request($ele.attr('href').trim()).its('status').should('eq', 200)
}
})