How to handle asynchronous behavior in Cypress

Last updated on Mar 28, 2023 by Suraj Sharma



In this tutorial, you'll learn how you can write Cypress tests to handle asynchronous behavior with an example

Let's say we have a web application that fetches data from an API and displays it on the page. We want to write a test that verifies that the data is displayed correctly.

Here's how we can do it:


  describe('Async behavior test', () => {
    it('displays data fetched from an API', () => {
      cy.visit('/'); // assuming the web app is hosted on the root URL

      cy.intercept('/api/data').as('getData'); // intercept API request

      cy.get('.data-container') // select the element that displays the data
        .should('not.contain', 'Loading...') // make sure the loading message is not displayed
        .should('not.contain', 'Error fetching data'); // make sure there are no error messages

      cy.wait('@getData').then((interception) => { // wait for the API request to complete
        expect(interception.response.body).to.not.be.empty; // assert that the response is not empty

        cy.get('.data-container')
          .should('contain', interception.response.body); // assert that the data is displayed correctly
      });
    });
  });


In this test, we intercept the API request using cy.intercept() and wait for it to complete using cy.wait(). Once the request is complete, we assert that the response is not empty and that the data is displayed correctly on the page. By using the cy.wait() command and the then() callback, we can handle the asynchronous behavior of the API request and ensure that the test only proceeds once the data is fetched and displayed correctly on the page.



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.