JavaScript in POSTMAN

JavaScript is a programming language that is developed mainly for website technology. JavaScript is used to make webpages more dynamic and attractive. It is also used for validating different data which is fed into the website and also different functions, scripts and logic can be implemented on the webpage using Javascript.

Like all other programming languages, JavaScript also has its own syntaxes and functions which can be used as we use in any other types of programming languages. It helps the developer to work with different JavaScript-based frameworks such as nodejs, jQuery, etc.

Mainly JavaScript is less used as a standalone programming language and is mostly used after integrating with Front end elements like HTML, XML, etc.

In POSTMAN, it is possible to write different pre-test scripts and test-scripts which gets executed after the request is sent to the server and after the response is received from the server. Therefore, learning JavaScript can be helpful to customize the test scripts in POSTMAN and also create a user-defined function to filter the response or to find, search or retrieve required data from the response.

To get started with JavaScript in POSTMAN, it is very important to study the basics of JavaScript, so we shall learn in brief the basics of JavaScript.

Below are the basics we need to know before getting started with POSTMAN :

  • Introduction to JavaScript.
  • JavaScript Data-types
  • JavaScript Variables.
  • Conditional.
  • Functions
  • Data Structures(objects, arrays)
  • Iterations & Loops.
  • Modern JavaScript.

JavaScript Variables

A JavaScript variable is an identifier that specifies the storage location for a certain value. There are two different types of variables in JavaScript. They are Local Variable and Global Variable.

Below are the Rules for declaring a variable in JavaScript:

  • The variable name can start with letters(alphabet), underscore(_) or a dollar sign($).
  • The variable name can have digits in the middle or at the end, but not at the beginning. (Ex: my01variable or myvariable01.)
  • JavaScript variables are case-sensitive, that is x and X are different
var myvariable = 100;
var _avalue ="chercher"

J

avaScript Local Variable

A local variable is that variable whose scope lies only inside the function, it is declared. It means, that the local variable is only accessible within its function, and not outside the function.

For example:

<script>
function testfunction(){
var myvariable= 100;
}
</script>

In the above example, the variable myvariable is a local variable and only can be accessed within the function testfunction().

JavaScript Global Variable

A global variable in JavaScript is the one that is not declared within any function but can be used and accessed by any functions in the program. Generally speaking, a variable in JavaScript with a window object or declared outside function is called a global variable.

<script>
var mydata= 50;
function func01(){
document.writeln(mydata);
}
function func02(){
document.writeln(mydata);
}
func01();
func02();
</script>

As shown in the above program example, the variable mydata is declared and initialized globally, which is not within any function. Therefore, the variable can be accessed by both the functions- func01() and func02().

However, the value of the global variable can be used within any function, but the value of the global variable which initialized one, cannot be changed throughout the execution of the program.

JavaScript Data Types

Like any other programming, language JavaScript provides different data types to hold different values. The data types can be broadly classified as:

  • Primitive Data Type
  • Non-primitive Data Type
In JavaScript, data types for different types of values should not be specified, as the type of data is taken care of by the JavaScript Engine.

Just var should be used to indicate that you are declaring a variable.

For example, in the case of,

var number= 85; or var name = "Riya" , the JavaScript Engine senses it dynamically that the variable number is an integer type variable and name is a string type variable.

Primitive Data Type

The following are the primitive data types in JavaScript:

  • String : It represents a sequence of characters. Such as: chercher.tech.
  • Number : It represents numeric values such as 100, 67, etc.
  • Boolean : It represents a boolean value which means it can be either true or false.
  • Undefined : It defines an undefined value.
  • Null : It represents a null value.
JavaScript Non-primitive Data Type
  • Object : Objects are created in JavaScript so that, the instances of it can be accessed or manipulated.
  • Array : Array is a data type that can hold multiple values of the same data types.
  • RegExp : It represents a regular expression.

JavaScript Operators

JavaScript operators are nothing but arithmetic operators and logical operators which are used to perform different logical and arithmetic operations.

