Skip to content
Advertisement

Cypress – get value from json response body

I’m using Cypress to do some API testing, but I am struggling to access values in the JSON response body; however I can perform assertions against the body which suggests it’s receiving it correctly.

Below I am trying to assign the JSON body (response.body) and then get the value of ‘id’ out of it:

describe('Creating a board', () => {    
it('should create a board', () => {
    cy.request({
    method : 'POST',
    url:`${requestUrl}/boards/`, 
    qs: {
      name : "test-board",
      token : token,
      key : key
    }
    }).then((response) => {
      expect(response).property('status').to.equal(200)
      expect(response.body).property('id').to.not.be.oneOf([null, ""])
      const body = (response.body)
      boardId = body['id']
    })
})

I’ve done numerous searches and can’t find a concrete way to do it. Any help would be appreciated…

Advertisement

Answer

I managed to solve this by using a Promise;

Doing some further reading, I found out the then function I am executing is synchronous (I’m new to JS, pls don’t hurt me).

I refactored the then function to the following:

.then((response) => {
        return new Promise(resolve => {        
            expect(response).property('status').to.equal(200)
            expect(response.body).property('id').to.not.be.oneOf([null, ""])
            const respBody = response.body;
            boardId = respBody['id']
            resolve(boardId)
        })

It’s probably not entirely correct or best practice, but it will do for my demo

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement