如何使用 newman API 导出环境变量

how to export environment variable using newman API

我是 运行 一个使用 newman api 的邮递员测试服。它按预期正确执行,但我想导出文件中测试执行期间生成的环境变量,在命令行中可以使用 --export-environment:

newman run collectionPreReq.json -e Environment.json -k --export-environment newmanExport.json 

同样,我正在写 javascript 来获取 collectionPreReq 导出的环境,但没有得到我要找的东西,代码是

var newman = require('newman');

newman.run({
    collection: require('./collectionPreReq.json'),
    //reporters: 'cli',
    environment: require('./Environment.json'),
    insecure: true
}).on('start', function (err, args) {
    console.log('running a collection...');
}).on('done', function (err, summary) {
    if (err || summary.error) {
        console.error('collection run encountered an error.');
    }
    else {
        console.log('collection run completed.:');
        console.log("summary environment :");
        console.log(summary.environment);
    }
});

输出:

running a collection...
collection run completed.:
summary environment :
{ object: [Function], toJSON: [Function] }

根据 NodeJS documentation 不可能。

The process.env property returns an object containing the user environment. See environ(7).

An example of this object looks like:

{ 
  TERM: 'xterm-256color', 
  SHELL: '/usr/local/bin/bash', 
  USER: 'maciej', 
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', 
  PWD: '/Users/maciej', 
  EDITOR: 'vim', 
  SHLVL: '1', 
  HOME: '/Users/maciej',   
  LOGNAME: 'maciej',   
  _: '/usr/local/bin/node' 
}

It is possible to modify this object, but such modifications will not be reflected outside the Node.js process. In other words, the following example would not work:

$ node -e 'process.env.foo = "bar"' && echo $foo

请尝试在 javascript 文件中使用此 newman 选项 exportEnvironment: require('./Environment.json')

newman.run({
   collection: require('./collectionPreReq.json'),
   //reporters: 'cli',
   environment: require('./Environment.json'),
   exportEnvironment: require('./Environment.json'),
   insecure: true 
})....

当然,这个语句会起作用。

要控制台记录实际环境变量,您需要首先对 JSON 进行字符串化: .....

.on('done', function (err, summary) {
if (err || summary.error) {
console.error('collection run encountered an error.');
}
else {
console.log('collection run completed.:');
console.log("summary environment :");
console.log(JSON.stringify(summary.environment))
}
});