The Operators are :

  • Arithmetic Operators : Arithmetic Operators are used to performing arithmetic operations such as addition, subtraction, multiplication, and division between two operands.
  • Comparison Operators : Comparison operators are used to comparing the values of any two operators.
  • Bitwise Operators: Bitwise Operators are used to performing bitwise operations on operands.
  • Logical Operators : Logical Operator is used to performing a logical operation such as AND or OR.
  • Assignment Operators : Assignment Operators are used to assigning a value to a variable or to assign the value of a variable to another variable.
  • Special Operators: There are some special operators in JavaScript which are there to carry out special tasks. Such as (?:) is used for returning value based on a condition, or comma operator(,).

Conditional Statement

A conditional statement is used to check certain conditions. It can be a comparative or logical condition. If a certain condition is fulfilled then a block of statement can be executed. Generally, a conditional statement is denoted with if or else.

In JavaScript, there are three different types of a conditional statement. They are:

  • IF statement
  • IF else statement
  • IF-else if statement.
IF statement

The if statement is used to check a certain condition, if a condition is true then a certain statement/block of statement gets executed.

Syntax :

if (conditional_expression) {
 //some code
}

For example, consider the below script :

< script >
 var myvalue = 25;
if (myvalue > 20)
 document.writeln("25 is greater than 20"); 
</script>

Program Example :

postman-javascript-if-output

If-Else Statement

This conditional statement is used to execute a code/block of code when a condition is found to be true or false.

Syntax :

if (expression) {
 //some code
} else {
 //some code
}

Program Example :

< script >
 var myvalue = 200;
if (myvalue > 100) {
 document.writeln("100 is greater than 200 ");
} else
 document.writeln("This part will not execute, as the condition is true"); 
</script>

Program Example :

postman-javascript-if-else-output

If...else if

Using the else-if statement, several conditions can be checked individually.

Syntax :

if (conditional_expression1) {
 // some code
} else if (conditional_expression2) {
 //some code
} else if (conditional_expression3) {
 //some code
}
.................
................
else {
 //some code
}

Program Example :

< script >
 var myvalue = 200;
if (myvalue > 100) {
 document.writeln("100 is greater than 200 ");
} else if (myvalue == 200) {
 document.writeln("both the values are equal");
} else
 document.writeln("This part will not execute, as the condition is true"); <
/script>

Program Output :

postman-javascript-if-else-if-output

Switch

A switch statement is used when there are multiple blocks of code and based on the optional selection a particular block of statement can be executed. A switch works similar to the if...else if, but it is more convenient as numbers, characters, etc can also be used to indicate the option.

Syntax :

switch (variable) {
 case value1:
  //some code
  break;
 case value2:
  //some code
  break;
  ..........
  ............
 case value_n
 //some code
 break;
 default:
  //some code if no options are matched
}

Program Example :

< script >
 var option = 1;
var output;
switch (option) {
 case 1:
  output = 100;
  break;
 case 2:
  output = 200;
  break;
 case 3:
  output = 3;
  break;
 default:
  document.writeln("None of the options are matched");
}
document.write(output); 
</script>

Program Output :

postman-javascript-switch-output

As shown in the program output, the first option in case 1 got executed, as we initialized the variable option to 1.

JavaScript Loops

Loop is a way in JavaScript programming to execute a statement/block of statements in a repetitive manner. Loop is important when a similar task has to be done again and again.

There are three different kinds of loops :

  • for loop
  • while loop
  • do-while loop
  • for-in loop
JavaScript for loop

The for loop in JavaScript is used when the code inside the loop has to be executed for a finite number of times. This loop is used when the number of iterations is known.

Syntax

for (loop_variable_initialization; loop_condition; counter) {
 //some code
}

Program Example :

< script >
 for (loop_variable = 1; loop_variable <= 5; loop_variable++) {
  document.write(loop_variable + "<br/>")
 } 
< /script>

Program Output :

postman-javascript-for-loop

JavaScript while loop

The JavaScript while loop is used when the code has to be iterated for an infinite number of times till a condition is reached. While loop is used when the number of iteration is not known, and the loop condition depends on the execution of the program.

Syntax

while (condition) {
 //some code
}

Program Example :

< script >
 var loop_variable = 1;
while (loop_variable <= 5) {
 document.write(loop_variable);
 loop_variable++;
} 
</script>

JavaScript do-while loop

The do-while loop is the same as that of the while loop, except the fact that in the do-while loop the block of code will execute the first time without any condition being checked and then the condition is checked and the loop is iterated till the loop condition is reached.

Syntax :

do {
 //some code
}
while (condition)

Program Example :

< script >
 var loop_variable = 1;
