Skip to content Skip to sidebar Skip to footer

Exit From While Loop With If/else In Cypress

I am writing a test case which requires me to reload the page N number of times, and compare its title for a value, if that value does not exists then break the while loop without

Solution 1:

cy.title() is asynchronous (proof is, you need to use .then()), so, the entire while loop ends even before the first .then() triggers. That's how asynchronism works.

You need another approach :

it("Visiting Google", async function () {
    var webUrl = 'https://html5test.com/'
    cy.visit(webUrl)

    for (let i = 0; i < 5; i++) { // You can't await in a 'while' loop

        const $text_data = await cy.title();

        if ($text_data.includes('HTML')) {
            cy.log(" --> ITERATION = ", i)
            cy.reload()
        }
        else {
            cy.log("Unknown website")
            break;
        }
    }
})

Post a Comment for "Exit From While Loop With If/else In Cypress"