我想在测试开始时提取余额
比较两个数值,使用.then() 删除货币并进行转换。
.then() 命令是一种将 javascript 转换应用于赛普拉斯命令链中的值的有用方法。
cy.get('[data-testid="wallet"]')
.invoke('text') // get text "100 kr"
.then(text => +text.replace('kr', '').trim()) // remove currency and convert
.then(initial => {
// spend 25 kr
cy.get('[data-testid="wallet"]')
.invoke('text')
.then(text => +text.replace('kr', '').trim())
.should('eq', initial - 25)
})
由于某些代码是重复的(并且您将需要其他类似的测试),请将其捆绑在自定义命令中
Cypress.Commands.add('currency', (selector) => {
cy.get(selector)
.invoke('text') // get text
.then(text => +text.replace('kr', '').trim()) // remove currency and convert
})
cy.currency('[data-testid="wallet"]')
.then(initial => {
// spend 25 kr
cy.currency('[data-testid="wallet"]')
.should('eq', initial - 25)
})
注意.invoke('text')提取所选元素和子元素中的所有文本。
如果钱包的子节点不只是值,例如
<div data-testid="wallet">
<div>Amount: </div>
<div class="css-3ro84u">100 kr</div>
</div>
您可以添加.filter() 来选择货币子项
Cypress.Commands.add('currency', (selector) => {
cy.get(selector)
.children()
.filter((index, child) => child.innerText.includes('kr')) // filter
.invoke('text')
.then(text => +text.replace('kr', '').trim()) // convert
})