How to Use Async/Await in Cypress

How to Use Async/Await in Cypress

Ferenc Almasi β€’ Last updated 2021 October 22 β€’ Read time 1 min read
  • twitter
  • facebook

The simplest way to handle asynchronous code in Cypress is by using async/await. To use asyn/await in Cypress, we can go with two different options. First, we can use an immediately invoked function expression, or IIFE for short:

Copied to clipboard! Playground
(async () => {
    const user = await service.getUser(Id);

    expect(user).to.deep.equal({ ... });
})();

We can also define callback functions as async and use await inside them like so:

Copied to clipboard! Playground
service.deleteUser(Id).then(async () => {
  const user = await service.getUser(Id);

  expect(user).to.be.null;
});

It is also important to mention that although Cypress commands are not Promises - the API is very similar. This means we can chain a then callback from commands and make the callback async in order to use await after executing commands:

Copied to clipboard! Playground
cy.get('button')
  .click()
  .then(async () => {
      // Await your asynchronous code here
  });

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Use Async/Await in Cypress
If you would like to see more webtips, follow @flowforfrank
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.