cy.server()

To control the behavior of network requests and responses, use the cy.server() command.

cy.server().should(function(server){
  // the default options on server
  // you can override any of these options
  expect(server.delay).to.eq(0)
  expect(server.method).to.eq('GET')
  expect(server.status).to.eq(200)
  expect(server.headers).to.be.null
  expect(server.response).to.be.null
  expect(server.onRequest).to.be.undefined
  expect(server.onResponse).to.be.undefined
  expect(server.onAbort).to.be.undefined

  // These options control the server behavior
  // affecting all requests
  expect(server.enable).to.be.true              // pass false to disable existing route stubs
  expect(server.force404).to.be.false           // forces requests that don't match your routes to 404
  expect(server.whitelist).to.be.a('function')  // whitelists requests from ever being logged or stubbed
})

cy.server({
  method: 'POST',
  delay: 1000,
  status: 422,
  response: {}
})

cy.request()

To make an XHR request, use the cy.request() command.

cy.request('https://jsonplaceholder.typicode.com/comments').should(function(response){
  expect(response.status).to.eq(200)
  expect(response.body).to.have.length(500)
  expect(response).to.have.property('headers')
  expect(response).to.have.property('duration')
})

cy.route()

To route responses to matching requests, use the cy.route() command.

var message = 'whoa, this comment doesn\'t exist'
cy.server()

// **** GET comments route ****

cy.route(/comments\/1/).as('getComment')

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

// **** Wait ****

// Wait for a specific resource to resolve
// continuing to the next command

cy.wait('@getComment').its('status').should('eq', 200)

// **** POST comment route ****

// Specify the route to listen to method 'POST'
cy.route('POST', '/comments').as('postComment')

// we have code that posts a comment when
// the button is clicked in scripts.js
cy.get('.network-post').click()
cy.wait('@postComment')

// get the route
cy.get('@postComment').then(function(xhr){
  expect(xhr.requestBody).to.include('email')
  expect(xhr.requestHeaders).to.have.property('Content-Type')
  expect(xhr.responseBody).to.have.property('name', 'Using POST in cy.route()')
})

// **** Stubbed PUT comment route ****
cy.route({
  method: 'PUT',
  url: /comments\/\d+/,
  status: 404,
  response: {error: message},
  delay: 500
}).as('putComment')

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

cy.wait('@putComment')

// our 404 statusCode logic in scripts.js executed
cy.get('.network-put-comment').should('contain', message)