Skip to content

Latest commit

 

History

History
 
 

server-communication__xhr-assertions

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

Assertions checking network request and response

This recipe shows how to spy on a network call and assert its request and response data.

cypress/integration/spec.js runs multiple assertions against an XHR object

Multiple assertions

cypress/integration/spok-spec.js asserts multiple values and schema properties using cy-spok plugin built on top of spok

Spok assertions

cy.wait vs cy.get for network requests

Both cy.get(<alias>) and cy.wait(<alias>) can yield a network request, but there is a difference. The command cy.wait will retry finding the matching request until the call is made, or the command times out. The command cy.get on the other hand, when dealing with aliases, just returns whatever it finds at that moment and does not retry.

In a situation when the network call might not have happened yet, cy.get will fail. For example, the followig test fails

it('waits for async network request using cy.wait', () => {
  cy.visit('index.html')

  cy.server()
  cy.route('POST', '/posts').as('post')

  cy.get('#delayed-load').click()
  // cy.get does NOT work
  // because it immediately returns null object,
  // since the request has not happened yet
  cy.get('@post').should('have.property', 'status', 201)
})

cy.get fails

The command cy.wait retries and "waits" until the matching network call really happens. Same test, but the last lines passes

cy.get('#delayed-load').click()
cy.wait('@post').should('have.property', 'status', 201)

cy.wait works

Find the above tests in cypress/integration/wait-vs-get.js

Tip: you can inspect the full XHR object by logging it to the console

cy.wait('@post').then(console.log)

XHR logged to console

Multiple requests

cypress/integration/multiple-requests.js shows how to wait for multiple matching requests and how to retrieve them all, or individually.

multiple requests

Controlling the clock

We can skip the initial 1 second delay set using setTimeout(..., 1000) inside the application by controlling the application's clock. See cypress/integration/clock-control.js.

Fast test via clock control

See also