Table of contents
1.
Introduction🤖
2.
Assertions in Postman🤓
3.
Finding an Object in Array by its Property Value📢
4.
Finding a Nested Object by Object Name🌐
5.
Comparing Response Value with pre-defined Variable😃
6.
Comparing Response Value to Multi-Valid Values😇
7.
Parsing an HTML Response to Extract a Specific Value🦾
8.
Fixing the Error “ReferenceError: jsonData is not defined”💻
9.
Performing Partial Match Assertions in Postman🦿
10.
Frequently Asked Questions
10.1.
What exactly is Postman's History tab?
10.2.
What is the Payload in Postman?
10.3.
What is the Postman Team workspace?
11.
Conclusion
Last Updated: Mar 27, 2024

What are the Assertions in Postman?

Author Ayush Mishra
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction🤖

In computer programming, writing a simple code is necessary to understand, but most of the time, we have to write bulky codes. Assertions help programmers to read the code, help the compiler to compile the code, or help the programmer detect defects in the code.

In this blog, we will discuss Assertions in Postman.

In this blog, we will discuss Assertions in Postman in deep detail. Let’s start going!

Assertions in Postman🤓

In this context, we will discuss assertions in Postman

Assertions are used to check whether the actual and expected values have matched after a test has been run. If they do not match, the test will fail, and the reason for failure will be revealed in the test output.

An assertion returns a true or false value only. It can be added to our test code with the help of the Chai Assertions Library.

Finding an Object in Array by its Property Value📢

In this first part of “Assertions in Postman,” we will discuss how to find an object by its property value in Array. 

Suppose you have the following response:

{
    "filters": [
        {
            "id": 220,
            "name": "College",
            "isAllowed": false
        },
        {
            "id": 221,
            "name": "City",
            "isAllowed": true
        },
        {
            "id": 222,
            "name": "State",
            "isAllowed": false
        }
    ]
}

 

Assert that the City filter's property isAllowed is true.

