Search Sreeni's Insights

Filter by content type
crafting July 19, 2018 6 min read

How to write Postman Scripts? - Part 1

The basics of Postman scripts: when pre-request and test scripts run, the execution order, the Postman Sandbox and how to write a first script.

Share:

How to write Postman Scripts? - Part 1

Introduction

In every regression phase, the QA team used to spend lots of time on repeated tests, and these tests are the most time-consuming tasks. Automated tests are the solution for this issue, and it is also applicable for API testing. For API automation tests, we have lots of tools in the market and Postman is one of the right choices since it provides the complete workflow to develop, test, document and monitor an API. Postman provides the test script feature through which we can write our automated tests for an API.

This is a two-part series. In this article, we are going to see the basics of Postman scripts: what a Postman script is, when it executes and how to write your first script. In the next article, we are going to write automated API tests with real world examples.

TL;DR Summary

  • Postman script is a JavaScript-based script which runs before a request is sent (Pre-request script) or after the response is received (Tests script).
  • We can write scripts at the collection, folder and request level, and Postman executes them in a fixed order.
  • All scripts run inside the Postman Sandbox, which exposes a global pm object.
  • Use pm.test() to write a test case and console.log() with the Postman Console to see what is going on.
  • Postman scripts are easy to learn, but they must be treated as production code; otherwise they will become a maintenance overhead.

Benefits and Drawbacks

Before we start, let us see some benefits and drawbacks of Postman automation tests.

Benefits

  1. Not much learning curve required except a basic understanding of Postman and JavaScript.
  2. Creating an API automation test is much simpler than UI automation tests, so you can create automation tests quickly and easily.
  3. Can save QA time by automating all possible repeated tests and the smoke test for your critical business data API.
  4. Can save Developer time to identify the impacted area whenever there is a change in an API function, and in turn it can reduce the roundtrip between Developer and QA.

Drawbacks

  1. Initially, we need to put some extra effort to build the required scripts, but it is worth to invest.
  2. Need to keep the scripts up to date on every change in the API. We must treat these scripts as equal to production code. Most of the time we will not give importance to test scripts.
  3. It will add the maintenance overhead if we do not write useful tests. So, think twice before writing an automation script.
  4. Postman does not support code reusability since all test scripts are bound to a collection instead of a separate file, but there is a way to reuse the code.
  5. All tests will run synchronously in the collection runner, so it is not suitable for performance or stress testing. You can use Newman for this purpose.

Pre-requisites

To write a Postman script, you should have the following knowledge,

  • Basics of HTTP protocol
  • Basics of Postman
  • Basics of JavaScript

Postman desktop app is required to follow along with these articles. Chrome add-on is not recommended. If you have not already installed the desktop app, you can download it from https://getpostman.com.

What is Postman Script?

Postman script is a JavaScript-based test script which is used to send the dynamic data with an API request and validate the API response.

Postman allows us to write scripts in two different scopes or events of a request,

  • Pre-request script - It will execute before sending the request to the server, and it helps us to write a script to modify or update the request before sending it.
  • Tests script - It will execute right after the response is received from the server. Here, we can write scripts to validate the response based on our test case. Most of the time it will be used for testing purpose.

Postman provides two different tabs to write pre-request and test scripts. It is packed with a bundle of script snippets, and you can find them on the right side of the script box.

Pre-request Script and Tests tabs with the snippets panel
Pre-request Script and Tests tabs with the snippets panel

Script Execution Order

Postman has the following artifacts hierarchy, and at each level, we can write scripts.

  • Collection
    • Folder 1
      • Request 1
      • …
      • Request N
    • Folder N
    • Request 1
    • …
    • Request N

You may raise a question related to the order of script execution when you write a script for the different levels. Very good question! The following diagram answers your question.

Postman script execution order across collection, folder and request levels
Postman script execution order across collection, folder and request levels

Execution order console logs:

Postman Console showing the script execution order
Postman Console showing the script execution order

Quick Start

Let us write a Hello World Postman script. Follow the following steps to write it.

Steps:

  1. Open the Postman.

  2. Create a new request.

  3. Enter https://httpbin.org/get into the URL field.

  4. Open the Pre-request Script tab and write the following script,

    console.log("Hello World! - Request Level - Pre-request Script");
    Hello World script in the Pre-request Script tab
    Hello World script in the Pre-request Script tab
  5. Open the Tests script tab and write the following script,

    console.log("Hello World! - Request Level - Tests Script");
    Hello World script in the Tests tab
    Hello World script in the Tests tab
  6. Open the Postman console from View -> Show Postman Console.

  7. Click on the Send button.

  8. Before it sends the request to the server, you can see the pre-request log entry in the console.

  9. Once the response is returned, you can see the test script log entry.

    Postman Console with the pre-request and tests log entries
    Postman Console with the pre-request and tests log entries

As per the above snapshot, the Postman console displays our custom logs whatever we added in the pre-request and tests script tabs.

Postman Sandbox

Postman uses a sandbox to execute the script, and this is the runtime environment for all Postman test scripts. It is pre-loaded with some libraries and these can be used in Postman scripts. For more information, refer to this link.

Postman exposes a global object called “pm” which provides all methods and properties that are required for writing a tests script.

Few important methods and properties of the pm object as follows,

  • pm.test(<test case name>, callback)
  • pm.info
  • pm.globals
  • pm.environment
  • pm.variables
  • pm.request
  • pm.response
  • pm.iterationData

Test Case

Postman provides two ways to write test cases. One is using pm.test("<test case name here>", test function) and another method is to use tests["<test case name>"] = assert statement.

pm.test("api should return 200 status code", function () {
    pm.response.to.be.ok;
});

tests["api should return 200 status code"] = responseCode.code === 200;

For more information, refer to this link.

Conclusion

In this article, we have looked at what a Postman script is, the benefits and drawbacks of Postman automation tests, the script execution order, the Postman Sandbox and how to write a Hello World script. I really appreciate that you took the time to read this article.

In the next article, I will walk you through how to write an API automation test with real world examples and how to run them with test data in the Postman Collection Runner.

Related Posts