davilo61
davilo61

Reputation: 43

Cypress intercept - how to chain multiple assertions on a response

I just started using the new intercept method and have a basic question and want to know how to chain the two assertions below in one test.

cy.intercept('GET', '/states').as('states');
cy.reload(true);
// cy.wait('@states').its('response.statusCode').should('eq',200)
cy.wait('@states').its('response.body').should('have.length', 50)

Both assertions work separately.

Upvotes: 4

Views: 2850

Answers (2)

Vitj
Vitj

Reputation: 53

Works like a charm:

cy.intercept("POST", "/graphql").as("someInterception");  

cy.wait("@someInterception").then(({ request, response }) => {
  expect(response.body.data.someField).to.be.true;
  expect(request.body.variables.someField).to.be.true;
});

See: https://docs.cypress.io/api/commands/intercept#Using-the-yielded-object

Upvotes: 1

user9161752
user9161752

Reputation:

The subject passed down from .its('response.statusCode') is the value of the statusCode property, so you need access to the response again to test both conditions

Using closure to make response available to both assertions

cy.wait('@states')
  .its('response')
  .then(response => {
    cy.wrap(response).its('statusCode').should('eq', 200)     
    cy.wrap(response).its('body').should('have.length', 50)
  })

Using the callback pattern

cy.wait('@states')
  .its('response')
  .should(response => expect(response.statusCode).to.eq(200))   
  .should(response => expect(response.body.length).to.eq(50))

Re-reading the alias

cy.wait('@states')                                   // wait for the alias
  .its('response.statusCode').should('eq', 200)

cy.get('@states')                                    // 2nd time use get()
  .its('response.body').should('have.length', 50)

Upvotes: 7

Related Questions