Intro: Hi there, I’m on a beginner level of javascript/postman-scripts and trying to figure some stuff out myself to obtain knowledge in this area. I’m using an existing API to figure things out.
My goal: I want to use a function as a pre-request script on a collection-level which I can use inside different post-response test-scripts that are on an endpoint-level.
What’s working: The Scenario#1 is working. When I smash everything in one and the same post-response script on the endpoint-level, the expected value (“111-A1”) gets saved as an environment variable.
What’s not working(/my goal): In stead of having to put this function on every endpoint, I want to put this function on the collection-level and just use the set function-name inside each endpoint-level script, So, the combination of Scenario#2-Part1 and Scenario#2-Part2 are not working.
So; my question: I don’t understand why this is not working. I’ve compared it to several pieces of javascript code, asked my digital robot-friend (famous AI), et cetera and yet I’m creating this thread, because I can’t figure it out. I’m leaning towards “somehow Postman doesn’t allow for a collection-level function” and that’s why I’m creating this thread in this community. Does anyone know if this, in fact, is the case and/or if there is another solution?
Extra information: I’ve tried about 4 variations of basically the same code, but without any luck and thus I’m looking for somebody that actually understands why I can’t seem to achieve the stated goal in stead of just posting the 5th variation (no hard feelings, of course ) … I just want to understand why this is happening…
Scenario#1 - My post-response script on an endpoint-level:
utils = {
setEnvironmentVariable: function(key, value) {
if (value) {
pm.environment.set(key, value);
}
}
};
response = pm.response.json();
fetchfirstarray=response[0];
if ('object1' in fetchfirstarray) {
utils.setEnvironmentVariable("object1variable", fetchfirstarray.object1);
}
Scenario#2-Part1 - My pre-request script on a collection-level:
utils = {
setEnvironmentVariable: function(key, value) {
if (value) {
pm.environment.set(key, value);
}
}
};
Scenario#2-Part2 - My post-response script on an endpoint-level:
response = pm.response.json();
fetchfirstarray=response[0];
if ('object1' in fetchfirstarray) {
utils.setGlobalVariable("object1variable", fetchfirstarray.object1);
}
My response-body looks like this:
[
{
"object1": "111-A1",
"object2": "222-A1",
"object3": "333-A1"
},
{
"object1": "111-A2",
"object2": "222-A2",
"object3": "333-A2"
},
]