Skip to content

Instantly share code, notes, and snippets.

@AlexNDRmac
Last active December 11, 2023 22:37
Show Gist options
  • Save AlexNDRmac/c5c69859d98f97b89746ca9c56dbf2ce to your computer and use it in GitHub Desktop.
Save AlexNDRmac/c5c69859d98f97b89746ca9c56dbf2ce to your computer and use it in GitHub Desktop.
Snippets and Usage examples for Postman autotests

Postman Tests

Assertions examples

// 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);
});

Validate Response with TV4 using JSON Schema

// 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);
}

Reusable functions for Postman | Asserts

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment