Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
-5
rated 0 times [  1] [ 6]  / answers: 1 / hits: 43234  / 4 Years ago, sun, february 2, 2020, 12:00:00

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...


More From » cypress

 Answers
72

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


[#51253] Thursday, January 23, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;