Test functions that are used across all collections in a workspace

Can I re-use the same test functions as a variable to be used by all test tabs in all collections within a workspace.?

Here is an example below of the functions in question. Also see a few values that are being validated by these functions. These work if I add the set of functions to each test tab but I want to use these functions globally on all test tabs in a workspace. I’ve tried using this set of functions at the “Collection Level” test tab but it does not work. It only works if I add them directly to the specific call test tab.

EXAMPLE FUNCTIONS
// Test scripts section to be added to postman collection

// get the json object from the response.

jsonData = pm.response.json();

// method to validate the response code

function validateResponseCode(expectedResponseCode)

{

pm.expect(pm.response.code, 'Response Code').to.equal(expectedResponseCode);

}

function validateQuestion(questionName, expectedValue)

{

var question = jsonData.questions.find(question => question.name == questionName);

validateQuestionWorker(question, questionName, expectedValue, 'Question: [' + questionName + '] Module: [Main] Value Equals:[' + expectedValue + ']');    

}

function validateRMQuestion(questionName, moduleName, moduleIndex, expectedValue)

{

var question = jsonData.questions.find(question => question.name == questionName && question.moduleName == moduleName && question.moduleIndex == moduleIndex);

validateQuestionWorker(question, questionName, expectedValue, 'Question: [' + questionName + '] Module: [' + moduleName + '] Index:'+ moduleIndex + ' Value Equals:[' + expectedValue + ']');

}

function validateQuestionWorker(question, questionName, expectedValue, testTitle){

pm.test(testTitle, function(){

        pm.expect(question, questionName + ' was not found').not.equal(undefined);

        pm.expect(question.value, questionName + ' was found but value is null').not.equal(undefined);

        pm.expect(question.value, questionName).to.equal(expectedValue);

});

}

// method to get document status

function validateDocument(docName, expectedStatus)

{

var document = jsonData.documents.find(documents => doc.name == docName);

pm.test('Document:[' + docName + '] Expected Status:[' + expectedStatus + ']', function(){ 

    pm.expect(document, expectedStatus).not.equal(undefined);

    pm.expect(document.status, expectedStatus).to.equal(expectedStatus);

});

}

// method to get workflow status

function validateWorkflow(workflowName, expectedStatus)

{

var task = jsonData.workflowTasks.find(task => task.name == workflowName);

pm.test('Workflow:[' + workflowName + '] Expected Status:[' + expectedStatus + ']', function(){ 

    pm.expect(task, workflowName).not.equal(undefined);

    pm.expect(task.status, expectedStatus).to.equal(expectedStatus);

});

}

// check context to see if questions are valid

function validateResponseContext(questionsAreValid)

{

pm.test('Validate Response Context', function(){ 

    pm.expect(jsonData.responseContext, 'responseContext.questionsAreValid').not.equal(undefined);

    pm.expect(jsonData.responseContext.questionValuesAreValid, 'responseContext.questionsAreValid').not.equal(undefined);

    pm.expect(jsonData.responseContext.questionValuesAreValid, 'responseContext.questionsAreValid').equal(questionsAreValid);    

});

}

// Test scripts section End #####

EXAMPLE TEST VALUES
/* Test Script For Page Name:‘Event Setup’ Id:‘52000240’ */

validateQuestion(‘IFS.WorkflowXPDLName’, ‘XPDL:Firm - IFS Onboarding:Transaction - Client Onboarding’);

validateQuestion(‘IFS.WorkflowSourceSR’, ‘Firm - IFS Onboarding’);

validateQuestion(‘DomainAccounts_AccountCustodian’, ‘NFS’);

validateQuestion(‘DomainAccounts_AccountRegistration1’, ‘IFS - IRA - Account’);

validateQuestion(‘ProductCommon_TransactionType’, ‘Client Onboarding’);

validateQuestion(‘ProductCommon_CurrentWFStatus’, ‘In Progress’);

validateQuestion(‘DomainCOB_EventName’, ‘IFS - IRA - Account’);

Hi Chris,

There are various ways in which this can be achieved, some of which have been discussed in other topics (Where is the best place to set global functions for tests?, Global functions via Collection level folder?) and some others which have been crowdsourced on StackOverflow over the years (How to write Global functions in Postman).

Following the top-rated eval example on StackOverflow, I was able to demonstrate this working with one of your functions; firstly, by utilising an arbitrary Pre-Request Script tab to submit my group of functions into a global variable:

Set functions in a Global variable
pm.globals.set('loadUtils', function loadUtils() {
    let utils = {};

    utils.validateResponseCode = function validateResponseCode(expectedResponseCode) {
       pm.test("Response status code is " + expectedResponseCode, function () {
           pm.expect(pm.response.code, 'Response Code').to.equal(expectedResponseCode);
       });
    }

    //...repeat for the rest of your functions

    return utils;

} + '; loadUtils();');

tests['Utils initialized'] = true;

…and then you can reference these in any Tests tab anywhere within your workspace:

const utils = eval(globals.loadUtils);
utils.validateResponseCode(200);

Things get a bit more complicated if you want to start setting other variables from within your common functions, but all of the examples you gave appear to be doing straightforward assertions, so hopefully this (and the linked resources) can get you what you need.

1 Like

I did something similar.

I use it for common tests, more involved error conditions, functions, pulling in debug headers etc
Anything to lighten the request script tabs code, making those easier to read. This also makes it so you only need make a change in one place, and everything gets updated and is consistent.

In the Collections Pre-request Script or Tests tab
NOTE: they need to reside in the matching tab where you want to use them.

// at the collection level


// called with.    myTests.<functionName>(<optional arguments>)
myTests = {

    statusCodeTest: function(statusCodeToTest, statusCode){
        pm.test(`Verify Status code <<${statusCodeToTest}>> is ${statusCode}`, function () {
        pm.response.to.have.status(statusCode);
        });
    },

    statusCodeInListTest: function(statusCodeToTest, statusCode){
        pm.test("Verify State <<"  + responseState + ">> to equal:  " + expectedState, function () {
            pm.expect(responseState).to.equal(
            expectedState);
        });
    }
}

These are called from the child requests with:

//set up
const responseStatusCode = pm.response.code
const expectedStatusCode_200 = 200
const expectedStatusCode_400 = 400
const expectedStatusCodes = [200, 400]

//tests
MyTests.statusCodeTest(responseStatusCode, expectedStatusCode_200)
MyTests.statusCodeInListTest(responseStatusCode, expectedStatusCodes)

...



Similarly, used here for error conditions with potentially bulky json, as here: 
...
//setup
//collected errors
const json_result_503 =
{
    "code": 503,
    "message": "server busy"
}

const json_result_sensor_FAIL = {
    "code": 400,
    "message": "sensor is not configured"
}

const json_result_model_FAIL = {
    "code": 400,
    "message": "modelId missing from header"
}

const json_result_buffer =
{
    "code": 400,
    "message": "The  buffer must have at least 400 rows of data."
}

const json_result_invalid_chunk =
{
    "code": 400,
    "message": "invalid chunk specifier: 'undefined:4'"
}

//tests
// error conditions
myTests.errorNotEncounteredTest(json_result_503, 503)
myTests.errorNotEncounteredTest(json_result_model_FAIL, "modelId")
myTests.errorNotEncounteredTest(json_result_sensor_FAIL, "sensorId")
myTests.errorNotEncounteredTest(json_result_buffer, "buffer")
myTests.errorNotIncludeStringTest(jsonData, "invalid chunk specifier")
myTests.errorNotIncludeStringTest(pm.response.headers, undefined)