最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Test if Postman response body Json is an array or object - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 9

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);;
});
发布评论

评论列表(0)

  1. 暂无评论