Capture Fetch with Cypress

10 November 2020

Updated: 03 September 2023

To capture the result of a fetch request with Cypress you will need to make use of cy.route2

Setup

The cy.route2 command needs to be enabled in your cypress.json file before usage, to do so add the following:

cypress.json

1
{
2
"experimentalNetworkStubbing": true
3
}

Usage

Next, using the command to capture requests to a route looks a bit like this in a test:

1
cy.route2('POST', '/do-stuff').as('data')

In the above you need to use the cy.route2 function. In the above we’re capturing POST requests to the /do-stuff endpoint. The object which contains the request and response data is stored in the @data which can be retreived and worked with like so:

1
cy.wait('@data').then((data) => {
2
// do stuff using the data object
3
console.log(data)
4
})

The cy.wait function retreives the data object, we use the .then function with a callback function to do stuff with the fully resolved data object

Furthermore, the HTTP response from the data object can be parsed using JSON.parse, you can then also add assertions based on the response object. Adding this in, the above code would look more like this:

1
cy.wait('@data').then((data) => {
2
console.log(data)
3
4
// parse the response body
5
const res = JSON.parse(data.response.body)
6
7
// assertions on the response
8
assert.isTrue(res.success)
9
assert.isNotNull(res.message)
10
})