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
Usage
Next, using the command to capture requests to a route looks a bit like this in a test:
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:
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: