Search code examples
node.jsautomationcypress

How to do calculations in cypress testing


I need to go through a group of tags that have a specific class associated with them and have a value

    <div class="ratinglabel col-6">
        <label>Area 1: Professional Engagement 
            <span test-data="area_1_Scor">
                (4/16)
            </span>
        </label>
    </div>

and i want to find (4/16*5) and save them in var to compare them with another value

i did this :

    cy.get('[test-data="area_1_Scor"]', { timeout: 2000 })
    .then(function($ele) {   
      var countOfElements = $ele*5;
      cy.log(countOfElements);
    });
  })

and

   cy.get('[test-data="area_1_Scor"]').each(($li, index, $lis) => {
      var sum = 0;
      Cypress.$('[test-data="area_1_Scor"]').each(function() {
        sum = +Cypress.$(this).text()*5||0;
      });
      cy.log("Total sum of all span elements:"+sum);
      
      })

but log appear as NaN in first case and 0 in second So how can i do it ?


Solution

  • You're almost there (first block), but you need to 1) extract the text from the element and 2) parse the text into numbers

    cy.get('[test-data="area_1_Scor"]', { timeout: 2000 })
      .invoke('text')
      .then(text => {
        const numerator = +text.split('/')[0].replace('(', '')
        const denominator = +text.split('/')[1].replace(')', '')
        const countOfElements = numerator * 5 / denominator;
        cy.log(countOfElements);
      });
    })
    

    Your 2nd block indicates there's multiple elements, if so use .each() like this

    let sum = 0;
    cy.get('[test-data="area_1_Scor"]', {timeout: 2000})
      .each($el => {
    
        cy.wrap($el).invoke('text')
          .then(text => {
            const numerator = +text.split('/')[0].replace('(', '')
            const denominator = +text.split('/')[1].replace(')', '')
            const countOfElements = numerator * 5 / denominator;
            sum += countOfElements
          }) 
      })
    })
    .then(() => cy.log(sum))
    

    To test the math

    const times5 = (text) => {
      const numerator = +text.split('/')[0].replace('(', '')
      const denominator = +text.split('/')[1].replace(')', '')
      return Math.round(numerator * 5 / denominator)
    }
    
    let sum = 0;
    cy.get('[test-data="area_1_Scor"]', {timeout: 2000})
      .each($el => {
        cy.wrap($el).invoke('text')
          .then(times5)                   // text is passed in automatically
          .then(result => sum += result)
      })
    })
    .then(() => cy.log(sum))
    

    So you can check the function with

    cy.log(times5("(4/16)"))