How to reuse function in 2022?

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');