pm.test("Check the City filter is allowed", function ()
 {
 
      var jsonData = pm.response.json();    // Process the response body

    // Find the array index for the City
    var City_Index = jsonData.filters.map(
            function(filter)
             {
                return filter.name; // Name of the property
            }
        ).indexOf('City’); // Index of Name you are searching for in array

    // Get the city filter object by using the index calculated above
    var cityfilter = jsonData.filters[City_Index];


    //Check that the city filter exists
    pm.expect(cityfilter).to.exist;


    //Check that the city filter is allowed
    pm.expect(cityfilter.isAllowed).to.be.true;
});

Finding a Nested Object by Object Name🌐

In this first part of “Assertions in Postman,” we will discuss how to find a nested object by its object name.

Suppose you have the following response:

{

“Name”: “TEST1”,
“FileName”: “TEST2.txt”,
“ItemIds”: {

“ABCD1234”: {
…},

“cDBVE”: {

.},
}
}

 

To make the code more readable, we will write the following function:

function findNestObjects(limits) {
    // Iterate over the properties (keys) in the object
    for (var key in limits) {
        // console.log(key, limits[key]);
        // If the property is listed, return the lists object
        if (limits[key].hasOwnProperty('ABCD1234')) {
            // console.log(limits[key].ABCD1234);
            return limits[key].ABCD1234;
        }
    }
}

 

The function will iterate through the limits Array, looking for any objects that contain an ABCD1234 object.

The assertions for the above code are:

pm.test("Status Check", function () {
    // Parse JSON body
    var json_Data = pm.response.json();

    // Retrieve the lists object
    var lists = findNestObjects(json_Data.ItemIds);
    pm.expect(lists.openPerBoard.status).to.eql('ok');
    pm.expect(lists.totalPerBoard.status).to.eql('ok');
});

Comparing Response Value with pre-defined Variable😃

In this part of “Assertions in Postman,” we will discuss how to compare response values with variables defined already.

Suppose you have a value saved to a variable from a previous response.

var json_Data = pm.response.json();  // Getting values from response
var name = json_Data.userName;
// Saving the value for later use
pm.globals.set("username", name);

 

To compare the Response value with the value of the variable from another API response, we need to use a special method, essentially the companion, to set a variable.

pm.test("Your test name", function () {
    var json_Data = pm.response.json();
    pm.expect(json_Data.value).to.eql(pm.globals.get("username"));
});

Comparing Response Value to Multi-Valid Values😇

In this part of “Assertions in Postman,” we will discuss how to compare response values to multi-valid values.

Suppose you have the following response:

{
    "College_ID": "aaa-ccc-xxx",
    "College_Detail": [
        {
            "College_City": "AAAAAA",
            "College_Type": "State"
        }
    ]
}

 

Suppose you need to ensure that the College_Type is Central or State. The assertion could be written as follows:

pm.test("Should be State or Central", function () {
    var json_Data = pm.response.json();
    pm.expect(json_Data.College_Detail[0].College_Type).to.be.oneOf(["National", "State"]);
});

 

In the above assertions:-

▶️ json_Data.College_Detail[0] is the first element of College_Detail array.

▶️ to.be.oneOf allows an array of multi-valid values.

Parsing an HTML Response to Extract a Specific Value🦾

In this part of “Assertions in Postman,” we will discuss how to parse an HTML response to extract a specific value.

Suppose you want to get the _csrf hidden field value from the response below for assertions or later use:

<form name="Login_Form" action="/login" method="POST">
        <input type="hidden" name="_csrf" value="a0e2d230-9d3e-4066-97ce-f1c3cdc37915" />
        <ul>
            <li>
                <label for="email">Email:</label>
                <input required type="email" id="email" name="email" />
            </li>
            <li>
                <label for="password">Password:</label>
                <input required type="password" id="password" name="password" />
            </li>
            <li>
                <input name="submit" type="submit" value="Login" />
            </li>
        </ul>
</form>

 

To pass or retrieve the value from the above response, we use cherrio Javascript Library:

// Parse HTML and get the CSRF token
responseHTML = cheerio(pm.response.text()); 
console.log(responseHTML.find('[name="_csrf"]').val());

 

Cheerio JS is a Javascript technology that is used in server-side web scraping. It is designed for non-browser use and implements a subset of the JQuery functionality.

Fixing the Error “ReferenceError: jsonData is not defined”💻

In this context, we will discuss fixing the error in postman.

In this part of “Assertions in Postman,” we will discuss how to fix the error “ReferenceError: jsonData is not defined.”

pm.test("Name should be icky", function () {
    var json_Data = pm.response.json();
    pm.expect(json_Data.name).to.eql('Micky');
});


pm.globals.set('name', jsonData.name);

 

While setting the global variable, you will receive the error ReferenceError: jsonData is not defined.

The reason for this error is that json_Data is only defined within the context of the anonymous function, and if you are attempting to set global variables outside of the function, json_Data is not defined. 

 

Methods to deal with this error are:

✔️ Define json_Data outside of the function.

    var jsonData = pm.response.json(); // defined outside callback


    pm.test("Name should be Micky", function () {
           pm.expect(json_Data.name).to.eql('Micky');
});


    pm.globals.set('name', json_Data.name);

 

✔️ Set the global variable inside the anonymous function.

    pm.test("Name should be Micky", function () {
    var json_Data = pm.response.json();
    pm.expect(json_Data.name).to.eql('Micky');
    pm.globals.set('name', json_Data.name); // <-- usage inside callback
});

Performing Partial Match Assertions in Postman🦿

In this part of “Assertions in Postman,” we will discuss how to perform partial match assertions in Postman.

Suppose you have a response:

{
    "uid": "12344",
    "firstName": "Michael",
    "lastName": "Clarke",
    "CollegeName": "MMM"
}

 

Suppose you are not interested in the dynamic value of uid, but you do want to assert firstName, lastName, and CollegeName. This can be achieved by partial matching of the response by using to.include expression. 

pm.test("Should include object", function () {
    var json_Data = pm.response.json();
    var expObject = {
        "firstName": "Michael",
        "lastName": "Clarke",
        "CollegeName": "MMM"
    }
    pm.expect(json_Data).to.include(expObject);


   // Optional Check to see if properties exist.
    pm.expect(json_Data).to.have.property('uid');
});

Frequently Asked Questions

What exactly is Postman's History tab?

All Postman requests appear in the sidebar under the History tab. It is very similar to browser history, which you can clear at any time. When you sign in to Postman, your history is synced across all of your devices.

What is the Payload in Postman?

The body of your request and response messages is the Payload of an API Module. It contains the data you send to the server when you make an API request. Payloads can be sent and received in various formats, such as JSON or XML.

What is the Postman Team workspace?

A Team workspace is a user-friendly environment in which multiple programmers can create APIs, provide feedback, and work on the same pools of requests. It also aids in synchronizing and collaborating all of the team's work in one location.

Conclusion

Congratulations on finishing the blog! We have discussed Assertions in Postman. We have looked at the various function to find an object inside an array and to compare the expected values with pre-defined objects.

If you want to read more blogs on Postman, please visit the following sites, which have been particularly selected for readers like you:

 

Please refer to our guided pathways on Code studio to learn more about DSACompetitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Please do upvote our blogs if you find them helpful and informative!

Happy learning!

Live masterclass