DEV Community

Rohit Jain
Rohit Jain

Posted on

3 2

How to Write Tests in Postman - API Testing


Writing tests in Postman is a great way to test your API. It is easy as well as necessary for your API Development as it makes sure your API is working as expected. You can check all your API in a couple of clicks. Let's Talk about how to test API in Postman.

First of all, you need to create a collection in Postman. I hope you already know how to create a collection and how to add a request to it.
After that, you need to write tests in the Tests tab.

Tests in postman are based on the Chai Js Assertion Library.
Chaijs is a BDD(Behavior Driven Development)/TDD(Test Driven Development) assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

Let's start with the most basic and very useful test.

Check Response Status

pm.test("Status code is 201",()=>{
    pm.response.to.have.status(200);
    pm.expect(pm.response.code).to.equal(200);
    pm.expect(pm.response.code).to.be.oneOf([201, 200]);
    pm.response.to.be.ok;
});
Enter fullscreen mode Exit fullscreen mode

pm.test is a Postman function that takes the name of the test and a callback function as arguments. Inside the callback function, you can write your assertions.
as you can see in the above example

  • First: Checking that the status code is 201.
  • Second: Expecting the response code is equal to 201.
  • Third: Expecting the response code is one of the following: [201, 200].
  • Forth: Checking that the response type is Ok.

Checking the Response time

pm.test("Response time is less than 200ms", () => {
    pm.expect(pm.response.responseTime).to.be.below(250);
});
Enter fullscreen mode Exit fullscreen mode

Is Content type is Present? Content type is JSON or not ?

pm.test("Content type is present", () => {
    pm.response.to.have.header("Content-Type");
    pm.expect(pm.response.headers.get("Content-Type")).to.be.equal("application/json");
    pm.response.to.be.json;
});
Enter fullscreen mode Exit fullscreen mode

Checking the Response Type by first storing the response in a variable

pm.test("Test data type of the response", () => {
    const res = pm.response.json();
    pm.expect(res).to.be.an("object");
    pm.expect(res.name).to.be.a("string");
    pm.expect(res.age).to.be.a("number");
    pm.expect(res.hobbies).to.be.an("array");
    pm.expect(res.website).to.be.undefined;
    pm.expect(res.email).to.be.null;
    pm.expect(res).to.be.ok;
});
Enter fullscreen mode Exit fullscreen mode

Response body should be an array and should have at least one element

pm.test("Response body should be an array", () => {
    let res = pm.response.json();
    pm.expect(res).to.be.an("array");
    pm.expect(res).to.have.length.above(0);
});
Enter fullscreen mode Exit fullscreen mode

Checking for the response have a particular key & Include a particular string

pm.test("Response should have a name & id property", () => {
    let res = pm.response.json();
    pm.expect(res[0]).to.have.property("name");
    pm.expect(pm.response.text()).to.include("id");
});
Enter fullscreen mode Exit fullscreen mode

Response body should not return the password

pm.test("Response body should not return password", () => {
    let res = pm.response.json();
    pm.expect(res).to.not.include("password");
    pm.expect(res).to.not.have.property("password");
});
Enter fullscreen mode Exit fullscreen mode

There are all the basic tests you can write in Postman.

Let's check out some helper functions to make your testing easier.

Setting Different types of Variables

let res = pm.response.json();
pm.environment.set("id", res[0]["id"]);
pm.collectionVariables.set("id", res[0].id);
pm.globals.set("id",res[0]["id"]);
console.log(pm.environment.get("id"));
Enter fullscreen mode Exit fullscreen mode

They're different in the types of variable is the scope of the variable. Globals are available to all the tests in all the collections. Collection Variables are available only to the tests in the collection. Environment variables are available to all the tests in the collections if the environment is set.

Checking the Active Environment

pm.test("Check the active environment", () => {
    pm.expect(pm.environment.name).to.eql("Api-Template");
});
Enter fullscreen mode Exit fullscreen mode

Basic schema validation

The database schema is its structure described in a formal language supported by the DBMS. The term "schema" refers to the organization of data as a blueprint of how the database is stored in the database.

var schema = {
    "items": {
        "type": "boolean"
    }
};

var data1 = [true, false];
var data2 = [true, 123];

pm.test("Schema is valid", () => {
    pm.expect(tv4.validate(data1, schema)).to.be.true;
});
Enter fullscreen mode Exit fullscreen mode

Send request inside Test

pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});
Enter fullscreen mode Exit fullscreen mode

That's Sit for basic to intermediate level of testing of APIs in Postman

Let me know if you have any questions or queries. I’ll be happy to help you

Like Share, and Follow. You can also check my other profiles on King Technologies

Thanks for Reading

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay