Search code examples
javascriptnode.jspostmannewman

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); 
        }
     });
});

Solution

  • 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); 
            }
         });
    });