Test if Postman response body Json is an array or object

Viewed 7618

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);
2 Answers

You 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);;
});
Related