0

I have the following simple test:

describe("smoke test", () => {
  it("visit site", async () => {
    cy.visit(SITE_URL);

    return new Promise((resolve) => cy.contains("banner text").should("be.visible").then(resolve));
  });
});

Cypress warns me that it is not necessary to return a promise. But if I remove it the test passes immediately, even if the site is not up:

describe("smoke test", () => {
  it("visit site", async () => {
    cy.visit(SITE_URL);

    cy.contains("banner text").should("be.visible");
  });
});

Is there a better way of fixing this test; is Cypress' warning wrong or is it something in my code?

jorgen
  • 3,425
  • 4
  • 31
  • 53
  • 1
    What's the exact wording of the warning? It may just be telling you that you don't need to use the `new Promise` constructor, because `cy.contains("banner text").should("be.visible")` already creates a promise. Returning that promise may still be needed. – Nicholas Tower Jan 03 '22 at 11:43
  • 1
    have you tried to remove `async ()`, fyi cypress already use it under the hood. Or you did it for the purposes? – Evgenii Bazhanov Jan 03 '22 at 11:46
  • 1
    It works if I return the assertion and remove the async keyword, thanks! If i want to do something asynchronous within the test body, however, and thus need the async keyword, it seems I have to return an explicit promise? – jorgen Jan 03 '22 at 13:47
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 04 '22 at 01:49
  • I'm very interested to learn about the promise constructor antipattern, but haven't found a very clear explanation (including the one in the above link). Are you aware of any? – jorgen Jan 04 '22 at 07:57

1 Answers1

1

Cypress already includes async under the hood, no need for it in code

describe("smoke test", () => {
  it("visit site", () => {
    cy.visit(SITE_URL);
    cy.contains("banner text").should("be.visible");
  });
});

If you want to do async stuff in your code, use .then(), to work with yielded promise. Don't use async, await as they won't work as expected probably... https://medium.com/@NicholasBoll/cypress-io-using-async-and-await-4034e9bab207

  • Thanks, that's a nice link. It seems to me, being used to async/await, that it's hard to predict when a cypress test will wait for execution (the tests in the above link don't return anything, as it seemed was necessary in my case, for example). This seems dangerous as it can easily lead to tests passing when they shouldn't. But maybe it's a matter of getting used to it – jorgen Jan 04 '22 at 08:02