Reputation: 96614
Day one with Cypress.
Trying to make a JSON call and examine result but all attempts giving me undefined.
describe('Test Number 000001 !!!', function() {
it('starts off OK', function() {
expect(true).to.equal(true)
})
it('can call the example api', function() {
cy.request('https://jsonplaceholder.typicode.com/todos/1')
})
it('can call the example api and store the result', function() {
result = cy.request('http://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json()) // I tried with and without then
expect(result).to.equal(1) // will fail but once i get real response I will adjust
})
})
Update: the below passes... but doesn't actually check anything (any values used will pass)
cy.request('http://jsonplaceholder.typicode.com/todos/1').
then((response) => {
response = JSON.stringify(response)
var jsonData = JSON.parse(response)
for (var i = 0; i < jsonData.length; i++) {
expect(jsonData[i]['xuserId']).to.equal(1)
}
})
Upvotes: 0
Views: 3194
Reputation: 2143
You need to convert response object to a json string using stringify function inside the promise.
.then((response) => {
response = JSON.stringify(response)
var jsonData = JSON.parse(response)
for (var i = 0; i < jsonData.length; i++) {
expect(jsonData[i]['userId']).eq(1)
}
edit
expect(jsonData[i]['userId']).to.equal(1)
Upvotes: 2
Reputation: 12009
I have used the same test API earlier and have got the results like below; Please have a look. I have used response.body.
to get json values
it('Sample Api testing', function () {
cy.request({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/todos/1',
headers: {
'accept': 'application/json'
}
}).then((response) => {
expect(response.status).to.eq(200);
expect(response.body.userId).to.eq(1);
expect(response.body.id).to.eq(1);
expect(response.body.title).to.eq('delectus aut autem');
})
})
Upvotes: 3