How to test for XHR failures

// Store data in ./fixtures/todos.json
[
  { "id": 1, "name": "Eat", isComplete: true },
  { "id": 2, "name": "Sleep", isComplete: false },
  { "id": 3, "name": "Dream", isComplete: false }
]

// Add you custom command in here: support/commands.js
Cypress.Commands.add('seedAndVisit', (seedData = 'fixture:todos') => {
  cy.server()
  cy.route('GET', '/api/todos', seedData)
    .as('loadToComplete')
  cy.visit('/')
  cy.wait('@loadToComplete')
})


describe('form submission', () => {
  it('shows error message on form submission failure', () => {
    const newTodo = 'buy milk'
    cy.server()
    cy.route({
      method: 'POST',
      url: '/api/todos',
      status: 500,
      response: {}
    }).as('save')

    cy.seedAndVisit()

    cy.get('.inputfield')
      .type(newTodo)
      .type('{enter}')

    cy.wait('@save')
    cy.get('.list-item').should('have.length', 3)
    cy.get('.error').should('be.visible')
  })
})

Last updated

Was this helpful?