Open In App

How to handle async code in Cypress ?

Last Updated : 18 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Handling asynchronous code in Cypress is crucial for writing reliable and stable tests. Cypress provides built-in mechanisms to handle various forms of asynchronous behaviour, such as network requests, dynamic content loading, and delayed actions. Cypress commands are automatically retried until they pass or time out, which simplifies working with asynchronous code. In this guide, we'll cover common strategies for handling async code in Cypress, including waiting for network requests, dealing with dynamic content, and using timeouts effectively.

Example to handle async code Cypress

Example 1: Waiting for Network Requests

In Cypress, When your application makes network requests (e.g., XHR or fetch requests), you might need to wait for these requests to complete before proceeding with further test steps.

HTML Code for Mock API (for demonstration)

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Example</title>
</head>
<body>
    <button id="load-data">Load Data</button>
    <div id="data-container"></div>
    <script>
        document.getElementById('load-data').addEventListener('click', () => {
            fetch('https://jsonplaceholder.typicode.com/posts/1')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('data-container').innerText = data.title; // Use title from the post
                });
        });
    </script>
</body>
</html>

Cypress Test Code

JavaScript
describe('Wait for Network Request', () => {
  it('should wait for the API request to complete', () => {
    // Intercept the API request
    cy.intercept('GET', 'https://jsonplaceholder.typicode.com/posts/1').as('getData');
    
    // Visit the page
    cy.visit('http://localhost:3000'); // Adjust this URL as needed
    
    // Click the button to trigger the API request
    cy.get('#load-data').click();
    
    // Wait for the API request to complete
    cy.wait('@getData');
    
    // Assert that the data has been loaded
    cy.get('#data-container').should('not.be.empty'); // Check if data is loaded
  });
});

Explanation

  • cy.intercept(): Intercepts the network request to /api/data and assigns it an alias @getData.
  • cy.wait('@getData'): Waits for the intercepted request to complete.
  • Assertions: Verifies that the data has been loaded into the #data-container element.

Output

Cypress waits for the network request to complete and verifies that the data has been loaded.

output
Output

Example 2: Handling Dynamic Content Loading

If your page dynamically loads content, you might need to wait for specific elements to appear.

HTML Code

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Content Example</title>
</head>
<body>
    <button id="fetch-content">Fetch Content</button>
    <div id="content" style="display: none;">Dynamic Content</div>
    <script>
        document.getElementById('fetch-content').addEventListener('click', () => {
            setTimeout(() => {
                document.getElementById('content').style.display = 'block';
            }, 2000); // Simulate a delay
        });
    </script>
</body>
</html>

Cypress Test Code

JavaScript
describe('Handle Dynamic Content', () => {
  it('should wait for dynamic content to appear', () => {
    // Visit the page
    cy.visit('http://localhost:3000');
    
    // Click the button to trigger content loading
    cy.get('#fetch-content').click();
    
    // Wait for the dynamic content to appear
    cy.get('#content', { timeout: 3000 }).should('be.visible');
  });
});

Explanation

  • cy.get('#content', { timeout: 3000 }): Waits up to 3 seconds for the #content element to appear and become visible.
  • Assertions: Ensures that the dynamic content is visible after the button is clicked.

Output

Cypress waits for dynamic content to appear and ensures it is visible.

output
Output

Conclusion

Handling async code in Cypress is streamlined by its built-in mechanisms for waiting and retrying commands. By using cy.intercept() for network requests, waiting for elements to appear, and chaining commands, you can effectively manage asynchronous behavior in your tests. Cypress's approach ensures that tests are stable and reliable, even when dealing with dynamic content and delayed actions.


Next Article
Article Tags :

Similar Reads