Search code examples
postmannewman

Postman - Newman running from NodeJS


In order to save the response from postman API calls, I am executing Postman collection using newman run.

The collection runs when running using

newman run C:\TasteBud\NewMan\JSON-Order_collection.json --env-var unique_order_id=OD-06-07-I2Q5-JYRY5ARPN --environment C:\TasteBud\NewMan\EnvironmentJSON.json

However when I run the same collection as part of javascript or nodejs script.

node writeToFile.js    

it throws error as node "1⠄ JSONError in test-script " refer attached image. I need to pass the auth token generated by login request to subsequent request. So I have variable assignment in the "test".

let response = pm.response.json();
pm.environment.set("auth_token", response.data.auth_token);
console.log(pm.response.json().data.auth_token);

Why cant I have "test" ? if no then how can I pass/set these environment variable for subsequent API call ?

Code inside writeToFile.js is here. writeToFile.js

Successful run using command line

Calling via NodeJS

Javascript in test to get auth-token


Solution

  • Always use status code validation in your token generation. because every request is based on the token, if we receive negative status code, terminate the build.

    postman.setNextRequest(null);

    var jsonData = JSON.parse(responseBody);
    if(responseCode.code === 200){
    tests["Status code is 200"] = responseCode.code === 200;
    postman.setEnvironmentVariable("AT", jsonData.oauth2.accessToken);
    console.log("AccessToken : " +jsonData.oauth2.accessToken);
    }
    else{
        postman.setNextRequest(null);
          console.log("Error generating user token");
        console.log("Status code : "+responseCode.code);
        console.log("Status description  : "+jsonData.statusDescr);
    }