const { exec } = require('child_process');
const collectionFile = 'path/to/collection.json';
const dataFile = 'path/to/data.json';
exec(`newman run ${collectionFile} --iteration-data ${dataFile} --reporters cli,json --reporter-json-export newman-report.json`, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing Newman: ${error.message}`);
process.exit(1);
}
if (stderr) {
console.error(`Newman stderr: ${stderr}`);
}
console.log(`Newman output:\n${stdout}`);
// Simple check for iterations run
const iterationsMatch = stdout.match(/iterations:\s*(\d+)/i);
if (iterationsMatch) {
const iterations = parseInt(iterationsMatch[1], 10);
console.log(`Iterations run: ${iterations}`);
} else {
console.warn('Could not find iterations count in output');
}
// Check for failures
const failuresMatch = stdout.match(/failed:\s*(\d+)/i);
if (failuresMatch) {
const failures = parseInt(failuresMatch[1], 10);
if (failures === 0) {
console.log('All tests passed for all iterations.');
} else {
console.error(`There are ${failures} test failures.`);
process.exit(1);
}
} else {
console.warn('Could not find failures count in output');
}
});This Node.js script runs Newman CLI using child_process.exec to execute the Postman collection with the data file.
The --iteration-data option tells Newman to run the collection once per data row.
The script captures the output and parses it to find how many iterations ran and how many tests failed.
If there are any failures, the script exits with error code 1 to indicate test failure.
This approach automates running the collection with multiple data inputs and verifies the results programmatically.