API response not getting in cypress

Viewed 71
///<reference types = "cypress"/>

describe('API Test Suite', ()=>{

    it('Send GET Request',()=>{

    cy.request('http://ptsv2.com/t/fu807-1554722621/post').then((res)=>{
        expect(res.body).has.property('username', 'automate')
    })
    })
})

I'm trying to validate username field but its throwing error

expected '{\r\n "username": "automate",\r\n "password": "everything",\r\n "targetUrl": "http://ptsv2.com/t/7ty82-1554722743/post"\r\n}' to have property 'username'

SAMPLE RESULT on POSTMAN: { "username": "automate", "password": "everything", "targetUrl": "http://ptsv2.com/t/7ty82-1554722743/post" }

3 Answers

You can do something like this:

///<reference types = "cypress"/>

describe('API Test Suite', () => {
  it('Send GET Request', () => {
    cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post').then(
      (res) => {
        const user = 'automate'
        cy.wrap(res.body).should('contain', `"username": "${user}"`)
      }
    )
  })
})

On, digging deeper into your response body, I could see that there are empty spaces and because of which it was failing. So before asserting you have to remove the empty spacing and then apply the has.property assertion.

///<reference types = "cypress"/>

describe('API Test Suite', () => {
  it('Send GET Request', () => {
    cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post').then(
      (res) => {
        expect(JSON.parse(JSON.stringify(JSON.parse(res.body)))).has.property(
          'username',
          'automate'
        )
      }
    )
  })
})

cy.request yields the response as an object so you can access it using .its()

cy.request('your-request-url')
  .its('response.body')
  .should('have.property', 'username','automate')

Alternatively, you can use cy-spok to check for properties and values in a more readable code format.

const 'spoke = require('cy-spok')

// in your test
cy.request('your-request-url')
  .its('response.body')
  .should(spok({
    username: 'automated',
    password: 'everything',
    //other props
    })
  )

The body property needs parsing - true, but there are less hacky ways of doing it

cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post')
  .its('body')
  .then(JSON.parse)
  .should('have.property', 'username', 'automate')

or

cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post')
  .then(res => JSON.parse(res.body))
  .should('have.property', 'username', 'automate')
Related