Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the sum of a list of numbers stored in a Cucumber Feature File data table in Cypress framework?

In my Cucumber/Cypress test framework, I am trying to add a list of numbers together. They are defined in the below Feature File:

 When add the following pokemon to my cart
     | pokemonName | price |
     | bulbasaur   | 64    |
     | ivysaur     | 142   |
     | venusaur    | 263   |

Here is my Step Definition:

When('I add the following pokemon to my cart', (dataTable) => {
  let totalAmount;
  dataTable.hashes().forEach(elem => {
    totalAmount += elem.price
  });
  cy.log(totalAmount)
});

Actual Result:
When I run this test, the totalAmount value logged is 64142263.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected Result:
I want the actual result to be the sum of the 3 prices – 469

I understand what the code is doing is appending the values together as strings, but I want to know how I can treat these values as numbers, so I can get the sum of them combined.

>Solution :

Cypress is most likely returning the text as a string instead of a number. When using += with a string, it will addend the string to the current string ('123' += '456' => '123456') instead of actually adding the numbers.

You could simply cast the text returned to a Number, if you did not want to use the unary plus operator.

...
totalAmount += Number(ele.price)
...

If picking this approach, it would probably be helpful to define a type for totalAmount

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading