Inject Code into test-script

Hi guys,

I want to ask, if there is a way to “inject” code to every test script in postman?
That I dont need to paste it everywhere, for each API-test?

Thanks a lot

1 Like

Hi @Anton39,

You can add the test script at a collection level, so that the test script gets executed for each request in the collection, thereby removing the need to add the same script for each request.

You can do that by following the steps given in the following link: https://learning.getpostman.com/docs/postman/scripts/test_scripts/#adding-a-test-script-to-a-collection-or-folder

2 Likes

Thanks a lot.
Is it possible to add a test script for multiple collections?
For example, I have 10 collections, and all need to use the same script?
Maybe there is a way to do it with postman?

Thanks

No, it is not possible to add the same test script because ideally, each collection is a self-contained unit executing a specific set of related functions and responsibilities, so there would be no need to execute the same test script across multiple collections.The structure is such that multiple related requests are organised into folders, which are then in turn organised into a collection.
But then again, each user is free to organise their collections and tests based on how it works best for them.

1 Like

Is it possible to include this script once and run the collection in newman?
If yes, how?

Is it also possible to run a pre-script for every collection?
That I dont need to duplicate the code?

Hi @Anton39,

You can add the Test scripts and Pre-Request scripts at the collection level as I mentioned previously and you can refer the following link which will provide you the required information to start running collections using Newman CLI. https://learning.getpostman.com/docs/postman/collection_runs/command_line_integration_with_newman/

I know this is an older post, but maybe you’re still out there.

Is it not possible to have test cases that are needed across all collections?

Say I want to do a status 200 check for all my requests across all collections.

If I have 10 collections, that’s 10 places the code is duplicated.

Unless I create a collection that only runs status 200 checks, then I’m duplicating code.

The Collection is the thing that holds all the individual information and one collection doesn’t know about another one.

If you were to export the individual collection and run it, it would be using that status code check - if you were to set this at say the Workspace level (which isn’t possible) the exported collection wouldn’t know about that being there.