Reputation: 678
I have this DOM:
div<data-hook='cart-content'>
<section data-hook="item">
<h3 data-hook='product-name'>Winter Feel Package</h3>
<section data-hook="item">
<h3 data-hook='product-name'>Christmas Wreath</h3>
I want to verify that my item name exist in the DOM (one time I will test it using the first value "Winter Feel Package" and then with "Christmas Wreath") however when I use the naive approch of 'cy.get' I am getting the only first item.
this is what I tried: first I tried the naive approach:
getProductName(itemName){
cy.get("iframe[title='Cart Page']").its('0.contentDocument')
.should('exist').its('body')
.should('not.be.undefined').then(cy.wrap)
.find("div[data-hook='item-list'] section[data-hook='item'] h3[data-hook='product-name']")
.then(($elem)=>{
expect($elem).to.have.text(itemName)
})
}
which returned me the first element no matter what.
this was my second go but here I got an empty array with no elements:
getProductName(itemName){
cy.get("iframe[title='Cart Page']").its('0.contentDocument')
.should('exist').its('body')
.should('not.be.undefined').then(cy.wrap)
.find("div[data-hook='item-list'] section[data-hook='item'] h3[data-hook='product-name']")
.then(($elem)=>{
let items = $elem.map((i, el)=>{
return Cypress.$(el).get("h3[data-hook='product-name']")
})
expect(items.get()).to.contain(itemName)
// expect($elem).to.have.text(itemName)
})
}
The DOM is quite simple and I am struggling how to do it , if it was java I would put it inside List and iterate through this list but here I truly lose myself.
Upvotes: 0
Views: 406
Reputation:
I recommend the cypress-iframe package because it's the safest way to ensure the iframe is fully loaded, without clutter in your test.
getProductName(itemName) {
cy.iframe('[title="Cart Page"]')
.contains('h3[data-hook="product-name"]', itemName); // gets just the h3 with text
}
Upvotes: 1