output responseBody somewhere with newman script from postman collection

RobBenz picture RobBenz · Mar 29, 2018 · Viewed 7.2k times · Source

I am attempting to run a script.js with newman from a locally saved postman collection. In postman the call works, and returns a response body token that I need access to.

I don't care how the response body is returned I just don't want to open postman if I don't have to.

I keep encountering an error of ReferenceError: responseBody is not defined

Any help on this matter would be really appreciated.

$ node script.js

var newman = require('newman'); // require newman in your project

// call newman.run to pass `options` object and wait for callback
newman.run({
    collection: require('./pathto/my_coll.postman_collection.json'),
    reporters: 'cli'
}, function (err) {
    if (err) { throw err; }
    // console.log(responseBody);
    JSON.parse(responseBody);

});

neither console.log or JSON.parse appear to be doing the trick because responseBody doesn't appear to be defined from the start

exhausted references:

https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox

https://www.npmjs.com/package/newman

how to get whole html or json repsonse of an URL using Newman API

Answer

Sivcan Singh picture Sivcan Singh · Mar 29, 2018

A postman collection is a collection of requests.

You're running the whole collection (which is a series of requests being ran all together by Newman)

Thus, logging / parsing the responseBody in a callback function is incorrect (Stating this logically).

As per the Newman Docs it states that the .run function's callback is called with two parameters that are err and summary

The summary argument in the callback contains the whole summary for the run and you can follow the documentation if you want to make use of that summary.

Now, What you're trying to do is basically log the response of the request(s).

You need to write a console.log(responseBody) / JSON.parse(responseBody) inside the test scripts for each request in the collection and then on running the collection using newman, each responseBody for each request will be logged out / parsed as per your needs.

To access the summary you can modify your function like so :

var newman = require('newman');
newman.run({
    collection: require('./C1.postman_collection.json'),
    reporters: 'cli'
}, function (err, summary) {
    if (err) { throw err; }
    console.log(summary);
});