import { exec } from 'child_process';
const collectionPath = './my_collection.json';
exec(`newman run ${collectionPath} -r json`, (error, stdout, stderr) => {
if (error) {
console.error(`Execution error: ${error}`);
process.exit(1);
}
try {
// Newman outputs JSON report after the run
const outputStart = stdout.indexOf('{');
const outputJson = stdout.substring(outputStart);
const result = JSON.parse(outputJson);
const totalRequests = result.run.stats.requests.total;
const totalTests = result.run.stats.tests.total;
const failedTests = result.run.stats.tests.failed;
console.assert(totalRequests === result.run.executions.length, `Expected total requests ${result.run.executions.length}, got ${totalRequests}`);
console.assert(failedTests === 0, `Expected 0 failed tests, got ${failedTests}`);
console.log('Collection run successful with all tests passing.');
} catch (parseError) {
console.error('Failed to parse Newman JSON output:', parseError);
process.exit(1);
}
});This script uses Node.js child_process.exec to run Newman CLI with the -r json reporter, which outputs the collection run results in JSON format.
It captures the standard output, extracts the JSON part, and parses it to an object.
Assertions check that the total number of requests run matches the number of executions and that there are zero failed tests.
If assertions pass, it logs success; otherwise, it throws an error.
This approach automates running the Postman collection and verifying the collection runner results programmatically.