I have some scripts that I have written myself that perform parsing and assertions on responses and I reuse these in multiple requests. Currently I am copying and pasting each of these scripts into each test. It would be nice to have the functions declared in a central library so I don’t have to manually update each collection/folder/request where they are declared.
I figured that maybe declaring a function on the collection level would make it available for a request within that folder, but no such luck. From the Postman Console:
ReferenceError | parseResponse is not defined
Is it possible to reference in a user-defined collection of functions?
I do this by running something in the test script for the collection that defines a global variable, then I can reuse in my tests.
In the collection scripts:
postman.setGlobalVariable(“DoAThing”, (Variable) => {
//do some stuff
});
And then in the specific tests as:
eval(globals.DoAThing)(var);
It’s not great, and eval isn’t a great thing to use, but it saved me a lot of time compared to changing stuff directly in loads of individual tests!
You can execute the same tests for every request in the collection without specifically adding it to each request by adding the tests at the collection level.
You can write test scripts at the collection level by clicking on the ellipsis “…” next to the collection, clicking on Edit and adding your test scripts in your pre-request scripts or tests based on your requirements as seen in the attached image.