I have some duplicate code I want to refactor and store in a postman collection variable. This function code is only duplicated once in my postman unit tests but I don’t want even one duplication. So, I’m trying to store it in a collection variable and execute it however many times I need it.
As an arrow-function it works perfectly.
const parseMillisecondsIntoReadableTime = milliseconds => {
// From the milliseconds parm, this function calculates
// hours (h), minutes (m) and seconds (s) and returns a string like: "0h 29m 59s".
return parseInt(h) + 'h ' + parseInt(m) + 'm ' + parseInt(s) + 's';
};
Sample usage that works:
const timeToExpire = parseMillisecondsIntoReadableTime(pm.collectionVariables.get('access_token_expiry') - new Date());
Now I want to store this function in a postman collection variable.
Object.prototype.parseMillisecondsIntoReadableTime = function(milliseconds) {
// same code as above
// From milliseconds parm, this calculates
// hours (h), minutes (m) and seconds (s) and returns this string.
return parseInt(h) + 'h ' + parseInt(m) + 'm ' + parseInt(s) + 's';
};
It works on one request but for all the rest, I get this Postman test failure message:
Response schema validation successful | Error: schema is invalid: data.properties['metadata'].properties['parseMillisecondsIntoReadableTime'] should be object,boolean.
The response object does have a schema with data and metadata properties. How it is involved in this error is perlexing.
I let PostBot fix the test and got this
pm.test("Response schema validation successful", () => {
const successSchema = JSON.parse(pm.collectionVariables.get("successSchema"));
console.log("200 successful post-request TEST script");
console.log(successSchema);
successSchema.properties['metadata'].properties['parseMillisecondsIntoReadableTime'] = { type: ['object', 'boolean'] };
pm.expect(require("ajv")().validate(successSchema, responseData)).to.be.true;
});
I still get the error. This is the successSchema layout.
const successSchema = {
type: "object",
properties: {
metadata: {
type: "object",
properties: {
status: { type: "string" }
},
required: ["status"]
},
data: {
type: "object",
properties: {
brandName: { type: "string" },
goodsSupplierNumber: { type: "string" },
supplierNumber: { type: "string" }
},
required: ["brandName", "goodsSupplierNumber", "supplierNumber"]
},
errors: {
type: "array",
items: {
type: "object",
properties: {
code: { type: "string" },
message: { type: "string" }
},
required: ["code", "message"]
}
}
},
required: ["metadata", "data", "errors"]
};
pm.collectionVariables.set("successSchema", JSON.stringify(successSchema));