Getting index of an array with cypress returns a "-1" instead

Viewed 703

I'm trying to get the header of table and put in an array in cypress which I've succesfully done but for some reason when I try to log for example cy.log(tableHeaders.indexOf("Tracking No.")) it returns "-1" but when I log the whole array cy.log(tableHeaders) it returns the proper array and also tried getting the array and index on a separate ".js" file without cypress it runs fine. Am I doing it right? Thank you.

let tableHeaders = []
    cy.get('.rt-table > .rt-thead > .rt-tr').each((headRow) => {
        cy.wrap(headRow).within(() => {
            cy.get('.rt-th').each((cellDataHead) => {
                    cy.log(cellDataHead.text())
                    tableHeaders.push(cellDataHead.text().trim())
            })
        })
    })
    
cy.log(tableHeaders) // Returns the whole array
cy.log(tableHeaders.indexOf("Tracking No.")) // returns -1
cy.log(tableHeaders.indexOf("Merchant Name")) // returns -1

enter image description here

enter image description here

1 Answers

Since JavaScript runs asynchronously, So the below lines are executed before there is anything saved in your array.

cy.log(tableHeaders.indexOf("Tracking No.")) 
cy.log(tableHeaders.indexOf("Merchant Name")) 

To make sure that once your data is saved in the array and then only execute your cy.log statements you can use then().

let tableHeaders = []
cy.get('.rt-table > .rt-thead > .rt-tr').each((headRow) => {
    cy.wrap(headRow).within(() => {
        cy.get('.rt-th').each((cellDataHead) => {
            cy.log(cellDataHead.text())
            tableHeaders.push(cellDataHead.text().trim())
        })
    })
}).then(() => {
    cy.log(tableHeaders)
    cy.log(tableHeaders.indexOf("Tracking No."))
    cy.log(tableHeaders.indexOf("Merchant Name"))
})
Related