Ben Weese

Testing with Postman: Reusable Code

Since I talked about reusable code in your environmental variable last week lets see how that works this week.

Adding Reusable Code to Your Variable

//Here we create a function that is then stored in the environmental variable. This is so we can then call this from any following test. This can be stored in the pre-req. of your first test in your collection.

postman.setEnvironmentVariable("commonTests", () => {
     //These are test that are ran on every call no matter if it is a positive or negative test.
     pm.test("Response time is below 300ms", function() {

      //This is the test we want to run on all positive outcomes.
     //Email enrollment does not have a valid json by design
     var positive = (validJson = true) => {
          pm.test("Status code is 200", function() {
          pm.test("Response does not error", function() {
          if (validJson) {
               pm.test("Response must be valid and have a body", function() {
            // this assertion checks if a body exists
          }     };
     //This is for our negative test that we want to fail. In Javascript we can set a default value for our incoming variable. 
     var negative = (code = 400) => {
            if (code === 400) {
                  pm.test("Status code is 400", function() {
          } else if (code === 403) {
               pm.test("Status code is 403", function() {
         } else if (code === 404) {
                  pm.test("Status code is 404", function() {
        } else if (code === 500) {
               pm.test("Status code is 500", function() {
//This could be simpler code of below.
var negative = (code = 400) => {
                 pm.test("Status code is correct", function() {
//another test to be added
     pm.test("Reports Error", function() {

          })     }
//we return the functions so they can be used outside of the environmental variable.
     return {
          testType: {

Using the Code in Test

//for positive test add this line to the top of your test.

//for negative test add this line to the top of your test.
//Can also use eval(environment.commonTests)().testType.negative(404); for when the code is 404


Postman Quick Reference Guide
Chai Assertion Library
Regex Cheat Sheet
Postman: The Complete Guide on Udemy

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.