In end-to-end testing with Cypress, it is common to ensure that all network requests complete, especially before performing data-dependent operations. Cypress provides several methods to help manage and wait for API requests to complete. Below are some commonly used approaches:
Using the cy.wait() Method
Cypress allows us to explicitly wait for one or more specific requests using the cy.wait() method. First, we need to use cy.intercept() to intercept network requests and assign aliases to them.
javascript// Intercept API request cy.intercept('GET', '/api/users').as('getUsers') // Trigger the request cy.visit('/users') // Wait for the request to complete cy.wait('@getUsers')
In the above example, we intercepted the GET request to /api/users and assigned an alias getUsers using the as() method. After the page visit or other actions trigger this request, we use cy.wait() with the alias to wait for completion.
Handling Multiple Requests
If the page involves multiple requests that need to be waited for, we can assign aliases to each request and wait for them sequentially using cy.wait().
javascriptcy.intercept('GET', '/api/users').as('getUsers') cy.intercept('GET', '/api/posts').as('getPosts') cy.visit('/dashboard') // Wait for multiple requests cy.wait(['@getUsers', '@getPosts'])
Verifying Request Completion
Sometimes, we need to perform further actions based on the response. We can use the .then() method after cy.wait() to access the response data.
javascriptcy.wait('@getUsers').then((interception) => { // Access the response body using interception.response assert.equal(interception.response.statusCode, 200, 'Verify status code') assert.isNotEmpty(interception.response.body, 'Response body should not be empty') })
Using a Polling Mechanism
In complex scenarios where specific requests are unknown or dynamically generated, a simple polling mechanism can periodically check if network activity has stopped.
javascript// Visit the page cy.visit('/dynamic-requests') // Use a recursive function and cy.wait() to check for idle network function waitForIdleNetwork() { cy.wait(1000) // Wait for one second cy.get('@networkIdle').then((idle) => { if (!idle) { waitForIdleNetwork() // Continue waiting if not idle } }) } cy.intercept('*', (req) => { req.on('response', (res) => { cy.wrap(true).as('networkIdle') // Mark as idle on response }) req.continue() }).as('anyRequest') waitForIdleNetwork() // Invoke the wait function
In this example, we recursively call waitForIdleNetwork until network activity stops. This approach should be used with caution as it may significantly extend test execution time.
Summary
In Cypress, waiting for all API requests to complete primarily relies on combining cy.intercept() and cy.wait(). By assigning aliases to requests and explicitly waiting for these aliases after triggering them, we ensure all relevant network requests complete before proceeding with subsequent test steps. This enhances test accuracy and reliability.