Test Body response by looping through Array or If/Else

New to Postman and starting to get into more complex testing base on the body responses. My aim is to test several arrays of data from the body response.

Questions is how best to either loop through testing or by doing if/else or try catch conditions when the data has the same properties but different values in each separate array of data?

Example: AccountID shows in all arrays but the numbers obviously change in each. I want to account for those to not be null. I know I can do a pm.expect (json.data.AccountID).to.be.not.null but I was looking for more efficient way to loop through and conditionally check each array output? Maybe I’m making this harder than it needs to be??

{
“AccountID”: 123485,
“AssociateNumber”: 123456,
“AssociateType”: “Account”,
“AccountType”: “Business”,
“DisplayName”: “Test”,
“FirstResDate”: “2011-07-06T00:00:00”,
“LastResDate”: “2011-09-14T00:00:00”,
“LastContactDate”: “2010-12-26T00:00:00”,
“PricingLevel”: “Executive”,
“ActiveFlag”: false,
“CreatedBy”: “Conversion”,
“CreatedDate”: “2010-12-26T07:48:34.827”,
“ModifiedBy”: “Test”,
“ModifiedDate”: “2020-09-02T07:27:29”
},
}, {
“AccountID”: 123485,
“AssociateNumber”: 123456,
“AssociateType”: “Account”,
“AccountType”: “Business”,
“DisplayName”: “Test”,
“FirstResDate”: “2011-07-06T00:00:00”,
“LastResDate”: “2011-09-14T00:00:00”,
“LastContactDate”: “2010-12-26T00:00:00”,
“PricingLevel”: “Executive”,
“ActiveFlag”: false,
“CreatedBy”: “Conversion”,
“CreatedDate”: “2010-12-26T07:48:34.827”,
“ModifiedBy”: “Test”,
“ModifiedDate”: “2020-09-02T07:27:29”
},

Hi @qateamll

When I was first learning Postman I created this workspace with my examples.

It should have everything you are asking for under the “Test Script Examples” collection.

Great, thank you! I will focus on that area for solutions…

Here is an example. It’s uses backticks\string literals to customize the test case name, which is fairly important when looping through a data set to know which one is actually failing.

const array = pm.response.json(); 

pm.test("Array check", () => {
    pm.expect(array).to.be.an("array").that.is.not.empty;
});

array.forEach(element => {
    pm.test(`expect ${element.AccountID} to not be null`, () => {
        pm.expect(element.AccountID).is.not.oneOf([null, undefined]);
    });
});

Thanks very much. Between your example and the examples from w4dd325 this is what I was hoping for and a way I can continue learning and building from these. I really appreciate the direction here which will assist me in moving forward with a little nudge :slight_smile: