3 Postman Hacks For Writing Tests Faster

Three simple to advance hacks to writing Postman tests

Audit Your API

Often when I’m working on a project, or even when I inherit and existing project, the first thing I look at is the API. It’ll give me insight as to how the payload is handled, what status codes to account for, what conventions are being followed, and more.

If you’re going to take on an existing project, it’s always a good idea to factor in an audit of the API, even if there is documentation.

Don’t always trust the API Documentation. Do an Audit.

A client may not like it, but it’s better to find out problems at the beginning versus finding them out later and not being able to manage expectations.

Postman Tests

If you’re not already using Postman, I recommend getting it, and even integrating into your tests with their CLI called newman. Great way to spot errors, and unexpected behaviour.

1. Collection Tests

As a common rule, if you ever find yourself copying and pasting things, that is probably not the way to go. This just reinforces the DRY principle, Don’t Repeat Yourself.

If you organize your tests in folders, and if all your payload is JSON, then there is one consistent test that you can run for all endpoints, to make sure that if you hit an endpoint, it’s not returning 500 Error with a bunch of error messages from the backend. This is the test I run for every endpoint:

const jsonData = JSON.parse(responseBody);
tests["Validate JSON - Body - Present"] = ((responseBody) !== undefined && (responseBody.length > 1))
tests["Validate JSON - Response - Object"] = (typeof jsonData) === 'object';tests["Validate JSON - Header - Content-Type - JSON"] = postman.getResponseHeader("Content-Type").has('application/json');

To make sure this test is run for all your endpoints, create a New Collection, and click the three (…) dots and go to Edit, which will bring you to edit your collection.

In the Edit Collection modal, click the tab called Tests and copy and paste the code above.

3 Ways To Write Postman Tests Faster — Edit Collection Tests

Click Update, and now when we create any new tests under that folder it will run those tests as well as any other tests specific to that endpoint.

3 Ways To Write Postman Tests Faster — Collection Tests

Small Plug. If you haven’t joined my email list yet, I’m working on a few courses that are going to be released later this year on JavaScript, React, NodeJS, Docker, and more. The first people will be given massive discounts when they are released.

2. Global Variable Functions

This is more of a hack of a solution, but if you ever found yourself writing the same functions over and over again for pre-scripts, tests, and overall http requests, then this is a great way to make functions globally accessible.

The first step is to define your function in JavaScript normally.

// Random Integer
(min, max) => Math.floor(Math.random() * (max - min + 1) + min)

Next we’ll take that function and go back to our Edit Collection > Tests and create a Global.

3 Ways To Write Postman Tests Faster — Create Global

The code should look like this, which sets our function as a string:

pm.globals.set("RANDINT", "(min, max) => Math.floor(Math.random() * (max - min + 1) + min)");

Next we’re going to use that function with eval in our tests and just output the value in a test.

// Globals
const randInt = eval(pm.globals.get("RANDINT"));
// Init
const ourValue = randInt(1, 10);
// Test
tests[`Validate '${ourValue}' Is Integer`] = typeof ourValue === 'number';
3 Ways To Write Postman Tests Faster —Global Function

You’ll notice I’m using tests['My Test'] more so than the documentation offered by Postman. That’s just a personal preference for simpler code, but if you wanted to write the same test in the standard tests Postman defined, you would write it as:

// Globals
const randInt = eval(pm.globals.get("RANDINT"));
// Init
const ourValue = randInt(1, 10);
// Test
pm.test(`Validate '${ourValue}' Is Integer`, () => {
pm.expect(typeof ourValue).to.eq('number');

3. Test Snippets

This last one is taking advantage of Postman test snippets, but specifically in Mac OS. This might differ for windows, but note that this does have the potential of making Postman not work if not done correctly. I recommend doing a backup of the file we’re modifying.

UPDATE OCT/21/2019: If you want to know how to do this on Windows, check out Gopi Krishna’s article on how you can implement Postman Test Snippets on Windows.

To give you context on Postman test snippets, there are two places they exist, Pre-request Scripts and Tests.

3 Ways To Write Postman Tests Faster — Example Test Snippet

Currently, there is no way to add your own snippets to Postman, but we’re going to change that. To make this more efficient, we’re going to use Visual Studio Code to modify the file.



cd /Applications/Postman.app/Contents/Resources/app/js/;
open -a /Applications/Visual\ Studio\ Code.app vendor-shared.js;

Make Sure To Make A Backup

We’re modifying a core file for Postman, so it’s import you have a way to revert back if anything goes wrong.

cp /Applications/Postman.app/Contents/Resources/app/js/vendor-shared.js /Applications/Postman.app/Contents/Resources/app/js/vendor-shared.js.bak;

When we open up the file, it’ll be large, but the line we’re looking for starts with:

module.exports = [{"id":"get-env-var","name":"Get an environment variable", ...
3 Ways To Write Postman Tests Faster — Postman Shared JavaScript File

What we’re going to do is copy the form of one of the array objects and include one of our own functions, that we can easily use multiple times.

Existing Sample Object

// unique id
"id": "get-env-var",

// name shown on postman
"name": "Get an environment variable",

// description not really shown in postman
"description": "Gets an environment variable",

// actual escaped code that is copied over
"code": "pm.environment.get(\"variable_key\");",

// where the code is shown, in Pre-Request Scripts and Tests

Now that we have the format, we’re going to create a new snippet that is visible on both the Pre-Scripts and Tests.

Our Function

"id": "rand-integer",
"name": "Random integer",
"description": "Generates random integer",
"code": "const randInt = eval(pm.globals.get(\"RANDINT\"));",

Now let’s minify the script:

{"id":"rand-integer","name":"Random integer","description": "Generates random integer","code":"const randInt = eval(pm.globals.get(\"RANDINT\"));","validity":["prerequest","test"]}

Add it to the end of the array in the vendor-shared.js file:

...,{"id":"rand-integer","name":"Random integer","description":"Generates random integer","code":"const randInt = eval(pm.globals.get(\"RANDINT\"));","validity":["prerequest","test"]}]
3 Ways To Write Postman Tests Faster — vendor-shared.js

Save our file and now restart Postman. We should now see under Pre-Request Scripts and Tests our snippet. You just need do a one-click of our new Random Integer snippet.

3 Ways To Write Postman Tests Faster — Postman Test Snippets

If you got value from this, and/or if you think this can be improved, please let me know in the comments.

Please share it on twitter 🐦 or other social media platforms. Thanks again for reading. 🙏

Follow me on twitter: @codingwithmanny and instagram at @codingwithmanny.




Web Application / Full Stack JavaScript Developer & Aspiring DevOps

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

We All Need Automated Tests (Rant.js)

Doubly Linked List All Operations

10 useful tips for Styled Components

100 AWESOME Developers to follow on Twitter

JavaScript Concepts(Closures, Conversion)

Node.js Module system Part 4( note-taking app)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Web Application / Full Stack JavaScript Developer & Aspiring DevOps

More from Medium

Solid Design Principles In Javascript (Part 2) — Open-Closed Principle

Reauthenticating a user without redirection in OIDC

3 Lessons Learned from Using Playwright for UI Tests