How to test if an environment variable is defined?

Postman for Mac Version 6.0.9
OS X 10.13.3 / x64

I am setting environment variable in one request and then using it in a subsequent request. I want to test if the environment variable is defined (it should fail if env variable not defined). However the test is passing when the variable is not defined.

My test code is:
var esi = postman.getEnvironmentVariable(“es_id”);
console.log(“search ES id: “+esi)
tests[“ES ID (”+esi+”) is defined”] = esi !== “(undefined)”;

The Test Results tab shows:
PASS ES ID (undefined) is defined

Console shows:
search ES id: undefined

1 Like

@testmonger

Try this method of checking for ‘null’/‘undefined’ … “testVar” was not set …

var test = pm.environment.get("testVar");

console.log(test);

if( !test) {
    console.log("testVar is not defined");
}

Using the ! will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.

2 Likes

@dhoyt That will work. But we also have a pm.environment.has API to check if the environment has a particular key(variable) defined.

@testmonger this would be the test you’re looking for

pm.test('foo should exist', function () {
    pm.expect(pm.environment.has('foo')).to.equal(true);
});

This is also supported as pm.globals.has.

Here’s a complete API reference of the Postman Sandbox for reference - https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference

5 Likes

Great suggestion, thank you @kamalaknn (I should have seen that :wink: ).

Thanks also @dhoyt dhoyt for the reply.

I found a usage for this where I am pulling elements out of an array stored in an environment variable, and I want to test that the array is not empty as a precaution.

// retrieve the list of tests from the environment variable
// and parse it into a typed object
if( pm.environment.has(‘actionList’) ) {
var actionList = JSON.parse(environment.actionList);
// check if there are still test actions to run
if (actionList.length > 0) {
//remove first element and set it as the next request
var test_request = actionList.shift();
//convert the list to a string and store it back in the environment variable
//minus the test we just pulled out
postman.setEnvironmentVariable(“actionList”,JSON.stringify(actionList));
postman.setNextRequest(test_request);
console.log("next test action: "+test_request);

//** etc… **//

Thanks dhoyt; great reference for syntax that I keep coming back to! :slight_smile: