I send a request which sends me back something like:
{
"items": [
{
"id": 86154,
...
},
{
"id": 86194,
...
}
}
I would like to count the size of this array in Postman test section. So I wrote:
var body = JSON.parse(pm.response.json());
tests["Count: " + body.items] = true;
As you can see above, it didn't worked. I am new to both PostMan and Javascript, that's probably why.
I send a request which sends me back something like:
{
"items": [
{
"id": 86154,
...
},
{
"id": 86194,
...
}
}
I would like to count the size of this array in Postman test section. So I wrote:
var body = JSON.parse(pm.response.json());
tests["Count: " + body.items] = true;
As you can see above, it didn't worked. I am new to both PostMan and Javascript, that's probably why.
Share Improve this question asked Apr 29, 2020 at 10:29 Revolucion for MonicaRevolucion for Monica 3,29610 gold badges48 silver badges92 bronze badges 1-
1
FYI re your currently-accepted answer: There's no reason whatsoever for using
Object.keys
here. – T.J. Crowder Commented Apr 29, 2020 at 12:00
4 Answers
Reset to default 10Simple answer is to get the same thing, using the new pm.*
API syntax:
pm.test(`Count: ${pm.response.json().items.length}`)
The syntax you used is incorrect JSON.parse(pm.response.json())
- You can just use pm.response.json()
and drop the JSON.parse()
.
To get the number of objects, you just need to use the .length property.
I'm not sure what you are testing for but this simple test would check or assert that you have 2 objects (Like your example) in the array:
let body = pm.response.json()
pm.test("Check the Items array length", () => {
pm.expect(body.items.length).to.equal(2)
})
This is using the newer pm.test()
syntax, more about this and all the other pm.*
API methods can be found here:
https://learning.postman./docs/postman/scripts/postman-sandbox-api-reference/
If you just wanted to log out the value and not add that to a test, you can use console.log(pm.response.json().items.length)
in the Tests
tab and see this displayed in the Postman Console.
.json()
returns an promise. try it like this:
(async () => {
var body = await pm.response.json();
tests["Count: " + body.items] = true;
})()
or like this:
pm.response.json().then(body => {
tests["Count: " + body.items] = true;
});
You need to define the test in the postman, and then inside that you can check the no of object in the response as shown in below code.
pm.test("Item count should be 5", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.items.length).to.eql(5);
});
I have used a static count, but in your test scripts you can also use dynamic variables
var body = JSON.parse(responseBody);
tests["Count: " + Object.keys(body.items).length] = true;
I suppose postman return json and might not always need to parse it, You then count the length of your "items" using https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys