Using momentjs-timezone in Postman

External libraries can be executed in postman if CDN equivalent of these libraries are available.

You can get CDN in equivalent from websites like: https://cdnjs.com/

Now to use momentTZ in postman, copy the below code into script section and execute it once and then comment out:

This will store the CDN equivalent of momentTZ and momentJS libraries to environment variables.

pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data-2012-2022.min.js", (mtzErr, mtzRes) => {
pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js", (mjsErr, mjsRes) => {
//you have to initialize the momentjs to make momenttz work so we are storing both into a variable
pm.environment.set("momentjs", mjsRes.text());
pm.environment.set("momenttz", mtzRes.text());
})
})

Now you initiate the libraries in either of the two approaches:

First Approach:

Now comment out the above code you don’t need it anymore. Now you can use momenttz anywhere in your collection’s script sections as :

eval(pm.environment.get("momentjs"));
eval(pm.environment.get("momenttz"));
console.log(this.moment.utc().tz("America/Los_Angeles", "UTC").format())

in this approach, the libraries are initialized in the local scope, so if you want to use them again then you have to run the 3 lines of code again in other script sections whenever it’s used.

Second approach:

new Function triggers function in the global scope. so you just have to execute the first two lines only ones in your collection run and it will be available globally throughout:

Add in first scripts pre-request script:

(new Function(pm.environment.get("momentjs")))();
(new Function(pm.environment.get("momenttz")))();

Now you can use momentTZ library anywhere as :

console.log(moment.utc().tz("America/Los_Angeles", "UTC").format())

😀 😬 😁 😂 😃 😄 😅

Using external libraries in postman and there by using custom helper in Postman visualization!

Postman allows you to use CDN libraries in the script session,

so here we are using the CDN equivalent of the handlebar and then passing the compiled template to the postman visualizer

**We can initialize CDN in two ways :**

**First Approach:**

By initializing the CDN in global space using “new Function(cdn)()”

You can see the code below , but this will mess up global scope and can be used only once in the entire run*

// you can call any package with min build in postman
pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.js", (err, res) => {
pm.environment.set("res", res.text());
// intialize the min.js
new Function(pm.environment.get("res"))();
//create template soource
var source =
`{{#ifCond v1 v2}}
{{v1}} is equal to {{v2}}
{{else}}
{{v1}} is not equal to {{v2}}
{{/ifCond}}`;
//you can call methods in the cdn file using this keyword
//here we are registring handlebar
Handlebars.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
//compile the template
var template = Handlebars.compile(source);
//data to be passed 
// try v1 and v2 with same and different values and observe the output in visualization tab
var data = {
"v1": "test",
"v2": "test",
};
// passing the data to template
var result = template(data);
//visualizing it 
pm.visualizer.set(result)
})

**Second Approach:**

you can call any package with min build in postman

this initializes the functions in local scope so it won’t mess up the global space and cause issues

pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js", (err, res) => {
pm.environment.set("res", res.text());
// intialize the min.js
eval(pm.environment.get("res"));
//create template soource
var source =
`{{#ifCond v1 v2}}
{{v1}} is equal to {{v2}}
{{else}}
{{v1}} is not equal to {{v2}}
{{/ifCond}}`;
//you can call methods in the cdn file using this keyword
//here we are registring handlebar
this.Handlebars.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
//compile the template
var template = this.Handlebars.compile(source);
//data to be passed
// try v1 and v2 with same and different values and observe the output in visualization tab
var data = {
"v1": "test",
"v2": "test",
};
// passing the data to template
var result = template(data);
//visualizing it
pm.visualizer.set(result)
})

The hidden gem: Postman API and Documentation feature

its easier than you would expect to create a project collection…

Postman API Feature:

you can create collection , mock servers, documentation in click of a button by using postman API definition feature.

Lets see how to do it!!

  1. Get the API definition:

postman supports following API definitions:

so what is API definitions ?

API definitions, or API specifications or description formats (all are the same) defines your API . It is like a live documentation on what is available, what it can do , what is supported etc . In short a comprehensive live documentation that can help consumers understand what your API can do.

in summary:

  • Help internal folks understand the API and agree on its attributes
  • Help external folks understand the API and what it can do
  • Act as live documentation on what all endpoints are available, what methods are supported, what attributes are expected etc.

https://swagger.io/blog/api-development/why-you-should-create-an-api-definition/

How to get API definition ?

Most APIs visualizes the API definition using swagger UI. Which creates a user interactable representation of your API from the API definition file.

In mostcases the swagger UI will have link to the definition file or you can goto network tab and search for it

