Verify API request completes successfully using cy.wait with alias
Preconditions (2)
✅ Expected Result: The API request completes with status 200 and the page shows 'Data loaded successfully'
describe('API request wait test', () => { it('waits for API request and verifies response', () => { cy.visit('http://localhost:3000'); // Intercept GET /api/data and alias as 'getData' cy.intercept('GET', '/api/data').as('getData'); // Click the button that triggers the API request cy.get('button#load-data').click(); // Wait for the API request to complete cy.wait('@getData').its('response.statusCode').should('eq', 200); // Verify the page shows success message cy.contains('Data loaded successfully').should('be.visible'); }); });
This test first visits the page where the API request will be triggered.
We use cy.intercept to watch the GET request to /api/data and give it the alias getData.
Clicking the button triggers the request.
Then cy.wait('@getData') waits for that request to finish before continuing.
We check the response status code is 200 to confirm success.
Finally, we assert the page shows the success message, confirming the UI updated correctly.
This approach avoids using fixed delays and makes the test reliable and fast.
Now add data-driven testing with 3 different API endpoints and verify each response
cy.wait() with an alias in Cypress tests?cy.wait() with aliascy.wait() command pauses the test until the network request with the given alias completes.cy.intercept() is used to spy or stub requests, and .as() assigns an alias.cy.intercept('/api/data').as('getData'), which is the correct syntax.cy.intercept('GET', '/users').as('getUsers')
cy.visit('/users')
cy.wait('@getUsers').then(({ response }) => {
console.log(response.status)
})cy.intercept() spies on the GET request to '/users' and aliases it as 'getUsers'.cy.wait('@getUsers') waits for the request to finish, then logs the response.status. A successful GET usually returns 200.cy.intercept('POST', '/login').as('loginRequest')
cy.get('button#submit').click()
cy.wait('loginRequest')cy.wait() command requires the alias to be prefixed with '@' to identify the request alias.cy.wait('loginRequest') missing the '@', which causes Cypress to not recognize the alias.cy.intercept() and alias before triggering the request by clicking the button.cy.wait('@submitRequest') after clicking to pause until the POST completes, then check page content.Pass the test and this pattern moves unknown