简体   繁体   中英

Accessing environment variable in Newman script

I'd like to access variable from my environment and save it to file every time Newman sends a request. I know there is --export-environment option while running it from command line, but I need to access it as Postman do through pm.environment.get("name") so the final script would look like this

newman.run({
    collection: require('./collection.json'),
    reporters: 'cli',
    environment: require('./environment.json'),
    exportEnvironment: require('./environment.json'),
    globals: require('./globals.json'),
    exportGlobals: require('./globals.json')
})
.on('request', (error, data) => {
    if (error) {
        console.log(error);
        return;
    }

    var variable1 = 'first variable' 
    var variable2 = 'second variable'

    fs.appendFile("my_values.txt", variable1 + variable2, function (error) {
        if (error) { 
             console.error(error); 
        }
     });
});

I found the answer so I'll post it as there is nothing in documentation about this and couldn't find answer on any of sites. Looks like variables are accessible in test event like this

newman.run({
    collection: require('./collection.json'),
    reporters: 'cli',
    environment: require('./environment.json'),
    exportEnvironment: require('./environment.json'),
    globals: require('./globals.json'),
    exportGlobals: require('./globals.json')
}).on('test', (error, data) => {
    if (error) {
        console.log(error);
        return;
    }
    var variable1 = data.executions[0].result.environment.values.reference.myVariable1.value;
    var variable2 = data.executions[0].result.environment.values.reference.myVariable2.value + '\n';

    fs.appendFile("output.txt", variable1 + variable2, function (error) {
        if (error) { 
             console.error(error); 
        }
     });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM