I have a response from one of the endpoints like below
{
"links": [
"First String",
"Second String"
]
}
Some times the values will be interchanged in the response.
Now I need to store only the Second String in the Environment Variable so I wanted to use if condition and if it satisfies the condition then store it.
But I don’t know how to do it.
Can anyone help with if condition how to write in tests
Hi @danny-dainton ,
Thank you for your response.
Yes there will be only 2 values, but the values will be interchanged in the response so there is no guarantee I will have Second String in 2nd place.
So before assigning the value I need to compare them
I did like this and issue is solved
var data = JSON.parse(responseBody);
var temp=data.links[0];
if(temp.includes(“accounts”)){
postman.setEnvironmentVariable(“variable”, data.links[0]);
}
else{
postman.setEnvironmentVariable(“variable”, data.links[1]);
}
I think you know, but this isn’t a reliable way to program this. I think you’re assuming the string value “accounts” will always return, and that it’s only ever going to be an array of two. If the data in your response array changes and ‘accounts’ doesn’t exist, you’re going to get an error.
I assume if you’re writing this test in this way, it’s because your interface needs to be able to do the same thing (tell the array list items apart to show a specific one). They will have an issue getting the information reliably, too, so it would still be a good idea to open a bug ticket with your API team to get them to send the data consistently and predictably. I would even go as far as to request an architectural change (if it were me) in this situation, so that you (and your interface) receive a key:value pair for each link and can properly index it, rather than string comparing in a for-loop through the array. But to each their own.