【问题标题】:In Cypress how to count elements containing the text?在赛普拉斯如何计算包含文本的元素?
【发布时间】:2020-10-14 13:40:16
【问题描述】:

在 Cypress 中,我试图计算有多少元素(在本例中为 li 中有多少按钮)包含文本。当使用“contains”时,返回的项目数总是等于一个,因为“contains”只给出文档中包含搜索文本的第一个项目。

          cy.get('li')
            .contains('button', 'Submit')
            .its('length')
            .then(elLength => {
              // I want to test here the number of all buttons in li elements containig word 'Submit'
             }

当然,这样不行,因为 elLength 始终为 1(如果未找到项目,则为 0)。

赛普拉斯有没有其他方法可以返回所有带有文本的元素,我可以计算它们?

【问题讨论】:

  • 最后,在获得了非常鼓舞人心的反对票后;),我找到了解决这个问题的方法:cy.get('li').then($el => { cy.wrap($el).find(Cypress.$('button:contains("Submit")')) .its('length').should('eq', expected_number)

标签: automated-tests cypress


【解决方案1】:

Cypress get() 使用与 jQuery 相同的选择器。因此,您可以使用:contains 来获取包含文本的所有元素。
由于 Cypress contains() 仅包含可见的 DOM 元素,您必须添加 :visible 才能获得相同的行为。

为了确保只有一个可见按钮包含“提交”:

cy.get('button:visible:contains("Submit")').should('have.length', 1);

要确保“li”元素内只有一个可见按钮包含文本“提交”:

cy.get('li button:visible:contains("Submit")').should('have.length', 1);

计算包含一个或多个可见“提交”按钮的“li”元素:

cy.get('li:has(button:visible:contains("Submit"))').should('have.length', 1);

【讨论】:

    【解决方案2】:

    如果您知道需要有该标签的按钮数量合适,您可以尝试:

    cy.get('li').then($el => {
        cy.wrap($el).find(".button").then($els => {
            expect($els.filter(index => $els.eq(index).is(':contains(Submit)'))).to.have.length(your_amount);
     })
    

    【讨论】:

    • 谢谢你,你的回答对我帮助很大。
    猜你喜欢
    • 2022-01-07
    • 2019-08-20
    • 2018-11-09
    • 2023-02-08
    • 1970-01-01
    • 2019-02-12
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多