DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

API Testing with postman.

Postman is an excellent tool for api testing. A little known fact to me was that you can code in javascript tests to ensure that your apis are ready and return the appropriate values.

Each test is run once you fire up your API Call and a response had been returned. So lemme show an example that I needed to do IRL. In my job due to a mobile app bug combined with lack of time I needed to ensure that the APIs does not return null values.

Therefore as first step I setup the API Call using the appropriate environment, then I clicked on the Tests tab.

Then I wrote the following piece of code:

const jsonNotNull = (json) => {
    keys = Object.keys(json);

    keys.forEach((key)=>{
        const value=json[key];

        if(Array.isArray(value)){
            return value.forEach((array_item)=>{
                pm.expect(array_item).to.not.equal(null)
            })
        }

        if(typeof value === 'object'){
            return jsonNotNull(value);
        }

        return pm.expect(value).to.not.equal(null)
    })
}

pm.test("Check if body does not contain null", function(){
  const response = pm.response.json();
  pm.test(response.length > 0);
  jsonNotNull(response);
});
Enter fullscreen mode Exit fullscreen mode

As you can see the pm object contains response item indicating the response of the performed http call. More info about them you can find in: https://learning.postman.com/docs/postman/scripts/test-scripts/

Furthermore pm also contains the assertions uses for example I assert that the response is not null via:

pm.expect(value).to.not.equal(null)
Enter fullscreen mode Exit fullscreen mode

So with pm.expect() you can do assertions like chai does in https://www.chaijs.com/api/bdd/ .

And if you want to run them in a CI/CD pipeline then you can use the newman tool: https://www.npmjs.com/package/newman. Therefore you can export your environment and your api calls and use newman tool to test them.

Top comments (0)