0
0
CypressHow-ToBeginner ยท 3 min read

How to Use cy.wait in Cypress for Test Synchronization

Use cy.wait() in Cypress to pause test execution for a fixed time or until a network request finishes. It accepts a time in milliseconds or an alias for a request to wait for, helping synchronize tests with app behavior.
๐Ÿ“

Syntax

The cy.wait() command can be used in two main ways:

  • cy.wait(time): Pauses the test for a fixed number of milliseconds.
  • cy.wait(alias): Waits for a network request that was aliased earlier with cy.intercept().

This helps control test timing and synchronization with app events.

javascript
cy.wait(2000) // waits 2 seconds

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

Example

This example shows how to wait for a network request before checking page content. It intercepts a GET request, waits for it, then asserts the response is shown.

javascript
describe('Wait example', () => {
  it('waits for API response before asserting', () => {
    cy.intercept('GET', '/users').as('getUsers')
    cy.visit('/users-page')
    cy.wait('@getUsers')
    cy.get('.user-list').should('be.visible')
  })
})
Output
Test passes if the .user-list is visible after the /users request completes.
โš ๏ธ

Common Pitfalls

Common mistakes when using cy.wait() include:

  • Using fixed waits like cy.wait(5000) unnecessarily, which slows tests and can cause flakiness.
  • Not aliasing network requests before waiting, causing errors.
  • Waiting for wrong or missing aliases.

Always prefer waiting for network requests over fixed time waits for reliable tests.

javascript
/* Wrong: fixed wait slows tests and is unreliable */
cy.wait(5000)

/* Right: wait for network request alias */
cy.intercept('POST', '/login').as('loginRequest')
cy.wait('@loginRequest')
๐Ÿ“Š

Quick Reference

UsageDescription
cy.wait(time)Pauses test for fixed milliseconds (e.g., 1000 = 1 second)
cy.wait(alias)Waits for a network request aliased with cy.intercept()
cy.intercept(method, url).as(alias)Defines a network request to wait for
Avoid fixed waitsPrefer waiting for requests to improve test speed and reliability
โœ…

Key Takeaways

Use cy.wait() to pause tests for fixed time or wait for network requests.
Always alias network requests with cy.intercept() before waiting on them.
Avoid fixed time waits when possible to keep tests fast and stable.
Waiting for requests ensures tests sync with app behavior reliably.
Check aliases carefully to prevent waiting on wrong or missing requests.