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.

JavaScript

Since some of the code is repeated (and you will want other similar tests), bundle it up in a custom command

JavaScript

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

JavaScript

you can add a .filter() to pick the currency child

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement