Making a test fail if an HTTP request fails in Cypress

Viewed 1828

I'm testing an app with Cypress, and the tests go against real HTTP servers. I'm not stubbing the HTTP requests.

Is there a way to make my tests fail if any of the HTTP requests fail?

There is a solution that seems ok in this other SO post, but I wonder if there is a more proper solution. In my case, I'm not always converting all HTTP errors into invocations to console.error.

1 Answers

You can listen to the request using cy.intercept() & check the status code etc.

Ref : https://docs.cypress.io/api/commands/intercept.html#Intercepting-a-response

Example 1 :

// Wait for intercepted HTTP request
cy.intercept('POST', '/users').as('createUser')
// ...
cy.wait('@createUser')
  .then(({ request, response }) => {
    expect(response.statusCode).to.eq(200)
  })

Example 2 :

   // Listen to GET to comments/1
    cy.intercept('GET', '**/comments/*').as('getComment')

    // we have code that gets a comment when
    // the button is clicked in scripts.js
    cy.get('.network-btn').click()

    // https://on.cypress.io/wait
    cy.wait('@getComment').its('response.statusCode').should('be.oneOf', [200, 304])
Related