Skip to content
Advertisement

Getting the numerical value from an element in Cypress

I currently have a parent element '[data-testid="wallet"]' with a child <div class="css-3ro84u">0 kr</div>

I want to extract the balance at the beginning of the test, and then compare that value to the end of the test when the user has spent their balance to purchase an item.

For example, if the user has 100kr at the beginning of the test and then spends 25kr, I want to assert that the updated value at the end of the test is 75kr.

My question is: how do I extract the numerical value from <div class="css-3ro84u">0 kr</div> in Cypress?

Advertisement

Answer

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
})
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement