如何捕获纽曼的回应体

时间:2018-10-18 13:30:35

标签: newman

我想在纽曼捕获响应主体。

            const newman = require('newman'); 
            newman.run({
                collection: require('./xxx.json'),
                iterationData: './data.jsp',
                reporters: 'cli'
            }, function (err, summary) {
                if (err) { throw err; }
                console.log('collection run complete!');
                console.log(summary);
            });

我使用上面的代码。它工作正常,但我想从调用中捕获json输出。我该如何实现?

2 个答案:

答案 0 :(得分:1)

也许您在检索json响应正文时使用了错误的术语。如果只想获取响应主体,则需要解析返回的JSON并将其保存到变量中。 如果您要使用newman在命令行中运行,那么一切都将变得非常简单:

let body = JSON.parse(responseBody)
console.log(body)

,然后在需要查看响应的地方进行测试,然后将这两行代码放入

但是对于您的情况,也许您需要: 1)回调选项

const newman = require('newman'); 
            newman.run({
                collection: require('./xxx.json'),
                iterationData: './data.jsp',
                reporters: 'cli'
            }, function (err, summary) {
                if (err) { throw err; }
                console.log('collection run complete!');
                console.log(summary);
            })
.on('request', function (err, data) {
     // err, data can be used to write to files using the node fs module.
  });

或更现代的选择:

let response = await newman.run({
            collection: 'collection',
            environment: 'env',
        })
.on('request', async function (err, data) {
         // err, data can be used to write to files using the node fs module.
      });
        console.log(response)

不确定我会按预期工作,但至少可以尝试。 顺便说一句,您在哪里运行这些测试?只是在清晰的环境中或使用某些运行器框架。

答案 1 :(得分:0)

回叫函数中的邮递员返回执行摘要。执行后,如果将摘要保存在回调中并返回。您可以访问请求/响应/标头。

function runcollection(callback){
   newman.run({
      collection: 'C:\\newman\\PMP Dependency latest collection\\Updated\\TestCollection.postman_collection.json',
      environment: 'C:\\newman\\PMP Dependency latest collection\\Updated\\Test.postman_environment.json',
      iterationCount :1
   },function(error, summary){
      callback(summary)
   });
}

runcollection(result => {console.log(result.run.executions[0].response.stream.toString())});