do {
 document.write(loop_variable);
 loop_variable++;
}
while (loop_variable < 5); <
/script>

Program Output:

1 2 3 4

JavaScript Functions

A function is JavaScript is nothing but a keyword that represents a block of the statement. Using function we can use reuse or execute the block of statement just by calling it wherever we want.

There are some advantages of using a function:

  • Code Simplification: Using function can make the code look simpler and clean.
  • Less Coding: Use of function decrease the need for writing the same code again and again for similar tasks.

Syntax for JavaScript Function

function functionName(arg1, arg2,...argN){
//some code
}

Program Example :

< script >
 function myfunction() {
  alert("Hello your javascript function is called");
 } 
< /script>
< input type = "button" onclick = "myfunction()" value = "Execute" / >

Thus a JavaScript function can be directly called by writing the script inside a webpage. Also, the JavaScript function can be used as a stand-alone programming language. The JavaScript function can also be used in the following way, without using any HTML or XML elements:

< script >
 function func01() {
  document.writeln("This is the output from first function");
 }
function func02() {
 document.writeln("This is the output from the second function");
}
func01();
func02();
 </script>

Arrays In JavaScript

An array in JavaScript is a data structure that can hold multiple values of different data types. The array in JavaScript is different from arrays of other programming languages in the sense that,

Syntax for array declaration :

var array_name = ["element1" , "element2", "element3"..]

Program Example :

var name = ["Rahul", 1, 'a'];

To access the array simply, you can use the array name with the index. Such as to retrieve the first data in the array, we shall write name[0]. As, you that the array addressing starts from index 0, so all the elements stored in the array can be accessed using the array index starting from 0.

Therefore the name[0] will return me data - Rahul.

An easier and convenient way to create arrays and objects is to write the javascript into your web browser console. You can use any web browser, but Mozilla Firefox or Google Chrome is a better option, for their reliability in inspecting elements.

I shall be using Google Chrome. To start with Chrome's console:

  • Right-click after opening an empty tab in the Chrome Browser and select inspect element.
  • Navigate to the console option and start writing your script.

postman-chrome-inspect-element

Then,

postman-chrome-console

In the console tab, you will get an editor to edit your script and see the output.

postman-chrome-console-create-array

Not only values but you can also have functions as well as other arrays that can also be an element of an array in javascript.

Object in JavaScript

Object in JavaScript is a data structure that has state and behavior. For example, a table, a car, etc. As JavaScript is an object-based language, therefore everything in JavaScript is an object. It may be noted that Javascript is a template-based language and not a class-based language.

Object In JavaScript can be created in different ways:

  • Using Object Literal.
  • By creating an object instance.
  • By using object constructor.
Using Object Literal

Syntax :

object_name = {property1:value1, property2:value2....property_n:value_n}

Program Example :

< script >
 student = {
  roll: 10,
  name: "Rahul Kumar",
  grade: 'A'
 };
document.write(student.roll + " " + student.name + " " + student.grade); 
</script>

In the above Program, the object name is student. And it has three attributes inside it: roll, name, and grade, with an integer value 10, string Rahul Kumar and a character A respectively.

Program Output :

10 Rahul Kumar A
Creating Object Instance

Object instance can be created along with creating the object itself. A keyword called new is used to create an object instance before the object function Object().

Suppose we want to create an object instance called: employee. So, we shall write like:

var employee = new Object();

Syntax :

var object_name = new Object();

Program Example :

< script >
var employee = new Object();
employee.id = 10;
employee.name = "Rahul Kumar";
employee.salary = "30000";
document.write(employee.id + " " + employee.name + " " + employee.salary); 
</script>

In the Above program, you can see that the object name is employee and is directly created with the keyword new along with the function Object(). But the property along with the data is set with a dot(.) operator, like- employee.id= 10. Here, we are declaring the property called id as well as assigning it with a value 10.

Program Output :

10 Rahul Kumar 30000
Creating Object by using Object Constructor

To create an object using Constructor, we have to declare a function with the object name we want to create. This function will have arguments that represent different properties of the object. The keyword this will be used to refer to the current object.

Program Example :

< script >
 function student(roll, name, grade) {
  this.roll = roll;
  this.name = name;
  this.grade = grade;
 }
s1 = new student(5, "Riya", 'A');
document.write(s1.roll + " " + s1.name + " " + s1.grade);
</script>

