2

I am new in cypress, I have created a generic function which is checking the count of rows in cypress and returning the count. I have used for loop, and returning the count under the chain. This function is correctly calculating count but if I call under the second function I am getting as undefined or null I have defined a global variable and below generic function where I am trying to return the count Calling under second function, in which I am getting rowcount_val as undefined

let rowcount_val = 0

function checkrowcount() {
    var count = 0;
    var val = ""
    for (let i = 1; i <= 10; i++) {
        cy.get(".rt-tbody>div:nth-child(" + i + ")>div>div:nth-child(1)").then((
            e) => {
            val = e.text();
            if (val.length > 1) {
                count++
            }
        })
    }
    cy.then(() => {
        return cy.log("count*" + count).then(() => {
            return count;
        })
    })
}
When('click on Add button', function() {
    cy.then(() => {
        rowcount_val = checkrowcount();
        cy.log("rowcountvalue is ******" + rowcount_val)
    })
})
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • `checkrowcount` has no `return` statement. It always returns `undefined`. Asynchronous code using Callbacks and Promises is one of the fundamental features of JS that you need to learn the basics of. – Quentin Mar 20 '23 at 13:59

1 Answers1

5

You are overriding the global variable with an undefined return value from the function.

To mkae it work, change

rowcount_val = checkrowcount();

to

checkrowcount();
Cara Gee
  • 129
  • 6
  • Thank you for answering but the value it suppose to return I want to save in a variable and use further...how do I store in the variable? – Aman Mishra Mar 20 '23 at 10:44
  • This changes the code so that instead of updating the global variable with the return value, it throws the return value away. For a question about getting the return value, that doesn't seem helpful. – Quentin Mar 20 '23 at 13:59
  • 3
    This is valid, the variable is already updated by closure. You shouldn't be using both closure and return value - at the minimum it's confusing code. – Fay Fulbright Mar 20 '23 at 21:08