Nag-Raj
Nag-Raj

Reputation: 179

Getting Cannot read property in postman scripts when null found

I am getting an Error when running a script in the Postman Tests tab, When trying to check that a property is not null.

My JSON response:

{
    "statusMessage": "Success",
    "timeStamp": "2018-01-23 05:13:16.7",
    "numberOfRecords": 7,
    "parties": [
        {

        "shippingAddress": null,
        "shippingDetails": null,
        "paExpirationDate": "",
        "historyDate": "01/22/2018",
        "renewal": {
            "renewalRx": "N",
            "priorRxNumber": "",
            "priorSB": "",
            "priorFillNumber": ""
        },
        "noOfRefillingRemaining": "1",
        "ndc": "00074-3799-06",
        "rxId": "7004942",
        "fillingNumber": "0"
    },

    {          
        "shippingAddress": {
            "addressLine1": "2150 St",
            "addressLine2": "Home Line 2",
            "city": "Bronx",
            "state": "NY",
            "zipCode": "10453",
            "addressSeqNumber": "1",
            "medFacilityIndicator": "N"
        }
    }

]
}

My postman script is:

var jsonData = JSON.parse(responseBody);
var parties = jsonData.parties;

parties.forEach(function(data){

 if(data.shippingAddress!==null && data.shippingAddress.addressLine1 !== null ){

    postman.setEnvironmentVariable("addressLine1",data.shippingAddress.addressLine1);

}

I am getting the following error:

"Error running tests for results: TypeError: Cannot read property 'addressLine1' of null"

Upvotes: 1

Views: 3513

Answers (1)

Danny Dainton
Danny Dainton

Reputation: 25881

You could try this, I changed your code slightly but this would work:

var parties  = pm.response.json().parties

for(i = 0; i < parties.length; i++) {
    if(parties[i].shippingAddress !== null) {
        pm.environment.set("addressLine1", parties[i].shippingAddress.addressLine1)
    }
}

I tested this locally with the Schema that you provided and that it wrote 2150 St to my environment file.

The schema you posted doesn't seem to be a complete one, I think that the parties array has a shippingAddress property which is either null or it is an object containing the shippingAddress details - I might be wrong but I can't get my head around the data that you posted.

I don't think what you're searching on the in the if statement is correct and it wouldn't work the way you have it because if the first condition is null (like in your response data) it wouldn't ever meet the second condition because the object wouldn't be there and that shippingAddress.addressLine1 reference would always show that error.

Or you could use your code like this:

var jsonData = JSON.parse(responseBody)
var parties = jsonData.parties

parties.forEach(function(data) {
    if(data.shippingAddress !== null) {
        postman.setEnvironmentVariable("addressLine1",data.shippingAddress.addressLine1)
    }
})

Upvotes: 1

Related Questions