Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text from two elements, convert them to a number and add them in cypress?

I'm moving tests from protractor to cypress.

I have two elements like below. I want to get the number and add them and store them in a variable.


<span id="num-2">20</span>

In protractor I wrote it like below

var totalCount =
      parseInt(element(by.id('num-1')).getText()) +
      parseInt(element(by.id('num-2')).getText());

I can't figure out how to do it in Cypress.

like image 415
autotest Avatar asked Oct 29 '25 10:10

autotest


1 Answers

You can achieve aliases/variables and get. The trick is that get, invoke, or similar are effectively async and you can't really effectively await cypress operations. Instead you can get the first number, parse it, get the second number, parse it, add the numbers and assert/expect:

const expectedTotal = 42;

// get element with id #num-1
cy.get('#num-1').then(($num1) => {
  // parse text to int/number
  const num1 = parseInt($num1.text());

  // get element id #num2
  cy.get('#num-2').then(($num2) => {
    // parse text to int/number
    const num2 = parseInt($num2.text());
    
    // expect/assert number total equal to some expected total
    expect(num1 + num2).toEqual(expectedTotal);
  });
});

Hopefully that helps!

like image 167
Alexander Staroselsky Avatar answered Oct 31 '25 00:10

Alexander Staroselsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!