How to deliberately fail a network request in a Cypress test

Viewed 53

We have added a new feature to our app for offline continuity, and I need the API requests not to return a value. There are a lot of tests and waiting for a disconnected API is not practical.

How can I simulate a disconnected network?

This is what I have so far, but it's not working

cy.intercept({
  'GET',
  '**/api/**/*'
}, (req) => {
  throw 'Network failure'
})
.as('failed')

cy.visit('/')

cy.wait('@failed')

cy.get('[data-cy="Error message"]')
  .should('be.visible')
1 Answers

The intercept command has an option forceNetworkError for this scenario

Blanket fail for all requests

cy.intercept('**/api/**/*', { forceNetworkError: true })
  .as('failed')

cy.wait('@failed').should('have.property', 'error')

Selective request failure

Alternatively, you can destroy() the request selectively

cy.intercept('**/api/**/*', (req) => {
  if (mustDestroy(req)) {
    req.destroy()
  }

  function mustDestroy(req) {
    return req.query.includes('something')  // destroy certain requests
  }
})

Specific status code failures

If the app responds differently for some status codes,

cy.intercept('**/api/**/*', { statusCode: 500 })
  .as('failed')

cy.wait('@failed')
cy.contains('There was an error completing your request')
Related