Test APIs with Postman - Scripting

We can set pre-request scripts (run before the request) & tests (after execution) at several levels:

  • Collection
  • Folder
  • Request

Snippets

Inside pre-request Script and Tests we have a SNIPPETS column with templates we may use for our code.

postman scripting

Get / Set variables

console.log("Hello world");

// work with local vars
let urlVar = pm.variables.get("protocol");
console.log("value for protocol: " + urlVar);

pm.variables.set("protocol", "http");
console.log(pm.variables.get("protocol"));  

// work with global vars
let globalVar = pm.globals.get("env");
console.log(globalVar);

Assertions

Postman uses Chai Assertion Library. Check Chai’s Assertions.

Headers

assert header exists

pm.test("Assert header exists", function () {
    pm.response.to.have.header('X-Cache');
});

assert header has value

pm.test("Assert X-Cache has value HIT", function () {
    pm.expect(pm.response.headers.get('X-Cache')).to.eql('HIT');
});

Status Code

assert status code

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

assert status code is any of the following

pm.test("Status code is 20x", function () {
    pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

Body

assert body is not empty

pm.test("Body is not empty", function () {
    pm.expect(pm.response.text()).to.not.be.empty;
});

assert exact body match

pm.test("Body matches x", function () {
    pm.response.to.have.body("OK");
});

Body properties

assert partial body check

pm.test("Response includes 'morpheus'", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.name).to.include("morpheus");
});

assert nested properties

pm.test("Correct output", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.data.email).to.eql("janet.weaver@reqres.in");
    pm.expect(jsonData.data.active).to.be.true;
    pm.expect(jsonData.data.last_name).to.be.null;
    pm.expect(jsonData.data.none).to.be.undefined;
    pm.expect(jsonData.data.array).to.be.empty;
    pm.expect(jsonData.data.email).to.match(regex):
});
// JSON data
{
    "data": {
        "id": 2,
        "email": "janet.weaver@reqres.in",
        "first_name": "Janet",
        "last_name": "Weaver",
        "active": true
    }
}

assert property not equals

pm.test("Doesnt contains name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData["name"]).to.not.eql("morpheus");
});

Assert collections

assert JSON array with fixed positions

pm.test("body has correct content", function() {
    var jsonData = pm.response.json();
    pm.expect(jsonData.data).to.not.be.empty;
    pm.expect(jsonData.data[0].name).to.not.be.null;
})

assert dynamic JSON array child

// JSON output
{
  "page": 1,
  "per_page": 6,
  "total": 12,
  "total_pages": 2,
  "data": [
    {
      "id": 1,
      "name": "cerulean",
      "year": 2000,
      "color": "#98B2D1",
      "pantone_value": "15-4020"
    }
  ]
}
// test
var jsonData = pm.response.json();
pm.test("body is not empty", function() {
    pm.expect(jsonData.data).to.not.be.empty;
})

let item;
for(let iteration of jsonData.data) {
    if(iteration.name == "cerulean") {
        item = iteration;
    }
}

pm.test("body has correct content", function() {
    pm.expect(item.color).to.not.be.null;
    pm.expect(item.year).to.eql(2000)
})

assert dynamic JSON array -> al childs have the same name

{
    "result": [
        {
            "page": "offering",
            "widget": "",
            "section": "",
            "text_en": "",
            "text_ja": "<p>dgdfgdfg</p>",
            "active": true,
            "creation_date": "2022-05-11T10:51:26.433785",
            "modification_date": "2022-05-11T10:51:26.433785"
        },
        {
            "page": "offering",
            "widget": "information",
            "section": "",
            "text_en": "",
            "text_ja": "<p>dfgdg</p>",
            "active": true,
            "creation_date": "2022-05-11T11:52:24.866301",
            "modification_date": "2022-05-11T11:52:24.866301"
        }
	]
}
var jsonData = pm.response.json();
var arrayParent = jsonData.result;
pm.test("body has exactly 2 childs", function() {
    pm.expect(arrayParent).to.not.be.empty;
    pm.expect(arrayParent.length).to.be.eql(2);    
})

pm.test("all childs contain only one name", () => {
	pm.expect(arrayParent).to.not.be.empty;
    _.each(arrayParent, (item) => {
        pm.expect(item.page).to.eql("offering")
    })
})

Example of a complex test:

pm.test("Response status code is 200", function() {
	pm.response.to.have.status(200);
});

pm.test("Body is not empty", function() {
	pm.expect(pm.response.text()).to.not.be.empty;
});

// check body is not empty
if (pm.response.text()) {
	// tests for my own bearer token
	var jsonData = pm.response.json();
	if (jsonData.message.includes("mario")) {

		pm.test("allowed is false", function() {
			var jsonData = pm.response.json();
			pm.expect(jsonData.allowed).to.be.false;
		});

		pm.test("internal status code is 403", function() {
			var jsonData = pm.response.json();
			pm.expect(jsonData.status).to.eql(403);
		});

		pm.test("message has to contain 'has not access'", function() {
			var jsonData = pm.response.json();
			pm.expect(jsonData.message).to.include("has not access");
		});

	}

	if (jsonData.message.includes("sergio")) {

		pm.test("allowed is true", function() {
			var jsonData = pm.response.json();
			pm.expect(jsonData.allowed).to.be.true;
		});

		pm.test("internal status code is 200", function() {
			var jsonData = pm.response.json();
			pm.expect(jsonData.status).to.eql(200);
		});

		pm.test("message has to contain 'has access'", function() {
			var jsonData = pm.response.json();
			pm.expect(jsonData.message).to.include("has access");
		});

	}
}