lets take https://petstore.swagger.io/ as example.

you can see the link to the definition file, it can be in yaml or json format. just click the link and copy the content.

you can see the version is swagger 2.0 meaning its open api v2

2. Create API in Postman

click API section and click the add icon or create new API link

Now give the below details:

name,version , open api v2.0 and json , and click create

Now paste the swagger definition we copied from pet store:

you can press ctrl+b to format the json properly after pasting:

click save

3. Now Generate collection from this swagger definition:

click generate collection:

click show advanced settings:

Give the below settings:

Now click Generate collection and goto your collections once the collection generation completes

4. Mock server , documentation and other things

so the generated collection will have documentation and examples as per the API definition file provided so you don’t have to generate documentation separately!!

And for mockserver, you can directly create a mock server from the collection as the examples are already available.

5. Publishing your documentation and adding animation to your documentation

Click the collection and click view documentation , and click publish

Now you have the documentation available in public domain for your customers.

https://swagger.io/blog/api-development/why-you-should-create-an-api-definition/

To unpublish follow the same procedure and click edit documentation and click unpublish

Adding animation:

you can add gif to your documentation , to do that use :

copy the absolute url of your gif:

provide it in documentation as :

![](https://i.pinimg.com/originals/f0/6a/9b/f06a9b257ba15f4761308ff84ab1ba2b.gif)

so when you click outside it will be resolved as

Postman trick and tips: How to run a specific iteration data from Newman

There is no inbuilt way to specify a specific iteration row to be executed using Newman, but can be done using Powershell or by using Newman as a library.

The approaches are as below

Powershell:

here we read the actual csv file in the current directory using import csv

Then considers only row 1..2 , if you just want 1 row you can change $a[1..2] to $[1]

$a= Import-Csv .\a.csv
$a[1..2] | Select-Object * | export-csv -Path .\temp.csv -NoTypeInformation
newman run .\test.postman_collection.json -d .\temp.csv

As library:

here we read and split the csv as we want using csv parser and then write it back to a temp file as csv using csv-stringify library.

First, install:

npm install csv
npm install fs
npm i fs-extra
npm install newman

Then use the below code

const newman = require('newman'); // require newman in your project
const stringify = require('csv-stringify')
const parse = require('csv-parse/lib/sync')
const fs = require("fs")
// call newman.run to pass `options` object and wait for callback
let data = fs.readFileSync('./a.csv',
{ encoding: 'utf8', flag: 'r' });
data = parse(data, {
columns: true,
    skip_empty_lines: true
})
console.log(data)
//index doesn't consider header so 0 is first data row
stringify(data.slice(0, 2), {
header: true
}, function (err, output) {

    fs.writeFileSync("temp.csv", output);

    newman.run({
collection: require('./test.postman_collection.json'),
reporters: 'cli',
iterationData: "./temp.csv"
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
});
})

Data driven testing per request without using data file

Create a environment variable called “csv” and copy the below content and paste it as value:

username,password,error_message,error_code
username1,password1,errormessage1,errorcode1
username1,password1,errormessage1,errorcode1

Now in pre-request add :

//we use variables as it will get destroyed after the run . So if index returns null then it means it’s the first iteration
if (!pm.variables.get("index")) {
    const parse = require('csv-parse/lib/sync')
//Environmental variable where we copy-pasted the csv content
const input = pm.environment.get("csv");
const records = parse(input, {
columns: true,
skip_empty_lines: true
})
    pm.variables.set("index", 0)
pm.variables.set("records", records)
}
records = pm.variables.get("records")
index = pm.variables.get("index")
//we are setting variable 
if (index !== records.length) {
for (let i of Object.entries(records[index])) {
pm.variables.set(i[0], i[1])
}
pm.variables.set("index", ++index)
pm.variables.get("index")===records.length?null:postman.setNextRequest(pm.info.requestName)
}

Now you can run data driven for that one particular request:

Note that here we used pm.variables. this is because it creates local variable that get destroyed after the collection run completes .

So for each run , first value will be null and then will be set to 0

Eg collection:

https://www.postman.com/collections/eb144d613b7becb22482

use the same data as environment variable content , now run the collection using collection runner or newman.

You can import this collection by clicking file >import >and then choosing links

Output:

How to run postman requests using Tags

Get all requests in the collection:

you can also get information about all the requests in a collection by using :

https://api.getpostman.com/collections/{{collection_UUID}}

to get uuid and api key goto :

https://app.getpostman.com

Now for generating api key >

goto account settings > api key and generate api key.

to get collection uuid goto specific workspace and collection and copy the uuid part from url:

Note: you can also get UUID by clicking collection and clicking info panel on the right side

Now in your collection

Rename all requests as:

get user details [Regression][Smoke][Somethingelse]
get account details [Regression]

Then Create a new request called initial request and keep it as the first request in your collection:

url: https://api.getpostman.com/collections/8xxxxtheuuidyoucopied

authorization: apikey-header : key: X-Api-Key and value: yourapikey

test-script :

pm.environment.unset("requestToRun")
reqeustlist = pm.response.json().collection.item.map((a) => a.name)
requestToRun = reqeustlist.filter((a) => a.includes(pm.environment.get("tag")))
let val = requestToRun.pop()
pm.environment.set("requestToRun", requestToRun)
val ? postman.setNextRequest(val) : postman.setNextRequest(null)

Now set the envirnoment variable as what you want to look for eg: run script that contains text “Regression” then set pm.environment.set("tag","Regression")

Now in your collection-pre-request add:

if (pm.info.requestName !== "initial request") {
let requestToRun = pm.environment.get("requestToRun")
let val = requestToRun.pop()
pm.environment.set("requestToRun", requestToRun)
val ? postman.setNextRequest(val) : postman.setNextRequest(null)
}

Output:

Ran only reqeusts that has “Copy” in its name

Example collection:

https://www.getpostman.com/collections/73e771fe61f7781f8598 , you can click ctrl+o and choose link to import this collection

Note: In newman you can pass the environment variable as “ — env-var tag=Regression”

Passing request body multiform-data file source as variable in postman.

Issue:

In postman if we check the UI, we notice that there is no way to define file path as variable.

This looks like a limitation when we need to run file from different systems

Solution:

The solution is to hack the collection.json file. Open the json and edit the formdata src and replace it with a variable, let say fire_path so : {{fire_path}}

Now in Postman:

in pre request you can below code to set the path

pm.environment.set("file_path","C:/Users/guest/Desktop/1.png")

You can also save it as environment variable directly or pass through cmd using — env-var when using newman.

Note:

set access file from outside working directory as true (settings from top right corner)

Reading CSV file in Postman

CSV:

a,b,c
1,2,3
1,5,6
2,4,6

CSV parse output:

Approach 1: store CSV content as an environmental variable

Just copy the CSV file content and create an environmental variable and paste the content inside it

Then in test or pre-requisite step:

console.log(pm.environment.get("data"))
const parse = require('csv-parse/lib/sync')
//Environmental variable where we copy-pasted the csv content
const input =pm.environment.get("data");
const records = parse(input, {
 columns: true,
 skip_empty_lines: true
})

console.log(records)

Approach 2: Passing the CSV content to an environmental variable through Newman (Powershell):

Then in test or pre-requisite step use the same code as above:

> $a= Get-Content -raw .\1.csv
> newman run .\test.postman_collection.json -e .\test.postman_environment.json -k -r "cli,htmlextra" --env-var data=$a

Writing first test script and chaining outputs between scripts.

Till now , we have executed requests but have not written any testscripts. Meaning, there were no validation steps to verify whether the request passed or failed.

Now let us see who to do this. Let us write our first test script.!!!! 🙂

Automation tests with Postman:

There are two parts were we can write the scripts for our tests.

  1. Pre-request script
  2. Tests

Here pre-request script act as the test setup script, meaning, it will get executed before the tests. So if you have any pre-requisite like creating user variable or validating whether a user variable value exists, you can do it here.

Tests are were we write the actual tests, it get executed after we get the response.

Writing first Test script:

The syntax of writing tests are as follows:

pm.test("Test_case_description", function () {
    <Validation steps!> ( The steps are available as test snippet you just need to select it )
});

Note:

We can write tests at both the places ( Pre-request or Tests) but as tests are meant to be validating the user action, it should be written at the ‘Test’ tab so that it will be executed only after the action is completed.

Postman pm.test function expects different exceptions and passes or fails the test accordingly. You can try running just the below command without the ‘pm.test’ enclosed and observe that on sending the request an assertion is thrown.

(The below script is to validate whether the text ‘test’ as sub-string ‘b’ in it.)

pm.expect('test').to.have.string('b');

Now enclose the command in pm.test as below on both pre-request and Tests tab:

pm.test("Check string", function () {
   pm.expect('test').to.have.string('b');
});

Now send the request and you will observe that two tests were executed.

Run the same using collection runner (Make sure to click save before running runner):

Chaining the response together:

Get the data from response body and store it in an environmental variable:

pm.test("Get email", function () {
    var jsonData = pm.response.json();
    var email= jsonData.data[2].email;
    pm.environment.set("email", email);
});

Use this environmental variable in next test.

{
    "email": "{{email}}",
    "password": "cityslicka"
}

Till now , we have executed requests but have not written any testscripts. Meaning, there were no validation steps to verify whether the request passed or failed.

Now let us see who to do this. Let us write our first test script.!!!! 🙂

Automation tests with Postman:

There are two parts were we can write the scripts for our tests.

  1. Pre-request script
  2. Tests

Here pre-request script act as the test setup script, meaning, it will get executed before the tests. So if you have any pre-requisite like creating user variable or validating whether a user variable value exists, you can do it here.

Tests are were we write the actual tests, it get executed after we get the response.

Writing first Test script:

The syntax of writing tests are as follows:

pm.test("Test_case_description", function () {
    <Validation steps!> ( The steps are available as test snippet you just need to select it )
});

Note:

We can write tests at both the places ( Pre-request or Tests) but as tests are meant to be validating the user action, it should be written at the ‘Test’ tab so that it will be executed only after the action is completed.

Postman pm.test function expects different exceptions and passes or fails the test accordingly. You can try running just the below command without the ‘pm.test’ enclosed and observe that on sending the request an assertion is thrown.

(The below script is to validate whether the text ‘test’ as sub-string ‘b’ in it.)

pm.expect('test').to.have.string('b');

Now enclose the command in pm.test as below on both pre-request and Tests tab:

pm.test("Check string", function () {
   pm.expect('test').to.have.string('b');
});

Now send the request and you will observe that two tests were executed.

Run the same using collection runner (Make sure to click save before running runner):

Chaining the response together:

Get the data from response body and store it in an environmental variable:

pm.test("Get email", function () {
    var jsonData = pm.response.json();
    var email= jsonData.data[2].email;
    pm.environment.set("email", email);
});

Use this environmental variable in next test.

{
    "email": "{{email}}",
    "password": "cityslicka"
}

First steps with Postman…

Ok lets start working with postman!!!!

Install Postman:

https://www.getpostman.com/downloads/

Open Postman:

Create Workspace:

Work space allows you to organize your work. It creates a separate working space where you group all your works including tests,collections, environments etc ( will learn as you read on).

Click My work space and select create New workspace

Note: Workspace could be personal, private or Team. Personal will be available only to you, shared will be available to everyone else with the invitation link and private is enterprise version and allows team members who were invited by you to be part of the workspace.

Team workspace and My Workspace are default workspace and cannot be deleted. To delete other workspaces, goto All workspace (will be opening in browser) and select delete by click ing the meatball menu.

Create Collection:

Collection allows to group your requests together in a logical order. It could be seen as the test suite level and we will have individual requests as the tests.

You also create folder inside postman to group your tests more efficiently for example :

Collection name be “Android FaceAPP”

And Folder name be “Test_LoginFeature”

Click collections>New collections for creating new collection

Click meatball menu> Add folder, to create folder

Create your first request:

Create a new request by clicking New or by using meatball menu corresponding to the desired collection and folder.

Add the request details:

And click save ( don’t forget to click save else the request won’t be saved onto collection- folder hierarchy)

Then click send.

Note: Use https://reqres.in/ to get API for practice.

Running Collection Runner:

So you can create as many requests as you want, now imagine you have to execute all this requests in order.

You can do this by using collection runner.

Click on the collection you want to run and click play icon, and click run.

The below window opens up and now click run <collectinname>

This will execute all requests in the collection and shows the result.

Note: Here test results shows ‘0’ passed and failed as there were no validation scripts added. We will learn it in next sections.

Running collections from command line:

For running collections through command line we need to use newman tool

To install newman you need npm (npm is installed as part of nodejs installation , Install here) and then use the below command:

npm install -g newman

Note: make sure that nodejs modules are in path or else add it to path , to ensure newman command is recognized from cmd.

Now to run the tests from command line create a share link or export collection as json

Through Share link:

Click the collection’s meatball menu and click share and navigate to ‘Get link’ and generate a link.

copy the link address and run the command:

newman run <link_address>

Through json:

Click the meatball menu and select export, this creats a json file for the collection

now run

newman run <full_path>/TestApp.postman_collection.json

Note: This could be used for running postman in CI/CD pipeline

HTML Reporting

We have seen how to run postman through command line using newman ( just npm install newman and use command ‘newman run <collection>.json’ or url)

To get html reporet install newman-reporter-htmlextra

npm install -g newman-reporter-htmlextra

Now run the scripts as

newman run <collection_file>.json -r htmlextra