Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress intercept - how to chain multiple assertions on a response

Tags:

cypress

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.

like image 845
davilo61 Avatar asked Nov 01 '25 21:11

davilo61


2 Answers

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)

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

like image 41
Vitj Avatar answered Nov 03 '25 23:11

Vitj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!