A variable cannot retrieve its value which is assigned in the Pre-request script in Newman

Hello,

When a JSON file of a collection is executed through Newman then A global variable cannot retrieve its value which is assigned through the Pre-request script. Tests are shown as failed as the value of that global variable was not retrieved.

If anyone can share any solution to this issue, it will be very helpful.

Thank you

Perhaps you can share the syntax you’re using?

I tried pm.globals.set("variableName", variableValue) in a pre-request script, and then pm.globals.get("variableName) in the test script, and that seems to work when running the collection via Newman.

Thanks Joyce for your reply. Let me explain this issue in detail.

GET Location/getDetails?security_key={{securitykey}}&locationID={{RecentLocationID}}

I wanted to automate this API. From another API response I get an array of locations and counting the array length I assign that value to a global variable - X ( i.e. pm.globals.set(“Variable Name”, “Variable Value”); ). I iterate the run of this ‘getDetails’ API for X times where X is the number of total locations. In every iteration I changed the value of “RecentLocationID” variable through pm.globals.set in the “Tests” section.

Everytime I run the iterations using ‘Collection Runner’, I can successfully run the iterations. But when I use newman for executing the tests then it returns an error for the variable “RecentLocationID”.

As the execution can be properly done, using ‘Collection Runner’ but why I cannot execute properly using newman? This was my query.

I re-created your similar scenario, and seems to be working for me. Two things I would doubly confirm:

  1. If you’re iterating newman runs, like with a script or something, note that global variables are not persisted across collection runs (but should work fine within the collection run).

  2. Also, you can’t import existing global variables into a newman run, but you can create them during a newman run.

However, from your description, sounds like you’re iterating within the same newman run, and also creating the new global variable during the run too. Can you confirm?

The last check I would do is to add some console.log() statements perhaps with your array, for some additional visibility. You can see the logs in the Postman console or your terminal when running with the Collection Runner or Newman, respectively. And see how they compare.

1 Like

Thank you @jetison for your feedback.

I was importing a global variable into Newman and that was the problem. Now I have solved the problem.