【问题标题】:Cypress - iterating through same elements with different values?赛普拉斯 - 迭代具有不同值的相同元素?
【发布时间】:2021-02-08 23:37:40
【问题描述】:

我有这个 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>

我想验证我的项目名称是否存在于 DOM 中(有一次我将使用第一个值“Winter Feel Package”然后使用“Christmas Wreath”对其进行测试)但是当我使用 'cy. get' 我得到了唯一的第一项。

这是我尝试过的: 首先我尝试了幼稚的方法:

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)
        })
    }

无论如何它都返回了我的第一个元素。

这是我的第二次尝试,但在这里我得到了一个没有元素的空数组:

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)
        })
    }

DOM 非常简单,我正在努力如何去做,如果是 java 我会把它放在 List 中并遍历这个列表,但在这里我真的迷失了自己。

【问题讨论】:

    标签: javascript cypress ui-testing


    【解决方案1】:

    我推荐使用 cypress-iframe 包,因为它是确保 iframe 完全加载的最安全方法,不会在您的测试中造成混乱。

    getProductName(itemName) {
    
      cy.iframe('[title="Cart Page"]')  
        .contains('h3[data-hook="product-name"]', itemName); // gets just the h3 with text
    }
    

    【讨论】:

    • 好的,这不是一个断言,它不会在我的测试中断言文本存在。
    • @tupacshakur 你错了,.contains() 会断言文本在h3 中存在。您可以通过输入一些不存在的文本来验证。
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2022-01-07
    相关资源
    最近更新 更多