I’m running Postman from the web and I am trying to extract just the values from the response and then also setup a monitor that e-mails when the response values differ from the previous response. For example, the below is a response from an API body I crafted:
I am looking to have a clean response of just the values under the State array. From there, I’d also like to have a monitor run every two hours (I’m familiar how to setup the monitor) that will e-mail if there is any change from the return of:
I was able to figure out utilizing Monitor and SendGrid to generate an email every couple of hours.
The one other hiccup I’m running into is writing an if/else statement where I want it to terminate at this step and not send an email is the array is the same. I set an environmental variable to be identical to the State environmental variable, however based on the console output I am writing this doesn’t work:
They are identical right now as I set both variables the same. I wrote a function to compare the two by checking the length and going through the array.
What’s interesting is if I run it through the thick client, it works. However, in the cloud environment (where the scheduled monitor will run out of) it throws the following error:
Couldn’t evaluate the test script:
TypeError: Cannot read properties of undefined (reading ‘length’)
Here’s the exact code:
function arraysEqual(arr1, arr2){
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++){
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
if (arraysEqual(pm.environment.get("properties"),pm.environment.get("propertiesorig"))) {
postman.setNextRequest(null);
console.log("terminating");
} else {
pm.environment.set("propertiesorig",properties);
console.log("continuing");
}
When working with arrays in Postman, the general advice is to JSON.stringify() the array when storing it, and JSON.parse() it when retrieving it. Otherwise it can sometimes cause issues with it being treated as a string.
However, your example is fairly simple and you should be able to get away without doing this.
In relation to your code, please read the following which goes into detail on how to compare arrays.
Thank you again! I tied the environment variables to the collectionVariables since they would be dynamic and the Pass/Fail on the test works. Working on figuring out how to then tie that into if else statement:
if (pm.test("array 1 matches array 2", function () { //pass
pm.expect(array1).to.eql(array2);
})=="Pass") {
console.log("same");
} else {
console.log("different")
}