8

Problem: I want to set a counter variable (a numeric value) in environment variable, so in "Test" we can control the flow.

My experiment: I wrote a simple API call with following-

  1. Prescript sets the counter variable-

    postman.setEnvironmentVariable("mycounter", 1);
    
  2. Test verifies the counter variable, if its value equals to 1, increment it by one-

    if (postman.getEnvironmentVariable("mycounter") == 1 ) {
    
        postman.setEnvironmentVariable("result", "YES");       
        postman.setEnvironmentVariable("mycounter", 
            1+postman.getEnvironmentVariable("mycounter")); 
    } 
    else {
        postman.setEnvironmentVariable("result", "NO"); 
    }
    

But when i check the value for "mycounter"-

  • Actual value: 11
  • Expected value: 2

Can anybody point out how to set numeric value in environment variable?

roschach
  • 8,390
  • 14
  • 74
  • 124
Sam
  • 859
  • 3
  • 12
  • 23

3 Answers3

16

I got workaround. By using Number function convert string to integer.

So

if (postman.getEnvironmentVariable("mycounter") == 1 ) {
    postman.setEnvironmentVariable("result", "YES");
    postman.setEnvironmentVariable("mycounter", 1+Number(postman.getEnvironmentVariable("mycounter")));  
} else {
    postman.setEnvironmentVariable("result", "NO"); 
}
mrroboaat
  • 5,602
  • 7
  • 37
  • 65
Sam
  • 859
  • 3
  • 12
  • 23
  • 1
    I tried same while setting the counter variable, but it did not work. So looks like environment variable always set as String irrespective what type we are sending. Can anybody please confirm my assumption? – Sam Jun 02 '17 at 20:18
5

I think the sam's answer works but here is a cleaner way I use in one of my pre-request scripts

let myCounter = +environment["mycounter"];  // '+' Convert String into Integer
if (myCounter == 1) {
    myCounter++;
    postman.setEnvironmentVariable("result", "YES");
    postman.setEnvironmentVariable("mycounter", myCounter);  
} else {
    postman.setEnvironmentVariable("result", "NO"); 
}

More informations about converting ==> https://stackoverflow.com/a/1133814/1646479

mrroboaat
  • 5,602
  • 7
  • 37
  • 65
2

With the new Postman API pm:

let myCounter = pm.environment.get("mycounter");
if (myCounter == 1 ) {
    pm.environment.set("result", "YES");
    pm.environment.set("mycounter", 1+Number(myCounter));  
} else {
    pm.environment.set("result", "NO"); 
}

the old postman. API is going to be deprecated and will be removed in future.

Muhammad Sheraz
  • 569
  • 6
  • 11