Good day,
I get this TypeError: Cannot read properties of undefined (reading 'substr')
error while I am running my tests in runner
, but If I send them one by one
error doesn’t occur.
Few days ago all was ok, but now I am getting this error.
Here are my functions:
//Save response field ([resPath]) value to variable ([varName])
function saveVar(varName, resPath) {
try {
const response = pm.response.json();
console.log(`Attempting to save variable '${varName}' from path '${resPath}'`);
// Retrieve the value from the response based on the resPath
const value = getResponsePath(response, resPath);
if (value !== undefined) {
console.log(`Saving variable '${varName}' with value: ${value}`);
pm.collectionVariables.set(varName, value);
} else {
console.error(`Error: Unable to save variable '${varName}' because the value at path '${resPath}' is undefined.`);
}
} catch (e) {
console.error(`Error in saveVar: ${e.message}`);
}
}
//Get and analyze path from response
function getResponsePath(response, resPath) {
console.log("resPath:", resPath); // Log resPath before splitting
console.log("response:", response); // Log response object
if (!resPath) {
console.error("Error: resPath is not defined");
return undefined;
}
const segments = resPath.split('.');
console.log("Segments:", segments);
let value = response;
for (const segment of segments) {
if (value === undefined || value === null) {
console.error(`Error: Value is ${value} at segment '${segment}'`);
return undefined;
}
// Check for array index
const match = segment.match(/(.+)\[(\d+)\]/);
if (match) {
const propertyName = match[1];
const index = parseInt(match[2], 10);
value = value[propertyName];
if (Array.isArray(value)) {
value = value[index];
} else {
console.error(`Error: Property ${propertyName} is not an array or does not exist.`);
return undefined;
}
} else {
value = value[segment];
}
if (value === undefined) {
console.error(`Error: Unable to access property '${segment}' in response.`);
return undefined;
}
}
console.log(`Final value: ${value}`);
return value;
}