In the above program, we have declared a function called student using the keyword function, which is nothing but a constructor, as all the arguments inside the function are initialized inside itself using the this keyword.

Then outside the scope of the constructor function, we have simply created an instance of the object just by using the keyword new before the user-defined object- student.

Program Output :

5 Riya A

JSON PATH

JSON path is nothing but the path through which you can access a particular data in a JSON document. It is very much important to understand the JSON path of all data, as to refer any data in a JSON document, the path of the data has to be used.

Consider the following response :

{
    "page": 2,
    "per_page": 6,
    "total": 12,
    "total_pages": 2,
    "data": [
        {
            "id": 7,
            "email": "[email protected]",
            "first_name": "Michael",
            "last_name": "Lawson",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
        },
        {
            "id": 8,
            "email": "[email protected]",
            "first_name": "Lindsay",
            "last_name": "Ferguson",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"
        },
        {
            "id": 9,
            "email": "[email protected]",
            "first_name": "Tobias",
            "last_name": "Funke",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg"
        },
        {
            "id": 10,
            "email": "[email protected]",
            "first_name": "Byron",
            "last_name": "Fields",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg"
        },
        {
            "id": 11,
            "email": "[email protected]",
            "first_name": "George",
            "last_name": "Edwards",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg"
        },
        {
            "id": 12,
            "email": "[email protected]",
            "first_name": "Rachel",
            "last_name": "Howell",
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg"
        }
    ]
}

You can see the response starts with different object properties such as page, per_page, total, total_pages, and data. Now, see that inside the attribute data, an array starts which also has an object inside it.

postman-json-path-demo

So, within the attribute data, you can see different records with fields like- id, email, first_name, and last_name. Now, to get access to the id, we must understand the JSON path. The whole response is referred to as JsonData. The data[0] indicates the first attribute inside the data, and then we can access the last_name.

Therefore, to access the last_name corresponding to the id =7(which belongs to the first record), we have to write the path as:

 jsonData.data[0].last_name

The above code means, access the last_name of the record data[0] of the JSON response jsonData.

JavaScript in POSTMAN

So far we have seen the basics of javascript so that it becomes easier to write tests in POSTMAN and the code snippets available in POSTMAN can be easily customized or written from scratch. Now we shall see the practical implementation of JavaScript in writing scripts.

Comparing Values

Check whether the value of any attribute is matched with any other attribute in the response. For example, in our response, we have seen that for all the individual records we have a unique id and first_name, last_name, etc.

Let us consider our first example, last_name as Lawson. Our task is to check whether the last_name is present in the record whose id is equal to 7.

postman-json-path-id

Now, edit the following code into the Tests Tab of POSTMAN.

pm.test("Check whether any last name Lawson is present is id 7", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.data[0].last_name).to.eql("Lawson");
});

Looks like,

postman-json-compare-data

Now, hit the Send Button and send the request. After the response is received, just to go to the Result tab and see the result. It the last_name is matched in the record of id 7, then it should return a PASS.

postman-response-result

What if the last_name Lawson did not belong to id 7?

Let us check for a different name, and it should give a FAIL result.

In API testing, it is equally necessary to check for the FAIL test case also. Getting a valid output does not(never) means that the testing is correct. It can create a dangerous error if, for negative test-condition, it produces a valid output or a PASS.

Now, just insert a different last_name and see what happens. So just edit the code, and check for last-name: Rahul for the same id =7.

pm.test("Check whether any last name Lawson is present is id 7", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.data[0].last_name).to.eql("Rahul");
});

Now after sending the request and receiving the response, check the Result tab:

postman-failed-test

Comparing values in different attribute

We can also compare the value of different attributes in the POSTMAN response. For that, we have to refer to the JSON path for the two different data.

For, example, we want to compare whether the first_name in id = 7 is the same as the first_name of id =8 also. Now, we have to get the JSON path for both the first_name(s).

first_name path for id = 7 is: jsonData.data[0].first_name

first_name path for id = 8 is: jsonData.data[1].first_name

pm.test("Check whether first name of id 7 and id 8 are same", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.data[0].first_name).to.eql("jsonData.data[1].first_name");
});

Now, send the request and see the Test Result.

postman-failed-test-result

if-else condition in POSTMAN script

