0
0
CypressHow-ToBeginner ยท 3 min read

How to Wait in Cypress: Syntax, Examples, and Tips

In Cypress, you can wait explicitly using cy.wait() with a time in milliseconds or an alias for network requests. Cypress also automatically waits for elements and commands to complete, reducing the need for manual waits.
๐Ÿ“

Syntax

The cy.wait() command pauses test execution for a specified time or until a network request completes.

  • cy.wait(time): Waits for a fixed time in milliseconds.
  • cy.wait(alias): Waits for a network request with the given alias to finish.
javascript
cy.wait(2000) // waits 2 seconds

cy.intercept('GET', '/api/data').as('getData')
cy.wait('@getData') // waits for the API call to finish
๐Ÿ’ป

Example

This example shows how to wait for 1 second and then wait for a network request to complete before continuing the test.

javascript
describe('Wait example', () => {
  it('waits explicitly and for API call', () => {
    cy.intercept('GET', '/users').as('getUsers')
    cy.visit('/users-page')
    cy.wait(1000) // wait 1 second
    cy.wait('@getUsers') // wait for users API
    cy.get('.user-list').should('be.visible')
  })
})
Output
Test passes if the user list is visible after waiting for the API and fixed delay.
โš ๏ธ

Common Pitfalls

Using fixed waits like cy.wait(5000) can make tests slow and flaky. Instead, prefer waiting for elements or network calls to finish. Avoid mixing setTimeout or manual delays outside Cypress commands.

javascript
/* Wrong way: fixed long wait */
cy.wait(5000)

/* Right way: wait for element or API */
cy.get('#submit-button').should('be.enabled')
cy.intercept('POST', '/submit').as('submitForm')
cy.wait('@submitForm')
๐Ÿ“Š

Quick Reference

CommandDescription
cy.wait(time)Waits a fixed time in milliseconds
cy.wait(alias)Waits for a network request with alias
cy.get(selector).should()Waits for element state automatically
cy.intercept()Create aliases for network requests to wait on
โœ…

Key Takeaways

Use cy.wait() with aliases to wait for network requests instead of fixed delays.
Avoid long fixed waits to keep tests fast and reliable.
Cypress automatically waits for elements and commands, reducing manual waits.
Use cy.intercept() to create aliases for API calls to wait on them explicitly.
Prefer waiting for conditions over arbitrary timeouts to prevent flaky tests.