user12845915
user12845915

Reputation: 69

Saving Postman environment variables not working correctly?

I'm experiencing a strange thing when exporting environment variables in my test and pre-request scripts. Let's take the following code:

var temp = ["a", "b", "c"];
pm.environment.set("Array1", temp);
temp.length=0;
temp = ["1", "2", "3"];
pm.environment.set("Array2", temp);
temp.length=0;
temp = ["ZZ", "YY", "XX"];
pm.environment.set("Array3", temp);
console.log(pm.environment.get("Array1")); // expected = ["a", "b", "c"]
console.log(pm.environment.get("Array2")); // expected = ["1", "2", "3"]
console.log(pm.environment.get("Array3")); // expected = ["ZZ", "YY", "XX"]

I'm expecting all 3 arrays to have value right? Surprisingly the results are:

[]
[]
["ZZ", "YY", "XX"]

Only the last one is correct. And I can carry on with more arrays, everytime, only the last one gets really updated, all the other ones remain desperately empty. I don't understand what's wrong. Beside, I tried postman.setEnvironmentVariable instead of pm.environment.set and it worked find. Any idea? Thank you.

Upvotes: 4

Views: 7081

Answers (1)

Kurtis Rader
Kurtis Rader

Reputation: 7459

FWIW, this isn't really a Postman question. It's a question about Javascript. I don't know anything about Postman but its pm.environment.set() method is obviously saving a reference to the array object rather than making a copy. When you subsequently do temp.length = 0; you truncate that array object so that it has zero elements. When you subsequently do temp = ['new', 'array']; you're creating a new array object and assigning a reference to it to the temp var. You then pass that new array object reference to the next pm.environment.set(). Note that the temp.length = 0; statement is unnecessary and the source of your problem.

See https://www.w3schools.com/js/js_arrays.asp

P.S., I'm curious what documentation you read that implied doing temp.length = 0; was the right thing to do.

Upvotes: 1

Related Questions