如何将 span 标签中包含的值与 Cypress.io 相加?
How to I add up values contained in span tags with Cypress.io?
我需要浏览一组具有特定 class 关联并具有文本值的标签。
例如。我想获取包含文本的跨度下的所有文本,将这些数字相加,并将它们存储在一个变量中,以便将它们与屏幕上的其他内容进行比较:
<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>
我希望将 14.50 的值存储到一个变量中,并将其与屏幕上的其他值进行比较。
在 ID 为 #mySpantext
的 div 中使用上述 html span
标记创建了一个本地服务器。使用 jquery each
函数遍历每个跨度 class 并计算跨度文本的 sum
如下;
var sum = 0;
Cypress.$('.text-old').each(function() {
sum += +Cypress.$(this).text()||0;
});
完整的柏树测试如下;
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)
})
})
})
如下所示的测试结果,在右侧突出显示了跨度文本值;
这里不用jQuery,Cypress有一个'each'方法:https://docs.cypress.io/api/commands/each.html#Syntax
金额将以文本形式表示,因此您需要转换为不连续。如果您的值 > 1,000
,这也会去除逗号
let sum = 0
let expectedVal = 14.50
cy.get('.old-text').each(($li, index, $lis) => {
sum += parseFloat($li.text().replace(',', ''))
if(index == $lis.length - 1) {
assert.equal(expectedVal, sum, 'Expected value equals sum of each line item')
}
}
小心已接受的答案,我无法使用与预期不同的值使其失败...
我需要浏览一组具有特定 class 关联并具有文本值的标签。
例如。我想获取包含文本的跨度下的所有文本,将这些数字相加,并将它们存储在一个变量中,以便将它们与屏幕上的其他内容进行比较:
<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>
我希望将 14.50 的值存储到一个变量中,并将其与屏幕上的其他值进行比较。
在 ID 为 #mySpantext
的 div 中使用上述 html span
标记创建了一个本地服务器。使用 jquery each
函数遍历每个跨度 class 并计算跨度文本的 sum
如下;
var sum = 0;
Cypress.$('.text-old').each(function() {
sum += +Cypress.$(this).text()||0;
});
完整的柏树测试如下;
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)
})
})
})
如下所示的测试结果,在右侧突出显示了跨度文本值;
这里不用jQuery,Cypress有一个'each'方法:https://docs.cypress.io/api/commands/each.html#Syntax
金额将以文本形式表示,因此您需要转换为不连续。如果您的值 > 1,000
,这也会去除逗号let sum = 0
let expectedVal = 14.50
cy.get('.old-text').each(($li, index, $lis) => {
sum += parseFloat($li.text().replace(',', ''))
if(index == $lis.length - 1) {
assert.equal(expectedVal, sum, 'Expected value equals sum of each line item')
}
}
小心已接受的答案,我无法使用与预期不同的值使其失败...