How to Wait for API Response in Cypress: Simple Guide
In Cypress, you can wait for an API response by using
cy.intercept() to spy or stub the request and then cy.wait() to pause the test until the response arrives. This ensures your test runs only after the API call completes.Syntax
The basic syntax to wait for an API response in Cypress involves two main commands:
cy.intercept(): To listen to or stub a network request.cy.wait(): To pause test execution until the intercepted request finishes.
You assign an alias to the intercepted request, then use that alias in cy.wait().
javascript
cy.intercept('GET', '/api/data').as('getData') cy.wait('@getData')
Example
This example shows how to wait for a GET API call to finish before checking the page content that depends on the API response.
javascript
describe('API wait example', () => { it('waits for API response before asserting', () => { cy.intercept('GET', '/api/data').as('getData') cy.visit('/page-that-loads-data') cy.wait('@getData').then(({ response }) => { expect(response.statusCode).to.equal(200) }) cy.get('#data-container').should('contain.text', 'Expected Data') }) })
Output
Test passes if API returns 200 and page shows 'Expected Data'.
Common Pitfalls
Common mistakes when waiting for API responses in Cypress include:
- Not assigning an alias with
.as()before usingcy.wait(). - Waiting for the wrong URL or method, causing the test to hang or fail.
- Not intercepting the request before the action that triggers it.
- Using
cy.wait()with a fixed time instead of waiting for the actual request.
Always intercept first, then trigger the request, then wait.
javascript
/* Wrong way: waiting without alias */ cy.wait(5000) // waits fixed 5 seconds, unreliable /* Right way: intercept and wait with alias */ cy.intercept('POST', '/api/submit').as('submitForm') cy.get('form').submit() cy.wait('@submitForm')
Quick Reference
| Command | Purpose | Example |
|---|---|---|
| cy.intercept() | Spy or stub network request | cy.intercept('GET', '/api/data').as('getData') |
| cy.wait() | Wait for intercepted request to finish | cy.wait('@getData') |
| Alias | Name for intercepted request | .as('getData') |
| Assertion | Check response status or body | cy.wait('@getData').its('response.statusCode').should('eq', 200) |
Key Takeaways
Use cy.intercept() with .as() to listen for API calls before triggering them.
Always use cy.wait() with the alias to pause test until the API response arrives.
Avoid fixed time waits; rely on network interception for reliable tests.
Check the response status or body inside cy.wait() callback for validation.
Intercept requests before the action that triggers them to avoid missing calls.