Search code examples
postmanbearer-tokenweb-api-testingpostman-testcase

Value of an environment variable is reset to null in Postman


I have a login request that returns a token that gets saved to environment variables via the following script added in Postman - Tests tab:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token_abc", jsonData.access_token);

Another request uses that token in the Authorization header as Bearer {{token_abc}}.

But, it seems the token is valid only for one-time use: after request #2 is sent, the value of token_abc is reset to null in Environment variables - Current value.

What could be causing this? Because this is not how the application usually behaves - the token should be valid for 24 hours. Is there a Postman setting I'm not seeing somewhere? I'm using Postman 8.6.1.


Solution

  • For some reason unknown to me there are 2 "postman" object in the postman sandbox that you can use to set environment variables.

    • postman
    • pm

    Both can call a function for setting variables on the variable scopes in postman. From what I gathered on forums discussing various postman problems, the usage of the postman object gets discouraged in favor of pm.

    See if this helps:

    //check if you get the value you expected first
    console.log(jsonData.access_token)
    pm.environment.set('token_abc', jsonData.access_token)
    

    Since your variable gets reset somewhere, there must be code in your script responsible for that. You mention the variable gets reset after request #2, so the first place to look is in the "Tests" tab of your second request. You can use console.log(value) to output the value of that variable to console on various places in that script in order to further pinpoint the exact location in code where it gets reset.