javascriptif-statementcypresscypress-conditional-testing

Cypress: Value of Variable is not saved when go out IF statement


I have a table as image below. I try to check in checkboxes having 'ST - ' text then Delete them.

UI OF TABLE

Here my code:

        cy.get('td').invoke('text').then(text => {
        //1st IF
        if (text !== 'No data available') {
            let hasAuto = false;
            let tableReport = cy.get('#tableA')
            let rpBN = [];

            tableReport.find('tbody tr').each(($row) => {
                const thirdColumnText = $row.find('td:nth-child(3)').text().trim();
                rpBN.push(thirdColumnText)

                //2nd IF
                if (rpBN.some(item => thirdColumnText.includes('ST - '))) {
                    hasAuto = true;
                    const checkbox = $row.find('input[type="checkbox"]');
                    checkbox.trigger('click');
                }
              
            })
            cy.log('hasAuto = ' + hasAuto)

            //3rd IF
            if (hasAuto) {  
                //Click Delete
                cy.get('#deleteBtn').click()

                //Confirmation popup open -> click [Yes] button
                cy.get('#confimeP').contains('Yes').click()  
            }

        }
    })

But after out 2nd IF hasAuto become false and 3rd IF not run.


Solution

  • Because we are dealing with sync and async cypress methods, I would suggest instead to wrap your last if into a then:

    cy.get('td').invoke('text').then(text => {
        //1st IF
        if (text !== 'No data available') {
            let hasAuto = false;
            const tableReport = cy.get('#tableA')
            const rpBN = [];
    
            tableReport.find('tbody tr').each(($row) => {
                const thirdColumnText = $row.find('td:nth-child(3)').text().trim();
                rpBN.push(thirdColumnText)
    
                //2nd IF
                if (rpBN.some(item => thirdColumnText.includes('ST - '))) {
                    hasAuto = true;
                    const checkbox = $row.find('input[type="checkbox"]');
                    checkbox.trigger('click');
                }
    
            }).then(()=>{
               cy.log('hasAuto = ' + hasAuto)
               //3rd IF
               if (hasAuto) {
                   //Click Delete
                   cy.get('#deleteBtn').click()
    
                   //Confirmation popup open -> click [Yes] button
                   cy.get('#confimeP').contains('Yes').click()
               }
            })
        }
    })