I have a API that I'm testing and I'm expecting responseBody
to be a Json object (starts with "{"). However it could be that due to an unexpected event the response could be returned as an array (starts with "[").
How can I determine the type (array or object) of responseBody
using Postman tests?
So far the best I have is: When expecting an object (not an array)
var bodyJson = pm.response.json();
tests["Response should not be an array"] = !(bodyJson instanceof Array);
I have a API that I'm testing and I'm expecting responseBody
to be a Json object (starts with "{"). However it could be that due to an unexpected event the response could be returned as an array (starts with "[").
How can I determine the type (array or object) of responseBody
using Postman tests?
So far the best I have is: When expecting an object (not an array)
var bodyJson = pm.response.json();
tests["Response should not be an array"] = !(bodyJson instanceof Array);
Share
Improve this question
edited Dec 18, 2018 at 11:53
uedemir
1,7141 gold badge14 silver badges22 bronze badges
asked Dec 18, 2018 at 10:39
ajgreylingajgreyling
1,4362 gold badges13 silver badges11 bronze badges
2
- In some cases with API responses, it may place the JSON object into an array on its own. – Jack Bashford Commented Dec 18, 2018 at 10:42
- You can check it using different tool, as JMeter with Response assertion – Ori Marko Commented Dec 18, 2018 at 10:48
2 Answers
Reset to default 9You could just use:
pm.test('is an Array', () => pm.expect(pm.response.json()).to.be.an('array').but.not.an('object'))
Taken from ChaiJS - which is built-in to the native Postman application.
For example you have the following json
{
"testA": [1, 2],
"testB": {"a": "b"}
}
you can use Array.isArray()
var bodyJson = pm.response.json();
tests["Response should not be an array"] = !Array.isArray(bodyJson['testA']); // false
//tests["Response should not be an array"] = !Array.isArray(bodyJson['testB']); // true
Or
var bodyJson = pm.response.json();
pm.test("is Array Test", function() {
var notArray = !Array.isArray(bodyJson.testA) // false
// var notArray = !Array.isArray(bodyJson.testB) // true
pm.expect(notArray).to.eql(true);;
});