We make heavy use of environment variables in Postman. But I’ve run into two roadblocks:
pm.environment.get()
(and its equivalents) do not evaluate embedded variables. So if I get a variable that has another variable in it,{{var1}}
is not replaced byval1
.
I got around this problem by writing a common function that I call in all my tests instead of pm.environment.get()
. The function is called recursively until all the variables aree evaluated:
var funcGetAndEvalEnvVar = (varName) => {
const EMBEDDED_VAR_REGEX = new RegExp(`{{\\w+}}`, 'g');
var varValue = environment[varName];
var evalVarValue = varValue;
var reMatch;
while (reMatch = EMBEDDED_VAR_REGEX.exec(varValue)) {
var embeddedVar = reMatch[0];
var embeddedVarName = embeddedVar.slice(2, -2);
if (environment.hasOwnProperty(embeddedVarName)) {
var embeddedVarValue = funcGetAndEvalEnvVar(embeddedVarName);
evalVarValue = evalVarValue.replace(new RegExp(embeddedVar, 'g'), embeddedVarValue);
}
}
return evalVarValue;
};
- After resolving the issues with #1 above, I thought I was in good shape. However, I also use variables in the request bodies, that contain embedded variables at multiple levels. The variables seem to only be evaluated at a limited number of levels. So I’m still having the same problems.
I tried to write the following pre-request script, but of course, according to the doc, the request
object is read-only (I created this script just in case it might be wrong!):
var REQUEST_DATA_VAR = 'requestData';
pm.environment.set(REQUEST_DATA_VAR, request.data);
request.data = funcGetAndEvalEnvVar(REQUEST_DATA_VAR);
My feature request is that it would be very helpful if all environment variables at all levels would be evaluated by Postman.
If this is not possible / feasible, then my alternate feature request would be to give the pre-request script a way to update the data in the request, instead of it being read-only.