Michael Durrant
Michael Durrant

Reputation: 96614

How can I use cypress to make a JSON call?

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
  })  
})

enter image description here

enter image description here

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

Answers (2)

Prany
Prany

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

soccerway
soccerway

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');
        })
    })

enter image description here

Upvotes: 3

Related Questions