Hi,
I am trying to write a test and have some collection variables defined in the Pre-request script which am using under the Tests section.
My question is, if there is any way to check if the collection variable has some value then only the if-else statement should work and tests can be executed else other console messages can be written.
var enum = pm.collectionVariables.get(“ENUM”)
console.log(enum!==null)
it always types TRUE even if the collectionVariable is empty.
So the collectionVariables are already present, so this will always be true:
var enum = pm.collectionVariables.has(“ENUM”);
I trying to check if they have any data in them or not. That is the reason I wrote console.log(enum!==null) so that if I get a bool value out of it.
Is there anyway to check if the collectionVariable is null or undefined?
Can you give us some more context around this workflow please?
If you’re using .has it wouldn’t return undefined as it would be either true/false. Is there going to be a scenario where the value of the variable will be null?
Where will you be eventually doing this check in your requests/collections?
Hello @padampreet . I’m assuming you are trying to run some piece of code only if the collection variable is present, and if the variable is either null or undefined, you log some messages to the console.
You can do something like this:
var enum = pm.collectionVariables.get("ENUM");
if (enum !== null && enum !== undefined) {
// collection variable "ENUM" exists and is not null or undefined
console.log("collection variable 'ENUM' exists and has data: " + enm);
// code to be run here
} else {
// collection variable "ENUM" is either null or undefined
console.log("some message here");
}
So the workflow is that enum is passed as one of the parameters for the request and as part of tests script I want to check if the request which I sent is equal to what I got in the response.
So to save the request am saving it in collectionVariables and later accessing the value in Tests section to verify the value.
I want to check null/undefined so to check if the value is passed in request, then only the test should run.
Yes, you assumed it right. I am trying to run the Test only if I have the value of enum and when am doing the same that you did it always returns me TRUE even if the Current Value of CollectionVariable is empty.
It would work that way due to it being present (The variable is created and returns true) but it has an empty value. It wouldn’t be either null (Maybe if there was a string value null) or undefined as it’s just an empty variable.