如何使用 Cypress.io 添加 span 标签中包含的值?

ton*_*cks 5 mocha.js chai cypress

我需要检查一组具有与其关联的特定类并具有文本值的标签。

例如。我想获取包含文本的跨度下的所有文本,将这些数字相加,并将它们存储在变量中,以便将它们与屏幕上的其他内容进行比较:

<span class="property-ut text-old">12.50</span>
<span class="property-ut text-old"></span>
<span class="property-ut text-old"></span>
<span class="property-ut text-old">.50</span>
<span class="property-ut text-old">1.50</span>
Run Code Online (Sandbox Code Playgroud)

我希望将 14.50 的值存储到一个变量中,并将其与屏幕上的其他值进行比较。

soc*_*way -1

span在带有 id 的 div 中使用上述 html 标签创建了本地服务器#mySpantext。使用jqueryeach函数迭代每个span类并计算sumspan文本的值,如下所示;

var sum = 0;
Cypress.$('.text-old').each(function() {
  sum += +Cypress.$(this).text()||0;
});
Run Code Online (Sandbox Code Playgroud)

完整的柏树测试如下所示;

describe('Sum of the span element values in Cypress', function() {
  it('Sum of the span element', function() {
    cy.visit('http://localhost:8080/test')
    cy.get('#mySpantext').find('span').then(() => {     
    var sum = 0;
    Cypress.$('.text-old').each(function() {
      sum += +Cypress.$(this).text()||0;
    });
    cy.log("Total sum of all span elements:"+sum);
    expect(sum).to.equal(14.5)
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

测试结果如下所示,在右侧突出显示了跨度文本值; 在此输入图像描述