Oct 26, 2020

API Testing 'A Beginners View': JavaScript - Array.prototype.length

"length" is a property of arrays in JavaScript. It returns the number of values in an array. 

The value returned by this property is always an integer. We can define the length property to an array at any time. When we extend an array by changing its length property, the number of actual values increases; for example, if we set length to 4 when it is currently 3, the array now contains 4 values, which causes the third value to be a non-iterable empty holder.


Example:

Response Body:

[ { "type": "configuration/entityTypes/HCP", "tags": [ "FCQA", "Jency Test Data", "Integration Testing" ], "attributes": { "Country": { "value": "Brazil" }, "TypeCode": { "value": "Nurse" }, "FirstName": { "value": "Kilian" }, "LastName": { "value": "Lethley" }, "Prefix": { "value": "MR." }, "Gender": { "value": "Male" }, "StatusIMS": { "value": "Active" }, "PresumedDead": { "value": "false" }, "InternationalHCP": { "value": "FALSE" }, "ClinicalTrials": { "value": "false" }, "PrivacyPreferences": [ { "value": { "OptOut": { "value": "false" }, "AllowedToContact": { "value": "false" }, "PhoneOptOut": { "value": "false" }, "EmailOptOut": { "value": "false" }, "FaxOptOut": { "value": "false" }, "VisitOptOut": { "value": "false" }, "TextMessageOptOut": { "value": "false" }, "MailOptOut": { "value": "false" }, "RemoteOptOut": { "value": "false" }, "OptOutOneKey": { "value": "false" }, "KeyOpinionLeader": { "value": "false" }, "ResidentIndicator": { "value": "false" } } } ], "Specialities": [ { "value": { "SpecialtyType": { "value": "Primary" }, "Specialty": { "value": "ANESTHESIOLOGY" }, "Rank": { "value": 1 }, "PrimarySpecialtyFlag": { "value": "true" } } } ], "ValidationStatus": { "value": "Valid" }, "IsBlackListed": { "value": "false" }, "RequiresAttention": { "value": "false" }, "TriggerDCR": { "value": "false" }, "Address": [ { "value": { "PrimaryAffiliation": { "value": "TRUE" }, "AddressType": { "value": "Shipping" }, "Country": { "value": "Brazil" }, "AddressLine1": { "value": "100 Main Street" }, "City": { "value": "Rio de Janeiro" }, "StateProvince": { "value": "RJ" }, "Zip": [ { "value": { "Zip5": { "value": 10000 } } } ], "VerificationStatus": { "value": "Partially Verified" }, "ValidationStatus": { "value": "Valid" }, "Status": { "value": "Active" }, "AVC": { "value": "P22-I44-P2-100" } } } ] } } ]


Test Script:

var resp = JSON.parse(responseBody);
console.log(resp);
for (var i = 0;i<resp[0].tags.length;i++
{
    console.log("Length of vaultID's array is: " + resp[0].tags.length);
    console.log("Index Value during iteration is: " + i);
}

Console Output:

In the above example, based on my JSON response, I have used the length property on array "tags", it's clear from the console output that the length of the array is 3 and in each iteration, the index value is printed correctly as in the screenshot.


Happy Learning 😇


No comments: