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);
Check if Variable is Array ? Sometimes, you need to check a parsed JSON object or a variable to see if it's an array before iteration or before any other manipulation. You can use the Array. isArray method to check if a variable is an array.
JSON Syntax JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.
The Postman Body tab gives you several tools to help you understand the response quickly. You can view the body in one of four views: Pretty, Raw, Preview, and Visualize. in the results pane. You can also place your cursor in the response and select ⌘+F or Ctrl+F.
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.
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