How to reuse a function

Is there a sane way to reuse a function?

I would like to put this in top root folder

function env(name) {
    return pm.environment.get(name);
}

and use it like that

pm.expect(pm.response.json().client.id).to.eql(env(‘clientId’));

what I don’t want is to write extra code like this in every test

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

@idpbee you could do the following:

  • In the Collection level pre-request script, declare an object without using the var, let or const keywords. The object is then attached to the global sandbox and is available in child context of that collection.

In the collection pre-request script:

utils = {
    getEnv(v) {
        return pm.environment.get(v);
    }
}

Now within any of the children of that collection, you could simply do the following:

utils.getEnv('name');
3 Likes

Why it works only for getting variables? When in this same manner I have utils object with a method which changes environmentVariables it doesn’t work. I need to pass explicitly in pre-request script of a request pm to make it work.

@Adam

Just pass PM as an argument and this should work.

utils = {
    setEnv(myPm, envVar, val) {
        return myPm.environment.set(envVar, val);
    }
}
utils.setEnv(pm, 'testVariable', 'testValue');

As an option, you can provide a util to set an actual pm for the current script.

And later, you can use it without passing your `pm on each call.

let _pm = null;
utils = {
    setPm(scriptPm) {
        _pm = scriptPm;
    },
    setEnv(envVar, val) {
        return _pm.environment.set(envVar, val);
    }
}
utils.setPm(pm);
utils.setEnv('testVariable', 'testValue');

It is especially useful when you are doing multiple utils calls where the actual pm is necessary.

utils.setPm(pm);
utils.setEnv('testVariable1', 'testValue1');
utils.setEnv('testVariable2', 'testValue2');
utils.setEnv('testVariable3', 'testValue3');

This seems not to work with newman :frowning:

utils is not handover from collection folder level to request level. Anyone have a solution that would work in newman ?

Hey @cardojp5 :wave:

Welcome to the Postman Community! :postman:

As this is an older topic now with a few different solutions suggested, could you share more contextual details about how you have things set up and an example of what’s not working so folks can help you further.