The Postman app is an excellent tool for building and testing Web APIs. It gets even better when you combine it with Newman, which allows you to execute your Postman scripts on a continuous integration system like Bitbucket Pipelines. While both Postman and Newman are awesome, you may encounter issues while working with both apps.

    // Code Omitted For Brevity

One issue you may encounter is having a script that was written in Postman, successfully tested using Postman, fail when executed using Newman. For example, the script above, which was written in Postman, is part of a series of tests that inspects the HTTP request body. The script can fail when executed on Newman because the function isEmpty does not exist.

The error generated by Newman is “Cannot read properties of undefined (reading ‘isEmpty’)”.

If you have done enough JavaScript development, you would know that the error means the function was invoked before it could be loaded. What is happening here is that in the Postman sandbox, the app you use to build your API collection and tests imports some external libraries implicitly, for example, in Postman you can do something like the following code snippet in a Pre-request script or test.

var bodyAsBase64 = CryptoJS.enc.Base64.strigify(pm.request.body.raw);

The code above works even though in any other JavaScript runtime like Node.js you would first need to import it CryptoJS as seen in the following code snippet.

var CryptoJS = require("crypto-js");
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123').toString();
console.log("ciphertext=", ciphertext);

This is why it is best to always be explicit when importing external dependencies on your Postman script. To solve our issue of the function isEmpty not being defined. We need to import the postman sdk because that is where the function isEmpty is defined. Our original code needs to be updated.

var sdk = require('postman-collection');
var options = {
    raw = pm.request.body
var body = new sdk.RequestBody(options)
    // Code Omitted For Brevity

First, as mentioned, import the Postman SDK, then create an options object using the request body, then instantiate the SDK and call the class you want to use, since we are working with a request body, the class RequestBody is called with the previously defined options being passed to it.

Now, when the code is executed in Newman, it will not fail because the function isEmpty will be defined when invoked by your script.