0
0
Cypresstesting~5 mins

Waiting for requests (cy.wait with alias) in Cypress

Choose your learning style9 modes available
Introduction

Sometimes your test needs to pause until a web request finishes. This helps make sure the page is ready before checking things.

When your app sends data to the server and you want to wait for the response before continuing.
When loading data from an API and you want to check the results after the data arrives.
When clicking a button triggers a network request and you want to wait for it to complete.
When you want to avoid flaky tests caused by slow or delayed server responses.
Syntax
Cypress
cy.intercept('GET', '/api/data').as('getData')
cy.visit('/page')
cy.wait('@getData')

You first create an alias for the request using cy.intercept() and .as().

Then you use cy.wait() with the alias name prefixed by @ to pause until the request finishes.

Examples
Waits for the login POST request to finish after clicking the submit button.
Cypress
cy.intercept('POST', '/login').as('loginRequest')
cy.get('button[type=submit]').click()
cy.wait('@loginRequest')
Waits for the users API call to complete when visiting the users page.
Cypress
cy.intercept('GET', '/users').as('getUsers')
cy.visit('/users')
cy.wait('@getUsers')
Waits for a product details request after clicking the first product link.
Cypress
cy.intercept('GET', '/products/*').as('getProduct')
cy.get('.product-link').first().click()
cy.wait('@getProduct')
Sample Program

This test waits for the GET request to '/api/items' to finish before checking that the page shows some items.

Cypress
describe('Wait for API request example', () => {
  it('waits for data to load before checking', () => {
    cy.intercept('GET', '/api/items').as('getItems')
    cy.visit('/items')
    cy.wait('@getItems')
    cy.get('.item').should('have.length.greaterThan', 0)
  })
})
OutputSuccess
Important Notes

Always create the alias before the action that triggers the request.

You can wait for multiple requests by passing an array of aliases to cy.wait().

If the request fails or times out, the test will fail, helping catch issues early.

Summary

Use cy.intercept() with .as() to name requests.

Use cy.wait() with the alias to pause until the request finishes.

This makes tests more reliable by syncing with network activity.