I have a json response like this and I would like to count how many Friend Groups are in MyFriends array (in my case I expect the code to return 7) :
I tried following but it throws tis error--
TypeError: Cannot read properties of undefined (reading '0')
var data = pm.response.json().MyFriends[0].FriendGroupProperties;
pm.test('Number of friends = ' + MyFriends.length, function () {
pm.expect(data.length).to.equal(7);
});
I also tried this but it also throws
TypeError: Cannot convert undefined or null to object
error :
var data = pm.response.json().MyFriends;
var count = Object.keys(data).length;
console.log("The number of expected friends in the response body is: " + count);
console.log(`Number of Friends: ${_.size(data)}`)
Is there anyone who can help me with this?
Your data is array data (start [
and end ]
) in your body.
It has single item of array, and MyFriends
is first field , then it has 7 items of array.
You can add console log(print) step by step as I added in my code.
Also console output(left bottom side of UI) help to debug and can get the correct data position and length as I attached image.
Using this test code
var jsonData = JSON.parse(responseBody);
console.log(jsonData.length)
console.log(jsonData[0])
console.log(jsonData[0].MyFriends)
console.log(jsonData[0].MyFriends.length)
pm.test('Number of friends = ' + jsonData[0].MyFriends.length, function () {
pm.expect(jsonData[0].MyFriends.length).to.equal(7);
});