lundi 27 mai 2019

Cypress request are async - but what about new object creation?

I tried to perform the request using Cypress and then create new objects with the value received in response but new objects are created instantly and request is being sent after all objects are already created:

describe("example", function() {

    it("of test", function() {

        console.log("1");

        cy.request({
            url: Cypress.env("URL"),
            method: "POST",
            headers: auth_req.authHeaders,
            body: merged_body
        })
            .as("/authorize")
            .then((resp) => {
                console.log("2");
                Cypress.env("resp_code", resp.status);
                console.log("RESP CODE FROM RESPONSE:");
                console.log(resp.status);
            })
            .its("headers")
            .its("content-type")
            .should("include", "application/json");

        console.log("3");
        const var1 = new something.NotImportant;
        console.log("4");
        const var2 = new something.AlsoNotImportant;
        console.log("5");

    }

}

I expected to get "1", "2", "3", "4" and "5" in console. However, I get "1", "3", "4" and "5" almost instantly and after a few seconds (slow response from server) I see that the request is being sent and "2" is spit out to my console.

My question is: If I get this correctly, requests are async and Cypress is waiting for them to finish, so why the test is not waiting for receiving the response and THEN creating the objects? How can I modify the code to be sure that the objects that I want to create after the request are using the value received from the request during new objects creation? I tried to use Cypress.env, but objects are created BEFORE the request and incorrect value is used instead of the value read from the response.


Bonus question: Why is this code not working as intended (hanging the computer)?

    while (true) {
        cy.wait(5000);
        var resp_code = Cypress.env("resp_code");
        console.log("RESP CODE:");
        console.log(Cypress.env("resp_code"));
    }

"RESP CODE" is printed to console like every 100 ms, I suppose it's because the test is async and I try to use the sync approach here. Am I correct?

Aucun commentaire:

Enregistrer un commentaire