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
cypress/integration/spok-spec.js asserts multiple values and schema properties using cy-spok plugin built on top of spok
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)
})
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)
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)
cypress/integration/multiple-requests.js shows how to wait for multiple matching requests and how to retrieve them all, or individually.
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.
If we decide to assert the network call's duration yet avoid specifying extremely large limit to avoid spurious test failures, we can use test retries to re-run the test. See cypress/integration/duration-spec.js
it('is faster than 300ms', { retries: 3 }, () => {
...
cy.wait('@post').its('duration').should('be.lessThan', 300)
})
- Cypress network guide
- Cypress Testing Workshop XHR chapter