'How can I save API response body or property in an environment variable or json to use it later in other requests in Cypress
API runs locally(and in future in a circleCI container) so I don't need to stub responses, only real requests and real responses.
When I send a POST request, it creates an event and returns a big response body containing a unique ID. I need to store that unique ID somewhere(as env variable, json or worst case scenario a const) so that I can access and use it in UPDATE request later and in the end in DELETE request to delete that Event from the system.
Is there a way to do this?
There is a way to retrieve that ID from the DB, but I really don't want to do it that way
Solution 1:[1]
You can save the unique ID in the fixture file and then later update or read from it:
cy.request({
method: 'POST',
url: '/someurl',
}).then((resp) => {
// Expect success response
expect(resp.status).to.eq(200)
//Write Unique ID to a fixture file
cy.writeFile('cypress/fixtures/testdata.json', {
"id": resp.uniqueID
})
})
If you want to update the value of the Unique ID, you can do something like this:
cy.readFile("cypress/fixtures/testdata.json", (err, data) => {
if (err) {
return console.error(err);
};
}).then((data) => {
data.id = newUniqueID //save the New Value of Unique ID
cy.writeFile("cypress/fixtures/testdata.json", JSON.stringify(data)) //Write it to the fixtures file
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alapan Das |