I have a sitemap looks like this:
Then what I would like to do in cypress is to visit each link on the list and insert some test in every link.
Yes, I can just click on it, but my main problem is the list is constantly changing in number so clicking links is not an option.
What I am thinking is to get all the links and push them into an array and visit. How can I do that?
CodePudding user response:
Cannot really tell what your testing aim is, but here are two approaches that are pretty much text-book
Test the link is valid
cy.get('li a')
.then($li => {
return [...$li].map(el => el.href)
})
.as('hrefs')
cy.get('@hrefs')
.then(hrefs =>
hrefs.forEach(href => {
cy.request({url: href, failOnStatusCode: false})
.then(response => {
if (response.statusCode !== 200) {
// do what you want with bad link
}
})
})
})
Test the link is clickable
cy.get('li').each($li => {
cy.wrap($li).click()
// do what you want with new page
cy.go('back')
})
CodePudding user response:
Jason is correct, but (presuming the list doesn't change each time the page loads), you can try to query inside the .each()
by index
cy.get('li').each(($li, index) => {
cy.get('li').eq(index).click()
// do what you want with new page
cy.go('back')
})
If that does not work, usually a recursive function will handle this scenario.
CodePudding user response:
You can do like this if you want to visit all the links and then do some assertion inside the link
var links = []
cy.get('a')
.each(($ele) => {
links.push($ele.attr('href'))
})
.then(() => {
links.forEach((link) => {
cy.visit(link)
//Add some test here
cy.get('selector').should('be.visible').and('have.text', text)
})
})
Or if you just want to check that the link returns 200 or not, you can do this:
var links = []
cy.get('a')
.each(($ele) => {
links.push($ele.attr('href'))
})
.then(() => {
links.forEach((link) => {
cy.request(link, {failOnStatusCode: false}).then((response) => {
expect(response.status).to.eq(200)
})
})
})