MillturnK
MillturnK

Reputation: 91

In Cypress, my table count comes too late for evaluation

I am passing in a var "rows" to be allocated into my Cypress table length function (# of table rows), but it is being set AFTER I need to use it in a later evaluation (so that always fails as it is still 0). This is no doubt due to my poor Javascript knowledge but how can I ensure it gets set before it gets used please?

Code:

    // get a count of all the current table rows
    let rows = 0;
    cy.get('table').find('tr').its('length')
        .then((l) => {
          console.log(l + ' rows detected')
          rows = l
          console.log(' rows set to ', rows)
          // NOTE this is set to 18 but only
          // after I have done the evaluation below
        })
    cy.get('table').find('tr').its('length')
      .should('be.lt', rows)
     //this is always still 0 at this point

Upvotes: 0

Views: 239

Answers (2)

ebanster
ebanster

Reputation: 1086

Putting it inside the chain will do the trick:

// get a count of all the current table rows
    let rows = 0;
    cy.get('table').find('tr').its('length')
        .then((l) => {
          console.log(l + ' rows detected')
          rows = l
          console.log(' rows set to ', rows)
          // NOTE this is set to 18 but only
          // after I have done the evaluation below

       //this should now work
       cy.get('table').find('tr').its('length')
       .should('be.lt', rows) 

    })

Upvotes: 1

MillturnK
MillturnK

Reputation: 91

Actually, this Cypress article explains why vars will be set out of sync and how to deal with this using closures: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Closures

Upvotes: 0

Related Questions