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

I'm moving tests from protractor to cypress.I have two elements like below. I want to get the num

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.

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.

Share Improve this question asked Jul 15, 2021 at 18:20 autotestautotest 632 silver badges5 bronze badges 2
  • Are you planning to assert/expect the two values equal some specific value? It's actually anywhere near as straightforward to save values to a variable within a single test. – Alexander Staroselsky Commented Jul 15, 2021 at 18:57
  • yes, I need to assert the total count with another value. – autotest Commented Jul 15, 2021 at 18:59
Add a ment  | 

1 Answer 1

Reset to default 5

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!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745429375a4627322.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信