javascripttestingcypressend-to-end

How to use then() and get the value in Cypress


I have a span element which value is 2. I would like to check if the value is greater than 0, but after checked online and implemented every method, it did not work...

Here is the console when I log the $span

enter image description here

I understand that Cypress works asynchronously, so I use .then() to get the text of element. How can I get the value of 2 and do the follow if-else?

HTML

<div>
  <span class="badge ml-1 badge-primary">2</span>
</div>
   cy.get(".badge.ml-1.badge-primary").then(($span)=> {
     if($span.text().includes(0)) {
      doFunction1()
    } else {
      cy.get(xxxxx)
    }
 )}

Solution

  • Do it by chaining conversions methods to go from from element -> text -> number

    cy.get(".badge.ml-1.badge-primary")  // get element
      .invoke('text')                    // to text
      .then(text => +text)               // to number
      .then(value => {
        if(value > 0) {                  // now test the number
          doFunction1()
        } else {
          cy.get(xxxxx)
        }
      })
    

    Waiting for value 2

    Using built-in Cypress retry instead of manual re-querying.

    cy.get(".badge.ml-1.badge-primary")  // get element
      .invoke('text')                    // to text
      .then(text => +text)               // to number
      .should('eq', 2)                   // wait for value 2 (retry)
      .then(() => {
        doFunction1()                    // now doFunction
      })