I am trying to learn cypress then come across a topic in validating json response body but did not discuss on how to store it in a variable. I would like to know how to store specific data set in a variable for later use. In the response body below I would like to store userId, title, and body for dataset where id = 2.
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
{
"userId": 1,
"id": 4,
"title": "eum et est occaecati",
"body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
}
]
For now I can only do this by filtering it making the result to display only 1 dataset.
let id = 2;
let userId, title, body;
cy.request({
method: "GET",
url: "https://jsonplaceholder.typicode.com/posts/",
qs: {
id: id
}
})
.then((response) => {
expect(response.status).to.eq(200)
userId = response.body[0].userId
id = response.body[0].id
title = response.body[0].title
body = response.body[0].body
cy.log(`userId: ${userId}, id: ${id}, title: ${title},
body: ${body}`)
})
To save data like request responses for later use, apply an alias, described here Variables and aliases
Rather that individual properties, take the whole body and destructure parts as required, for example
it('saves the response as an alias', () => {
let id = 2
cy.request({
method: 'GET',
url: `https://jsonplaceholder.typicode.com/posts/${id}`,
})
.then(response => {
expect(response.status).to.eq(200) // check status inline
})
.its('body') // take the response body
.as('response') // assign it to an alias
/// later
cy.get('@response')
.its('title')
.should('eq', 'qui est esse')
})