I want to extract the balance at the beginning of the test
Comparing two numeric values, use a .then() to remove the currency and convert.
The .then() command is a useful way to apply javascript transforms to a value in a chain of Cypress commands.
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)
})
Since some of the code is repeated (and you will want other similar tests), bundle it up in a custom command
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)
})
Note .invoke('text') extracts all text in the selected element and child elements.
If there are more children of the wallet than just the value, e.g
<div data-testid="wallet">
<div>Amount: </div>
<div class="css-3ro84u">100 kr</div>
</div>
you can add a .filter() to pick the currency child
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
})