// Response should have JSON Body
pm.test("Response should have JSON Body", function () {
pm.response.to.have.jsonBody();
});
// Check for Successful Status code
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Check if Items number equals to Expected (ex.: total)
pm.test("Items Count is equals to Total", function () {
var total = pm.response.json().total;
var actual = pm.response.json().items.length;
pm.expect(total).to.eql(actual);
});
// Response Validation
const schema = {
"required": ["id", "name", "expires_in"],
"properties": {
"id": { "type": "integer", "minimum": 1 },
"name": { "type": "string", "pattern": "^(.*)$" },
"expires_in": { "type": "integer", "minimum": 0 }
}
};
// Test whether the response matches the schema
tests["Response Data is valid"] = tv4.validate(pm.response.json(), schema);
// Print Validation Error Details
if (tv4.error !== null) {
console.log("Validation errors: " + tv4.error.message + " at " + tv4.error.dataPath, tv4.error);
}
Place these Scripts into Collection Pre-Request Scripts
// Reusable Functions for Postman Asserts
let functions = function loadAsserts() {
let asserts = {};
asserts.isJsonResponse = function isJsonResponse() {
pm.test('Response should have JSON Body', function () {
pm.response.to.have.jsonBody();
});
};
asserts.isResponseStatus = function isResponseStatus(statusCode) {
pm.test('Status code is ' + statusCode, function () {
pm.response.to.have.status(statusCode);
});
};
asserts.isEquals = function isEquals(expected, actual, message) {
message = message || 'Expected value is Equals to actual';
pm.test(message, function () {
pm.expect(expected).to.eql(actual);
});
};
asserts.validateJsonSchema = function validateJsonSchema(schema) {
tests["Response Data is Valid"] = tv4.validate(pm.response.json(), schema);
if (tv4.error !== null) {
tests["Validation ERROR => " + tv4.error.message] = "";
}
};
return asserts;
} + '; loadAsserts();';
let postmanAsserts = JSON.stringify(functions);
if (!pm.globals.has('postmanAsserts') || pm.globals.get('postmanAsserts') !== postmanAsserts) {
pm.globals.set('postmanAsserts', postmanAsserts);
tests['Set up Postman Asserts to Globals'] = pm.globals.has('postmanAsserts');
}
Next - invoke this script inside Postman Tests
// evaluate functons
let test = eval(JSON.parse(pm.globals.get("postmanAsserts")));
// Describe Schema for Validation
const schema = {
"type": "object",
"required": ['args', 'headers']
};
// Assertion usage Examples
test.isJsonResponse();
test.isResponseStatus(200);
test.validateJsonSchema(schema);