Use one only instance of tests and re-use

tests
testscripts
testing
#1

Hello everyone.

I have some folder with different request, something like:

Folder 1
     request 1
     request 2
     request 3
Folder 2
     request 1
     request 2
     request 3
Folder 3
     request 1
     request 2
     request 3

The thing is that all request 1 use the same test (same for request 2 and request 3). The reason for this is that there are some little differences on the bodies, but the structure of the responses is similar.

The problem here is that I need to duplicate all those tests for all the folders, and if I make some change replicate it in all the instances of the tests.

Isn´t there any way to write this code only once, encapsulate like functions and then call these functions from the Test area of the request??

Thank you very much.

#2

You can set a global variable that contains a “function” in the “pre-request” script of request 1.

As an example, this is some code that I run in the “test” script for a lot of the endpoints that I run.

pm.globals.set('test200', test200 = function () { 
  if( responseCode.code != 200 ) {
    tests['expected responseCode is 200 ... responseCode received = ' + responseCode.code] = responseCode.code = false ;
    tests['responseCode.name = ' + responseCode.name] = true;
    tests['responseCode.detail = ' + responseCode.detail] = true;
    }
};)

Once it has been loaded once into the global variable pool, the test200 function can now be called from any of your “requests” in the pre-request or test scripts.

eval( pm.globals.get('test200') );
test200();

Or, you can load “test200” into the “global variables” file (globals.postman_globals.json) that will be automatically loaded when each collection is run and you can skip the “pm.globals.set”.

Hope this helps.

2 Likes
#3

Thanks dhoyt!!

I will try (when I have a little of time :confused: ).

#4

I would prefer to use the same request which depends on environment variables instead of duplicate requests.