If you want to create a method to maintain some control over when the code is executed (instead of for every request if its set at the collection level), then you can use something similar to the following.
You need to initialize a variable at a global level (just define the variable without LET, CONST or VAR) with your function inside.
You will need to pass “pm” as an argument to the function if you intend to utilize Postman functions (which as you want to run tests, you will need to do).
The same applies if you want to access the pm.response method in your function.
utils = {
statusCode: function (pm) {
pm.test("Status code is 200", () => {
pm.response.to.have.status(200);
})
return 'hello';
},
response: function (pm) {
console.log(pm.response.json());
return 'hello';
}
};
You can then call these functions in your tests tab.
utils.response(pm);
utils.statusCode(pm);
To make it more re-usable, you may want to consider extending the arguments with customizable parameters.