How to handle async code in Cypress ?
Last Updated :
18 Sep, 2024
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.
OutputExample 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.
OutputConclusion
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.
Similar Reads
How to handle Cypress Asynchronous Behavior? Cypress is a dynamic end-to-end testing framework used for testing web applications. Unlike traditional testing tools, Cypress operates directly inside the browser, providing a more intuitive and consistent testing experience. One of the key features that makes Cypress stand out is its ability to ha
7 min read
How to Handle Errors for Async Code in Node.js ? Handling errors effectively in asynchronous code is crucial for building robust and reliable Node.js applications. As Node.js operates asynchronously by default, understanding how to manage errors in such an environment can save you from unexpected crashes and ensure a smooth user experience. This a
4 min read
How to run Cypress Tests in Chrome and Edge? Cypress is a popular testing framework that provides end-to-end testing for various web applications. It can provide testing in various browsers like Chrome, Firefox, etc. In this article, we will learn how to run tests in Chrome and Edge.What is Cypress Framework?Cypress is an end-to-end testing fr
3 min read
How can I compare Arrays in Cypress? In Cypress, you can compare arrays by extracting them and using JavaScript's array comparison methods. Cypress provides a variety of commands such as .then() or .should() to extract the arrays from the DOM or API responses and compare them. You can use built-in JavaScript methods like expect() from
3 min read
How to handle concurrency in Node.js ? Node.js is an open-source, cross-platform runtime environment built on Chrome's V8 Engine. It is used to develop highly scalable backend as well as server-side applications. Node.js uses a single-threaded event loop architecture. It is also asynchronous in nature. These are the two main reasons why
4 min read
Basic Commands in Cypress Cypress being a modern, full-stack test runner, developers are able to create maintainable web application unit tests which turn out to be reliable and supportable. It gives a palette of commands for interacting with web elements that allows for various actions to happen, and it is a very useful too
7 min read