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