Postman API Test Script Cases Tutorial
To write a test script in postman, open a request in your Postman app and open the Tests tab.
Enter JavaScript code:
pm.test(“Status code is 200”, function () {
pm.response.to.have.status(200);
});
You can check the test results by opening the Test Results tab in the Response area.
In postman, you can use Chai Assertion Library for asserting tests as per requirements. The pm object contains request, response, and environment information that can be used in our tests.
Let's jump into learning more ways by which we can write test cases for API
You can watch detail tutorial video here:
How to get response data in JS Object
var responseJson = pm.response.json();
//pm object contains request, response and environment information which can be used in our tests.
1) Test response filed value
pm.test(“The response field page have value 150”, () => {
//parse the response json and test three properties
var responseJson = pm.response.json();
pm.expect(responseJson.page).to.eql(150);
});
2) Test multiple response filed value
pm.test(“The response field values”, () => {
//parse the response json and test three properties
var responseJson = pm.response.json();
pm.expect(responseJson.page).to.eql(150);
pm.expect(responseJson.total).to.eql(12);
});
3) Test Response status code
pm.test(“Status code is 200”, function () {
pm.response.to.have.status(200);
});
4)Test from multiple Response status code list
pm.test(“Successful POST request”, () => {
pm.expect(pm.response.code).to.be.oneOf([200,201]);
});
5) Test Status Message
pm.test(“Status code name has string”, () => {
pm.response.to.have.status(“OK”);
});
6) Test Header
pm.test(“Content-Type header is application/json”, () => {
pm.expect(pm.response.headers.get(‘Content-Type’)).to.eql(‘application/json; charset=utf-8’);
});
pm.test(“Response property matches environment variable”, function () {
var pageVal = pm.environment.get(“pageValue”);
pm.expect(pm.response.json().page).to.eql(pageVal);
});
7) Test from environment variable
pm.test(“Response property matches environment variable”, function () {
var pageVal = parseInt(pm.environment.get(“pageValue”));
pm.expect(pm.response.json().page).to.eql(pageVal);
});
/8) Assert Response Time
pm.test(“Response time is less than 200ms”, function () {
pm.expect(pm.response.responseTime).to.be.below(200);
});