73

I'm using the packaged app version of Postman to write tests against my Rest API. I'm trying to manage state between consecutive tests. To faciliate this, the Postman object exposed to the Javascript test runtime has methods for setting variables, but none for reading.

postman.setEnvironmentVariable("key", value );

Now, I can read this value in the next call via the {{key}} structure that sucks values in from the current environment. BUT, this doesn't work in the tests; it only works in the request building stuff.

So, is there away to read this stuff from the tests?

chad
  • 7,369
  • 6
  • 37
  • 56

2 Answers2

101

According to the docs here you can use

environment["foo"] OR environment.foo
globals["bar"] OR globals.bar

to access them.

ie;

postman.setEnvironmentVariable("foo", "bar");

tests["environment var foo = bar"] = environment.foo === "bar";

postman.setGlobalVariable("foobar", "1");

tests["global var foobar = true"] = globals.foobar == true;

postman.setGlobalVariable("bar", "0");

tests["global var bar = false"] = globals.bar == false;
gooddadmike
  • 2,329
  • 4
  • 26
  • 48
  • 4
    One thing I noticed is that when I set the global var, I set it as int; when I read it back it was a string. So I needed to parse it: tests["stress"] = data.Rating.RatingScoreList[1].Value === parseInt(globals.stress); – Duncan Apr 14 '16 at 19:57
  • 9
    From the docs [here](https://www.getpostman.com/docs/environments): "Warning - Environment and global variables will always be stored as strings. If you're storing objects/arrays, be sure to JSON.stringify() them before storing, and JSON.parse() them while retrieving." – GrayedFox Aug 02 '16 at 10:04
  • Also note that globals is not supported if you're planning on using [postman monitors](https://www.getpostman.com/docs/v6/postman/monitors/intro_monitors), while environment variables are. – Jim Aho Mar 09 '18 at 12:22
12

Postman updated their sandbox and added a pm.* API. Although the older syntax for reading variables in the test scripts still works, according to the docs:

Once a variable has been set, use the pm.variables.get() method or, alternatively, use the pm.environment.get() or pm.globals.get() method depending on the appropriate scope to fetch the variable. The method requires the variable name as a parameter to retrieve the stored value in a script.

J.Lin
  • 1,120
  • 9
  • 11