Search code examples
testingwebcypresscypress-intercept

cypress .each() does not pause on cy.wait


shouldn't cypress wait between iterations if there is cy.wait() or setTimeout in there?

describe("Store", () => {
    it("changes category on click", () => {
        cy.visit("/store");
        cy.intercept("https://fakestoreapi.com/products/category/*").as(
            "getProducts",
        );
        cy.get(".category").each((category, i, l) => {
            category.click();
            cy.wait("@getProducts");
            console.log(i);
        });
    });
});

but when I run this all the buttons are getting called, it's not waiting for the API call

Output


Solution

  • The .each() does pause for cy.wait() inside the loop, but the console.log() does not.

    All the cy commands you have in the test are run separately on a queue, but javascript code like console.log are executed immediately.

    To see the difference, execute the console.log on the queue like this

    cy.get(".category").each((category, i) => {
      category.click()
      cy.wait("@getProducts")
      cy.then(() => console.log(i))   // console.log on the queue in sync with other cy.* 
    })
    

    Here's my dev-tools console, the app and the test are in sync:

    enter image description here

    See also Why does Cypress print cy.log output later than I would expect?