If-else statement in the script in POSTMAN is a conditional statement to execute some code when a certain condition is reached. But such output which is customized is displayed in the POSTMAN console.

To display the value of a variable, string or any data in the POSTMAN console, console.log() is used.

Let us check with the help of if-statement whether the last_name : Lawson is present in the response body whose id is 7. It is the same as that of the previous code, just we shall add a if-else block to print the output in the console.

Edit the following code into the Tests tab of the request.

pm.test("Check whether last_name in id 7 is Lawson", function() {
 var jsonData = pm.response.json();
 var myvar = jsonData.data[0].last_name;
 if (myvar == "Lawso") {
  console.log("Yes, The name is present in id 7");
 } else
  console.log("The name is not present in id 7");
});

Now, before sending the request, open the POSTMAN console and clear the console.

To open the console: Go to the view tab in the POSTMAN toolbar and select the console window.

postman-if-else-console

In the above image, you can see that in the console the text for the else-part has executed. As in the if-condition, we have provided a wrong name that does not exist in the record of id =7.

Loop in POSTMAN Script

For loop in Script

We can also iterate a part of a script in POSTMAN using loops. In this example, we shall use for-loop to check whether the name is present in other records as well. As we are uniquely identifying the records with the help of id, therefore we shall iterate our if condition by using the for a loop.

Edit the following code into the editor :

pm.test("Check whether first name of id 7 and id 8 are same", function() {
 var jsonData = pm.response.json();
 for (var index = 0; index <= 4; index++) {
  var myvar = jsonData.data[index].last_name;
  if (myvar == "Lawson") {
   console.log("Yes");
  } else
    console.log("No not matching");
 }
});

In the above script, the variable called jsonData, is assigned the JSON response. And then the for loop is used to check whether the name "Lawson" is present in any of the records. Now, the record is identified by data[index]. The loop starts with the variable index 0 and goes up 3, as per the condition: (forvar index = 0; index <=4 ; index++).

Now, Go to the POSTMAN console, clear the console, and then send the request to see the output after the response is received.

postman-for-loop-console

While Loop in Script

While loop is used when a part of the script or any condition has to be checked again and again till a condition is reached. In this example, we shall search for a name in the response and keep on searching until the name is found.

Edit the following code into the Tests tab in POSTMAN.

pm.test("Check whether first name of id 7 and id 8 are same", function () {
    var jsonData = pm.response.json();
    var index = 0;
    while(myvar!="Edwards")
    {
         var myvar = jsonData.data[index].last_name;
        console.log("The name is not found");
    index++;
    }
    index = index+1;
    console.log("The name is found after "+index+" iterations");
});

In the above program, you can see that we have written a while condition as: while(myvar!="Edwards"). Because we know that, that some last_name Edwards is present in the response, but we don't know, in which record it is present.

Therefore, we have used a while loop to iterate the search and get out of the loop only when the last_name is found.

Outside the scope of the while loop, we have written index = index + 1. This is done because the array index starts from 0 and so the number of iterations it covers will always be displayed less by 1. So, to output the actual number of iterations, we increase it by 1.(for understanding purpose.)

Go to the Console and clear the console and then hit the send button to sent the request.

Console Output :

postman-while-console

In the above console output, it is very much clear that the loop iterated 6 times. And in the 6th iteration, the name is found.

Switch in POSTMAN Scripts

Switches are used when a code/block of code has to be executed based on a certain option that is selected. In POSTMAN script we can execute code or print text in the console based on the data values inside the response.

Edit the following code into the Tests Tab:

pm.test("Check whether first name of id 7 and id 8 are same", function () {
    var jsonData = pm.response.json();
    var myvar = jsonData.data[0].last_name;
     switch(myvar)
     {
        case "Lawson":
        console.log("Found Lawson");
     break;
         case "Rahul":
         console.log("Found Rahul")
    break;
     }
 });

In the above program, we have used switch() have used the variable myvar inside it. The variable myvar contains the last_name of data[0]. And we have seen earlier that the last_name inside the data[0] is "Lawson".

So, we implemented two cases:

  • case: "Lawson"
  • case: : "Rahul"

Now, go to the console and clear the console. Then send the request and wait for the response. Once the response is received, check the console of POSTMAN.

postman-switch-console

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Subscribe to See Videos

Subscribe to my Youtube channel for new videos : Subscribe Now