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.
Simple 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.com/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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With