Reputation: 2823
I have a suite of end-to-end Cypress tests for my web app. When the tests run, AJAX calls are made against a real server (i.e. the requests are not mocked or stubbed). Currently, I do something like the following to ensure that the tests wait for these AJAX requests to complete
// declare the AJAX request we will wait for
cy.route('POST', '/api/authenticate').as('authenticate')
// type the username and password and click the login button
cy.get('#username').type('john-doe')
cy.get('#password').type('secret')
cy.get('#login-button').click()
// wait for the AJAX request to complete before testing the response code
cy.wait('@authenticate')
cy.get('@authenticate').then(xhr => {
expect(xhr.status).to.eq(200)
})
This seems very verbose, is there a simpler way? I'm using the latest version of Cypress, v. 6.1.0.
Upvotes: 1
Views: 6920
Reputation: 18634
cy.server() and cy.route() are deprecated in Cypress 6.0.0. Instead cypress introduced cy.intercept(). So you can write something like:
// declare the AJAX request we will wait for
cy.intercept('POST', '/api/authenticate').as('authenticate')
// type the username and password and click the login button
cy.get('#username').type('john-doe')
cy.get('#password').type('password')
cy.get('#login-button').click()
// wait till we get 200
cy.wait('@authenticate').its('response.statusCode').should('eq', 200)
//You can also assert request body and response body contents
cy.wait('@authenticate').its('request.body').should('include', 'username')
cy.wait('@authenticate').its('response.body').should('include', 'password')
Upvotes: 8
Reputation: 486
In the example here, it's written like this.
cy.wait('@authenticate').should('have.property', 'status', 200)
Not a huge saving, but it's something :)
Edit: I just noticed you saying you have the latest version. I'd follow Alapan's suggestion in that case.
Upvotes: 3