smeeb
smeeb

Reputation: 29477

PostMan Test scripts: Inspecting contents of response JSON

PostMan 6.0.10 here. I'm trying to understand how to write test scripts a little better, and after reading their otherwise superb documentation I still have some confusion surrounding how to query & examine the JSON response coming back from requests.

Specifically, given the following snippet of JavaScript:

pm.test("Verify the contents of the response payload are correct", function () {
    // ???
});

I need to be able to query the response JSON and:

Scenario #1: JSON response is an array

Example:

[
    {
        "fizz": "buzz",
        "foo": 53
    },
    {
        "fizz": "bozz",
        "foo": 291
    }
]

Scenario #2: JSON response is a single object

Example:

{
    "fizz": "buzz",
    "foo": 293
}

Any ideas how this JSON inspection of the response payloads can be performed?

Upvotes: 6

Views: 6171

Answers (2)

BKM
BKM

Reputation: 1

//You can do something like this

 if (responseCode.code === 200) {
  var jsonDataArray;
  var jsonArray= JSON.parse(responseBody);
 var found=false;

       for (var i = 0;i<jsonArray.length;i++){`enter code here`

     jsonDataArray = jsonArray[i];
     for (var j = 0; j<jsonDataArray.length && found === false;j++){
         if (jsonDataArray[j].fizz === "buzz" && jsonDataArray[j].foo === 53)

Upvotes: -1

Danny Dainton
Danny Dainton

Reputation: 25851

This is basic but should work to get the dynamics:

pm.test("Verify payload of example one",  () => {
    pm.expect(pm.response.json()[0].fizz).to.equal('buzz')
    pm.expect(pm.response.json()[0].foo).to.equal(53)
    pm.expect(pm.response.json()[1].fizz).to.equal('bozz')
    pm.expect(pm.response.json()[1].foo).to.equal(291)
});

pm.test("Verify payload of example two",  () => {
    pm.expect(pm.response.json().fizz).to.equal('buzz')
    pm.expect(pm.response.json().foo).to.equal(293)
});

Might be worth researching some basic JavaScript and how to parse JSON objects.

Upvotes: 10

Related Questions