### Install HTML Reporter Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Install the HTML reporter globally for Newman. Remove the -g flag for a local installation. ```bash $ npm install -g newman-reporter-html ``` -------------------------------- ### Install Newman HTML Reporter Source: https://github.com/postmanlabs/newman/blob/develop/README.md Install the Newman HTML reporter globally using npm. For local installation, omit the -g flag. ```bash npm install -g newman-reporter-html ``` -------------------------------- ### Run Newman with Community Reporters (CLI) Source: https://github.com/postmanlabs/newman/blob/develop/README.md Use community-maintained reporters like 'htmlextra' and 'csv' via the Newman CLI. Ensure the reporter packages are installed. ```bash newman run /path/to/collection.json -r htmlextra,csv ``` -------------------------------- ### Install Newman Globally via NPM Source: https://github.com/postmanlabs/newman/blob/develop/README.md Install Newman globally on your system to run it from any directory. Remove the -g flag for a local installation. ```bash npm install -g newman ``` -------------------------------- ### Run HTML Reporter with Ubuntu Docker Image Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Execute Newman with the HTML reporter using the Ubuntu-based Docker image. Ensure the collection directory is mounted and the reporter is installed. ```bash docker run -v "~/collections:/etc/newman" --entrypoint /bin/bash postman/newman:ubuntu -c "npm i -g newman-reporter-html; newman run sample-collection.json -r html" ``` -------------------------------- ### Run HTML Reporter with Alpine Docker Image Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Execute Newman with the HTML reporter using the Alpine-based Docker image. Ensure the collection directory is mounted and the reporter is installed. ```bash docker run -v "~/collections:/etc/newman" --entrypoint /bin/sh postman/newman:alpine -c "npm i -g newman-reporter-html; newman run sample-collection.json -r html" ``` -------------------------------- ### Install Newman via Homebrew Source: https://github.com/postmanlabs/newman/blob/develop/README.md Install Newman globally on your system using Homebrew for macOS users. ```bash brew install newman ``` -------------------------------- ### Configure Newman with Socks Proxy Agent Source: https://github.com/postmanlabs/newman/blob/develop/README.md Use Newman as a library and configure it to use a custom HTTP(S) agent for making requests, such as a SocksProxyAgent. Ensure the 'socks-proxy-agent' package is installed. ```js const newman = require('newman'); const SocksProxyAgent = require('socks-proxy-agent'); const requestAgent = new SocksProxyAgent({ host: 'localhost', port: '1080' }); newman.run({ collection: require('./sample-collection.json'), requestAgents: { http: requestAgent, // agent used for HTTP requests https: requestAgent, // agent used for HTTPS requests } }, function (err) { if (err) { throw err; } console.log('collection run complete!'); }); ``` -------------------------------- ### Display Newman Version Source: https://github.com/postmanlabs/newman/blob/develop/README.md Use the -v or --version flags to display the current Newman version installed on your system. ```bash -v, --version ``` -------------------------------- ### Create a Custom Newman Reporter Source: https://context7.com/postmanlabs/newman/llms.txt Implement a custom reporter by subscribing to Newman's run events. This example shows how to record request details and export them. ```javascript // File: newman-reporter-myreporter/index.js // Install: npm install -g newman-reporter-myreporter // Usage CLI: newman run collection.json -r myreporter // Usage lib: reporters: ['myreporter'] function MyReporter(emitter, reporterOptions, collectionRunOptions) { const results = []; emitter.on('request', function (err, args) { results.push({ name: args.item.name, url: args.request.url.toString(), status: err ? 'ERROR' : args.response.code, responseTime: args.response && args.response.responseTime }); }); emitter.on('beforeDone', function (err) { if (err) { return; } // Export to custom destination before run finishes emitter.exports.push({ name: 'myreporter', default: 'newman-myreporter.json', path: reporterOptions.export, content: JSON.stringify(results, null, 2) }); }); emitter.on('done', function () { console.log(`MyReporter: ${results.length} requests recorded.`); }); } module.exports = MyReporter; // --- Using the external reporter programmatically --- const newman = require('newman'); newman.run({ collection: require('./sample-collection.json'), reporters: ['cli', 'myreporter'], reporter: { myreporter: { export: './out/my-report.json' } } }, function (err) { if (err) { throw err; } }); // Install well-known community reporters: // npm install -g newman-reporter-html // npm install -g newman-reporter-htmlextra // npm install -g newman-reporter-allure // CLI: // newman run collection.json -r html --reporter-html-export ./report.html // newman run collection.json -r htmlextra --reporter-htmlextra-export ./report.html ``` -------------------------------- ### Listen to Newman Run Events Source: https://github.com/postmanlabs/newman/blob/develop/README.md Use the `.on()` method to subscribe to Newman events like 'start' and 'done'. This is useful for logging or performing actions at specific points in the collection run. Ensure the collection path and any necessary data/environment variables are correctly configured. ```javascript newman.run({ collection: require('./sample-collection.json'), iterationData: [{ "var": "data", "var_beta": "other_val" }], globals: { "id": "5bfde907-2a1e-8c5a-2246-4aff74b74236", "name": "test-env", "values": [ { "key": "alpha", "value": "beta", "type": "text", "enabled": true } ], "timestamp": 1404119927461, "_postman_variable_scope": "globals", "_postman_exported_at": "2016-10-17T14:31:26.200Z", "_postman_exported_using": "Postman/4.8.0" }, globalVar: [ { "key":"glboalSecret", "value":"globalSecretValue" }, { "key":"globalAnotherSecret", "value":`${process.env.GLOBAL_ANOTHER_SECRET}`} ], environment: { "id": "4454509f-00c3-fd32-d56c-ac1537f31415", "name": "test-env", "values": [ { "key": "foo", "value": "bar", "type": "text", "enabled": true } ], "timestamp": 1404119927461, "_postman_variable_scope": "environment", "_postman_exported_at": "2016-10-17T14:26:34.940Z", "_postman_exported_using": "Postman/4.8.0" }, envVar: [ { "key":"secret", "value":"secretValue" }, { "key":"anotherSecret", "value":`${process.env.ANOTHER_SECRET}`} ], }).on('start', function (err, args) { // on start of run, log to console 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.'); } }); ``` -------------------------------- ### Use Custom Reporters with Newman Docker Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Integrate custom Newman reporters by installing them within the Docker container. Mount a local directory for collections and reports. ```bash docker run -v ":/etc/newman" --entrypoint /bin/ -c "npm i -g newman-reporter-; newman run sample-collection.json -r " ``` -------------------------------- ### V5 Equivalent CSV Input Example Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Shows the equivalent CSV input format for Newman v5, where the default escape character is a double quote. ```csv id, name """1""", "foo ""bar"" baz" ``` -------------------------------- ### Update Newman to Latest Version Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Use npm to update Newman to the latest version. Verify the installation by checking the version number. ```bash $ npm update -g newman ``` ```bash $ newman --version # Should show the latest version of Newman $ npm show newman version # Should show the same version as of above ``` -------------------------------- ### V4 to V5 CSV Input Example Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Illustrates the CSV input format used in Newman v4, where the escape character is a backslash. ```csv id, name "\"1\"", "foo \"bar\" baz" ``` -------------------------------- ### Run Postman Collection using Newman as a Library Source: https://github.com/postmanlabs/newman/blob/develop/README.md Integrate Newman into your JavaScript projects to programmatically run Postman collections. This example runs a collection from a local JSON file and uses the CLI reporter. ```javascript const newman = require('newman'); // require newman in your project // call newman.run to pass `options` object and wait for callback newman.run({ collection: require('./sample-collection.json'), reporters: 'cli' }, function (err) { if (err) { throw err; } console.log('collection run complete!'); }); ``` -------------------------------- ### Display Newman Command Line Help Source: https://github.com/postmanlabs/newman/blob/develop/README.md Use the -h or --help flags to view Newman's command line help, which includes a list of available options and sample use cases. ```bash -h, --help ``` -------------------------------- ### Migrate Basic CLI Options from V2 to V3 Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Compare V2 and V3 CLI commands for basic collection runs. Note the renaming and restructuring of options like `--data` to `--iteration-data` and `--number` to `--iteration-count`. ```terminal newman --collection collection.json --environment env.json --data data.csv --globals globals.json --number 2 --exportGlobals globalOut.json --exportEnvironment envOut.json --delay 10 --requestTimeout 5000 --noTestSymbols --tls --exitCode --whiteScreen --avoidRedirects --stopOnError ``` ```terminal newman run collection.json --environment env.json --iteration-data data.csv --globals globals.json --iteration-count 2 --export-globals globalOut.json --export-environment envOut.json --delay-request 10 --timeout-request 5000 --disable-unicode --suppress-exit-code --ignore-redirects --bail ``` -------------------------------- ### Newman V3 Run Command Equivalent Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md This snippet demonstrates the V3 `newman.run` command, which is the equivalent of V2's `execute`. It shows the updated options for reporters and output file configuration. ```javascript newman.run({ collection: 'https://a.com/collection.json', environment: { "id": "my-id", "name": "testEnv", "values": [ { "key": "env", "value": "env2", }, { "key": "data", "value": "env2", } ] }, iterationData: [ {a: 1}, {a: 2} ], globals: [ { key: "var1", value: "/get", enabled: true }, { key: "var2", value: "Global Bar", } ], reporters: ['html', 'junit', 'json'], reporter: { html: { export: 'htmlOutput.html' }, junit: { export: 'xmlOut.xml' }, json: { export: 'jsonOut.json' } } }, callback); ``` -------------------------------- ### Migrate Reporter CLI Options from V2 to V3 Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md See how V2 reporter options are mapped to V3's more structured reporter system. Options like `--outputFile` are replaced by specific reporter configurations such as `--reporter-json-export`. ```terminal newman --url https://a.com/collection.json --environment-url https://a.com/env.json --noColor --outputFile jsonOut.json --testReportFile xmlOut.xml --html htmlOutput.html --outputFileVerbose verboseOut.log ``` ```terminal newman run https://a.com/collection.json --environment https://a.com/env.json --reporters cli,html,json,junit --reporter-json-export jsonOut.json --reporter-junit-export xmlOut.xml --reporter-html-export htmlOutput.html ``` -------------------------------- ### Enable Colored Output in CLI (V3 vs V4) Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Demonstrates how to enable colored output in the Newman CLI. V3 used a simple flag, while V4 requires specifying 'on'. ```bash # V3 command $ newman run collection.json --color ``` ```bash # V4 equivalent $ newman run collection.json --color on ``` -------------------------------- ### Run Newman with Local Collections (Custom Mount) Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/alpine/README.md Run Newman with a custom volume mount for collections. Ensure the path to your collection and environment files is correctly specified. ```terminal docker --volume="/home/postman/collection:/etc/newman" -t postman/newman:alpine run JSONBlobCoreAPI.json.postman_collection" -r json --reporter-json-export newman-report.json ``` -------------------------------- ### Run Newman with Local Collections (Default Mount) Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/alpine/README.md Run Newman using the Docker image, mounting a local directory for collections and exporting the report. The collection directory is mounted to the default working directory `/etc/newman`. ```terminal docker --volume="/home/postman/collections:/etc/newman" -t postman/newman:alpine run JSONBlobCoreAPI.json.postman_collection -r json --reporter-json-export newman-report.json ``` -------------------------------- ### Migrate Basic Library Options from V2 to V3 Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Compare V2 and V3 library usage for basic collection runs. Options like `data` are renamed to `iterationData`, and `number` to `iterationCount`. ```javascript newman.execute({ collection: 'collection.json', environment: 'env.json', data: 'data.csv', globals: 'globals.json', number: 2, exportGlobals: 'globalOut.json', exportEnvironment: 'envOut.json', delay: 10, stopOnError: true, requestTimeout: 5000, noTestSymbols: true, tls: true, exitCode: true, whiteScreen: true, avoidRedirects: true }, callback); ``` ```javascript newman.run({ collection: 'collection.json', environment: 'env.json', iterationData: 'data.csv', globals: 'globals.json', iterationCount: 2, exportGlobals: 'globalOut.json', exportEnvironment: 'envOut.json', delayRequest: 10, bail: true, timeoutRequest: 5000, disableUnicode: true, suppressExitCode: true, ignoreRedirects: true }, callback); ``` -------------------------------- ### Build Newman Docker Image Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/ubuntu/README.md Build the Docker image locally and tag it for use. Replace 'full semver version' with the desired Newman version. ```terminal docker build -t postman/newman:ubuntu --build-arg NEWMAN_VERSION="full semver version" . ``` -------------------------------- ### Run Newman with Local Collections (Custom Workdir) Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/alpine/README.md Run Newman by mounting collections to a custom directory and changing the working directory to the mount point using the `-w` flag. ```terminal docker run --volume="/home/postman/collections:/etc/newman" -t postman/newman:alpine run JSONBlobCoreAPI.json.postman_collection -r json --reporter-json-export newman-report.json ``` -------------------------------- ### Run Newman with Local Collection, Environment, and JSON Report Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Executes a local Newman collection, applies a local environment file, and exports the results as a JSON report. The host's collections directory is mounted, and the reporter-json-export flag specifies the output file. ```bash docker run -v ~/collections:/etc/newman -t postman/newman:ubuntu \ run "HTTPBinNewmanTest.json.postman_collection" \ --environment="HTTPBinNewmanTestEnv.json.postman_environment" \ --reporters="json,cli" --reporter-json-export="newman-results.json" ``` -------------------------------- ### Run Collection with CLI and JSON Reporters Source: https://github.com/postmanlabs/newman/blob/develop/README.md Use this command to run a collection and output results using both the CLI and JSON reporters. The CLI reporter is enabled by default, but explicitly including it ensures output when other reporters are active. ```bash $ newman run examples/sample-collection.json -r cli,json ``` -------------------------------- ### Enable Colored Output in Library (V3 vs V4) Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Illustrates enabling colored output when using Newman programmatically. V3 used a boolean, V4 uses the string 'on'. ```javascript // Using V3 newman.run({ collection: 'collection.json', reporters: ['cli'], color: true }, callback); ``` ```javascript // V4 equivalent newman.run({ collection: 'collection.json', reporters: ['cli'], color: 'on' }, callback); ``` -------------------------------- ### Run Newman with Local Collection Files Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Runs a Newman collection from a local file by mounting the host's collections directory into the Docker container. The host directory '~/collections' is mounted to '/etc/newman' inside the container. ```bash docker run -v ~/collections:/etc/newman -t postman/newman:ubuntu run "HTTPBinNewmanTestNoEnv.json.postman_collection" ``` -------------------------------- ### Run Newman with File Upload Source: https://github.com/postmanlabs/newman/blob/develop/README.md Execute a Postman collection that includes file uploads using Newman. Ensure the collection file and the specified sample file are in the current directory. ```console $ ls file-upload.postman_collection.json sample-file.txt $ newman run file-upload.postman_collection.json ``` -------------------------------- ### Configure Run Behavior (Bail, Exit Code, SSL) Source: https://context7.com/postmanlabs/newman/llms.txt Control the collection run's behavior by enabling `--bail` on failure, suppressing the default exit code with `--suppress-exit-code`, and disabling SSL verification with `--insecure`. ```bash # Bail on first failure, suppress default exit code, disable SSL verification newman run examples/sample-collection.json \ --bail failure \ --suppress-exit-code \ --insecure ``` -------------------------------- ### Build Newman Docker Image Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Builds a Docker image for Newman from the cloned repository. The --build-arg NEWMAN_VERSION allows specifying the Newman version. The '.' indicates the build context is the current directory. ```bash docker build -t postman/newman:ubuntu --build-arg NEWMAN_VERSION="full semver version" .; ``` -------------------------------- ### Run Newman with HTML Reporter (CLI) Source: https://github.com/postmanlabs/newman/blob/develop/README.md Execute a Newman collection run using the CLI, specifying the 'html' reporter alongside the default 'cli' reporter. ```bash newman run /path/to/collection.json -r cli,html ``` -------------------------------- ### Enable Verbose Output and Request Delay Source: https://context7.com/postmanlabs/newman/llms.txt Use `--verbose` for detailed output during the collection run and `--delay-request` to introduce a specified delay in milliseconds between each request. ```bash # Add a delay between requests and use verbose output newman run examples/sample-collection.json \ --verbose \ --delay-request 500 ``` -------------------------------- ### Run Newman with Remote Collection, Local Environment, and JUnit Report Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Runs a remote Newman collection, applies a local environment file, and exports the test results as a JUnit XML report. The host's collections directory is mounted, and the reporter-junit-export flag specifies the output file. ```bash docker run -v ~/collections:/etc/newman -t postman/newman:ubuntu \ run https://www.getpostman.com/collections/8a0c9bc08f062d12dcda \ --environment="HTTPBinNewmanTestEnv.json.postman_environment" \ --reporters="junit,cli" --reporter-junit-export="newman-report.xml" ``` -------------------------------- ### newman.run(options, callback) Source: https://context7.com/postmanlabs/newman/llms.txt Executes a Postman collection programmatically. It accepts an options object for configuration and a callback function to handle completion or errors. All command-line features are available through the options. ```APIDOC ## `newman.run(options, callback)` — Programmatic Collection Runner The `newman.run()` function executes a Postman collection and returns an `EventEmitter`. The callback receives `(err, summary)` on completion. All CLI features are available programmatically. ### Parameters * **options** (object) - Configuration options for running the collection. * `collection` (object | string) - Collection object, file path, or URL. * `environment` (object | string) - Environment file path, URL, or object. * `globals` (object | string) - Globals file path, URL, or object. * `iterationData` (string) - CSV or JSON data file for iterations. * `iterationCount` (number) - Number of iterations to run. * `folder` (string | string[]) - Specific folder(s) to run within the collection. * `reporters` (string | string[]) - Active reporters to use (e.g., 'cli', 'json'). * `reporter` (object) - Reporter-specific options. * `envVar` (object[]) - Array of environment variables to set. * `globalVar` (object[]) - Array of global variables to set. * `timeoutRequest` (number) - Request timeout in milliseconds. * `timeoutScript` (number) - Script timeout in milliseconds. * `timeout` (number) - Total run timeout in milliseconds. * `delayRequest` (number) - Delay between requests in milliseconds. * `bail` (boolean) - Stop execution on the first failure. * `insecure` (boolean) - Skip SSL certificate verification. * `ignoreRedirects` (boolean) - Do not automatically follow 3xx redirects. * `color` (string) - CLI color setting ('auto', 'on', 'off'). * `workingDir` (string) - Working directory for file reads. * `insecureFileRead` (boolean) - Allow reading files outside the working directory. * `suppressExitCode` (boolean) - Override the process exit code. * `verbose` (boolean) - Show detailed request and response information. * **callback** (function) - A function to be called upon completion. It receives two arguments: `err` (error object if any) and `summary` (an object containing run statistics and results). ### Response * **err** (object | null) - An error object if the run failed, otherwise null. * **summary** (object) - An object containing the results of the collection run, including statistics, failures, and timings. * `run.stats` (object) - Statistics about the run (total requests, failed requests, total assertions, failed assertions). * `run.failures` (array) - An array of failures encountered during the run. * `run.timings` (object) - Timing information for the run. ### Example ```javascript const newman = require('newman'); newman.run({ collection: require('./sample-collection.json'), environment: './environment.json', reporters: ['cli', 'json'], reporter: { json: { export: './results/report.json' } } }, function (err, summary) { if (err) { throw err; } console.log('Collection run completed. Summary:', summary); }); ``` ``` -------------------------------- ### Run Collection with Environment File Source: https://context7.com/postmanlabs/newman/llms.txt Execute a Postman collection using a specified environment file. This allows you to apply environment-specific variables during the run. ```bash # Run with a Postman environment file newman run examples/sample-collection.json -e environment.json ``` -------------------------------- ### Run Postman Collection from Local File Source: https://github.com/postmanlabs/newman/blob/develop/README.md Execute a Postman collection by specifying the path to its JSON file. Refer to the Command Line Options section for available flags. ```bash newman run examples/sample-collection.json ``` -------------------------------- ### Run Newman with HTML Reporter (Programmatic) Source: https://github.com/postmanlabs/newman/blob/develop/README.md Programmatically run a Newman collection, enabling both 'cli' and 'html' reporters. The process will exit after the run. ```javascript const newman = require('newman'); newman.run({ collection: '/path/to/collection.json', reporters: ['cli', 'html'] }, process.exit); ``` -------------------------------- ### Run Newman with Custom Working Directory Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/ubuntu/README.md Execute Newman, mounting collections to a specific directory and then changing the container's working directory to that mount point using the -w flag. ```terminal docker run --volume="/home/postman/collections:/etc/newman" -t postman/newman:ubuntu run JSONBlobCoreAPI.json.postman_collection -r json --reporter-json-export newman-report.json ``` -------------------------------- ### Run Postman Collection from URL Source: https://github.com/postmanlabs/newman/blob/develop/README.md Fetch and run a Postman collection directly from a URL, such as from the Postman Cloud API. ```bash newman run https://www.getpostman.com/collections/631643-f695cab7-6878-eb55-7943-ad88e1ccfd65-JsLv ``` -------------------------------- ### Disable Colored Output in Library (V3 vs V4) Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Demonstrates disabling colored output programmatically. V3 used 'noColor: true', while V4 uses 'color: "off"'. ```javascript // Using V3 newman.run({ collection: 'collection.json', reporters: ['cli'], noColor: true }, callback); ``` ```javascript // V4 equivalent newman.run({ collection: 'collection.json', reporters: ['cli'], color: 'off' }, callback); ``` -------------------------------- ### Build Newman Alpine Docker Image Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/alpine/README.md Build the Docker image for Newman on Alpine Linux. Replace 'full semver version' with the desired Newman version. ```terminal docker build -t postman/newman:alpine --build-arg NEWMAN_VERSION="full semver version" . ``` -------------------------------- ### Newman V2 Execute Command Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md This snippet shows the V2 `newman.execute` command with various options for collection execution, environment, globals, and output files. ```javascript newman.execute({ collection: 'https://a.com/collection.json', environment: { "id": "my-id", "name": "testEnv", "values": [ { "key": "env", "value": "env2", }, { "key": "data", "value": "env2", } ] }, globals: [ { key: "var1", value: "/get", enabled: true }, { key: "var2", value: "Global Bar", } ], outputFile: 'jsonOut.json', testReportFile: 'xmlOut.xml', html: 'htmlOutput.html', outputFileVerbose: 'verboseOut.log' }, callback); ``` -------------------------------- ### Set Request and Script Timeouts Source: https://context7.com/postmanlabs/newman/llms.txt Configure various timeout settings for the collection run in milliseconds. This includes general timeouts, request timeouts, and script timeouts. `--delay-request` adds a pause between requests. ```bash # Set timeouts (in milliseconds) newman run examples/sample-collection.json \ --timeout 60000 \ --timeout-request 10000 \ --timeout-script 5000 \ --delay-request 200 ``` -------------------------------- ### Clone Newman Repository Source: https://github.com/postmanlabs/newman/blob/develop/docker/README.md Clones the Newman repository from GitHub to build the Docker image locally. This is the first step in building the image from source. ```bash git clone https://github.com/postmanlabs/newman.git ``` -------------------------------- ### Configure Multiple Reporters in Newman Source: https://context7.com/postmanlabs/newman/llms.txt Utilize multiple built-in Newman reporters simultaneously, such as CLI, JSON, and JUnit. Reporter-specific options are namespaced under `reporter.`. ```javascript const newman = require('newman'); // Use CLI and JSON reporters together newman.run({ collection: require('./sample-collection.json'), reporters: ['cli', 'json', 'junit'], reporter: { json: { export: './results/report.json' // Path for JSON report file }, junit: { export: './results/report.xml' // Path for JUnit XML report file }, cli: { silent: false, // Show CLI output noSummary: false, // Show summary table noFailures: false, // Show failure details noAssertions: false, // Show assertion results noSuccessAssertions: false, // Show passing assertions noConsole: false, // Show console.log output noBanner: false, // Show newman banner showTimestamps: true // Print timestamps per request } } }, function (err) { if (err) { throw err; } }); // CLI equivalent: // newman run collection.json \ // -r cli,json,junit \ // --reporter-json-export ./results/report.json \ // --reporter-junit-export ./results/report.xml \ // --reporter-cli-show-timestamps \ // --reporter-cli-no-success-assertions ``` -------------------------------- ### Run Events — emitter.on(event, handler) Source: https://context7.com/postmanlabs/newman/llms.txt The `newman.run()` method returns an EventEmitter that allows you to hook into various stages of the Newman run. Handlers receive `(err, args)`, where `args` contains event-specific properties and a `cursor` object detailing the run's progress. ```APIDOC ## Run Events — `emitter.on(event, handler)` ### Description The `newman.run()` method returns an EventEmitter that allows you to hook into various stages of the Newman run. Handlers receive `(err, args)`, where `args` contains event-specific properties and a `cursor` object detailing the run's progress. ### Events - **start**: Fired once at the start of the run. - **beforeIteration**: Fired before each iteration begins. - **beforeItem**: Fired before each request item's lifecycle (prerequest → request → test). - **request**: Fired after an HTTP response is received. - **assertion**: Fired for every test assertion. - **console**: Fired for every `console.log/warn/error` call inside a Postman script. - **exception**: Fired when an async error occurs inside a script. - **iteration**: Fired after each iteration completes. - **beforeDone**: Fired just before the run ends. - **done**: Fired when the entire run completes. ### Example Usage ```javascript const newman = require('newman'); newman.run({ collection: require('./sample-collection.json') }) .on('start', function (err, args) { if (err) { return; } console.log(`Starting run: ${args.cursor.length} requests × ${args.cursor.cycles} iteration(s)`) }) .on('beforeIteration', function (err, args) { console.log(`Iteration ${args.cursor.iteration + 1} starting`) }) .on('beforeItem', function (err, args) { console.log(` → Item: ${args.item.name}`) }) .on('request', function (err, args) { if (err) { console.error(' Request error:', err.message); return; } const url = args.request.url.toString(); const status = args.response.code; const time = args.response.responseTime; console.log(` ${status} ${url} (${time}ms)`) }) .on('assertion', function (err, args) { const icon = err ? '✗' : '✓'; console.log(` ${icon} ${args.assertion}`) }) .on('console', function (err, args) { console.log(` [script:${args.level}]`, ...args.messages) }) .on('exception', function (err, args) { console.error(' Script exception:', args.error.message) }) .on('iteration', function (err, args) { console.log(`Iteration ${args.cursor.iteration + 1} complete`) }) .on('beforeDone', function (err, args) { const { total, failed } = args.summary.run.stats.assertions; console.log(`beforeDone: ${total - failed}/${total} assertions passed`) }) .on('done', function (err, summary) { if (err || summary.run.error) { console.error('Run encountered a fatal error.'); return; } const failures = summary.run.failures.length; console.log(failures ? `Run finished with ${failures} failure(s).` : 'Run finished successfully.') }); ``` -------------------------------- ### Run Newman with Online Collection URL Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/ubuntu/README.md Execute Newman using a collection directly from a URL, bypassing the need to mount local collection files. This is useful for publicly accessible collections. ```terminal docker run -t postman/newman:ubuntu run https://www.getpostman.com/collections/8a0c9bc08f062d12dcda ``` -------------------------------- ### Run Newman with Community Reporters (Programmatic) Source: https://github.com/postmanlabs/newman/blob/develop/README.md Programmatically run a Newman collection using community reporters such as 'htmlextra' and 'csv'. The process will exit after the run. ```javascript const newman = require('newman'); newman.run({ collection: '/path/to/collection.json', reporters: ['htmlextra', 'csv'] }, process.exit); ``` -------------------------------- ### Run Collection from Postman Cloud API Source: https://context7.com/postmanlabs/newman/llms.txt Execute a Postman collection directly from the Postman Cloud API using its URL and an API key. Similarly, environments can also be specified via URL. ```bash # Run using the Postman Cloud API newman run "https://api.getpostman.com/collections/$COLLECTION_UID?apikey=$POSTMAN_API_KEY" \ --environment "https://api.getpostman.com/environments/$ENV_UID?apikey=$POSTMAN_API_KEY" ``` -------------------------------- ### Set Inline Environment and Global Variables Source: https://context7.com/postmanlabs/newman/llms.txt Define environment and global variables directly from the command line using `--env-var` and `--global-var` flags. This is useful for setting dynamic values without external files. ```bash # Set inline environment and global variables from the CLI newman run examples/sample-collection.json \ --env-var "baseUrl=https://api.example.com" \ --env-var "token=abc123" \ --global-var "timeout=5000" ``` -------------------------------- ### Run Newman with Online Collection Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/alpine/README.md Run Newman directly using a collection URL, without mounting local directories. This is suitable for publicly accessible collections that do not require environment files. ```terminal docker run -t postman/newman:alpine run https://www.getpostman.com/collections/8a0c9bc08f062d12dcda ``` -------------------------------- ### Run Collection with Globals and Iteration Data Source: https://context7.com/postmanlabs/newman/llms.txt Execute a Postman collection with global variables and iteration data loaded from CSV or JSON files. The `-n` flag specifies the number of iterations. ```bash # Run with global variables and an iteration data file (CSV or JSON) newman run examples/sample-collection.json \ -g globals.json \ -d iteration-data.csv \ -n 3 ``` -------------------------------- ### Accessing Newman Run Summary and Statistics Source: https://context7.com/postmanlabs/newman/llms.txt Use this snippet to run a Newman collection and access the `summary` object in the callback. It demonstrates how to log various statistics such as iterations, requests, tests, assertions, and scripts, along with response time and total bytes transferred. ```javascript const newman = require('newman'); newman.run({ collection: require('./sample-collection.json'), reporters: 'cli' }, function (err, summary) { if (err) { throw err; } // summary.run.stats — counters for each phase const stats = summary.run.stats; console.log('Iterations:', stats.iterations.total, '/', stats.iterations.failed, 'failed'); console.log('Requests: ', stats.requests.total, '/', stats.requests.failed, 'failed'); console.log('Tests: ', stats.tests.total, '/', stats.tests.failed, 'failed'); console.log('Assertions:', stats.assertions.total, '/', stats.assertions.failed, 'failed'); console.log('Scripts: ', stats.scripts.total, '/', stats.scripts.failed, 'failed'); // summary.run.timings — response time statistics (ms) const t = summary.run.timings; console.log(`Response time avg/min/max: ${t.responseAverage}/${t.responseMin}/${t.responseMax} ms`); console.log(`DNS avg/min/max: ${t.dnsAverage}/${t.dnsMin}/${t.dnsMax} ms`); console.log(`First byte avg/min/max: ${t.firstByteAverage}/${t.firstByteMin}/${t.firstByteMax} ms`); // summary.run.transfers — bytes received console.log('Total response bytes:', summary.run.transfers.responseTotal); // summary.run.failures — array of failure descriptors summary.run.failures.forEach(failure => { console.error(`[${failure.at}] ${failure.source && failure.source.name}: ${failure.error.message}`); }); // summary.run.executions — per-request detail (request, response, assertions) summary.run.executions.forEach(exec => { const status = exec.response && exec.response.status; const time = exec.response && exec.response.responseTime; console.log(`${exec.item.name}: HTTP ${status} in ${time}ms`); if (exec.assertions) { exec.assertions.forEach(a => { console.log(` [${a.error ? 'FAIL' : 'PASS'}] ${a.assertion}`); }); } }); // summary.collection / .environment / .globals — Postman Collection SDK objects console.log('Collection:', summary.collection.name); }); ``` -------------------------------- ### Run Newman with Different Mount Path Source: https://github.com/postmanlabs/newman/blob/develop/docker/images/ubuntu/README.md Run Newman, mounting collections to a different path and specifying that path in the command. Ensure the volume mount path matches the collection path. ```terminal docker --volume="/home/postman/collection:/etc/newman" -t postman/newman:ubuntu run JSONBlobCoreAPI.json.postman_collection -r json --reporter-json-export newman-report.json ``` -------------------------------- ### Generate CSR from Private Key Source: https://github.com/postmanlabs/newman/blob/develop/test/fixtures/ssl/SSL.md Use this command to create a Certificate Signing Request (CSR) from an existing private key. ```bash openssl req -new -key server.key -out server.csr ``` -------------------------------- ### Load and Export Cookie Jar in Newman Source: https://context7.com/postmanlabs/newman/llms.txt Configure Newman to load cookies from a JSON file and export them after a run. Alternatively, pass a live CookieJar instance. ```javascript const newman = require('newman'); const { CookieJar } = require('@postman/tough-cookie'); // Load from serialized JSON file newman.run({ collection: require('./sample-collection.json'), cookieJar: './cookies.json', exportCookieJar: './out/cookies-after.json' }, function (err, summary) { if (err) { throw err; } console.log('Run complete with persistent cookies.'); }); // Pass a live CookieJar instance const jar = new CookieJar(); newman.run({ collection: require('./sample-collection.json'), cookieJar: jar }, function (err) { if (err) { throw err; } // jar now contains cookies set during the run }); // CLI equivalent: // newman run collection.json \ // --cookie-jar ./cookies.json \ // --export-cookie-jar ./out/cookies-after.json ``` -------------------------------- ### Check Postman API Key Alias Environment Variable Source: https://github.com/postmanlabs/newman/wiki/Using-Newman-with-the-Postman-API Verifies the current value of the `POSTMAN_API_KEY_ALIAS` environment variable. ```bash $ echo $POSTMAN_API_KEY_ALIAS ``` ```bash $ echo %POSTMAN_API_KEY_ALIAS% ``` -------------------------------- ### Login to Postman API Source: https://github.com/postmanlabs/newman/wiki/Using-Newman-with-the-Postman-API Stores the Postman API Key for future access to Postman-Cloud resources. If a key already exists, this command allows storing a new key as an alias. ```bash $ newman login ``` -------------------------------- ### Run Postman Collection via Postman API Source: https://github.com/postmanlabs/newman/blob/develop/README.md Execute a Postman collection using its API URL and an associated environment. This requires obtaining the collection and environment URIs first. ```console $ newman run "https://api.getpostman.com/collections/$uid?apikey=$apiKey" \ --environment "https://api.getpostman.com/environments/$uid?apikey=$apiKey" ``` -------------------------------- ### Disable Colored Output in CLI (V3 vs V4) Source: https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md Shows how to disable colored output in the Newman CLI. V3 used a --no-color flag, while V4 uses --color off. ```bash # V3 command $ newman run collection.json --no-color ``` ```bash # V4 equivalent $ newman run collection.json --color off ``` -------------------------------- ### Run Newman Collection Programmatically Source: https://context7.com/postmanlabs/newman/llms.txt Use `newman.run()` to execute a Postman collection with extensive configuration options. The callback handles errors and provides a summary of the run. ```javascript const newman = require('newman'); newman.run({ collection: require('./sample-collection.json'), // Collection object, file path, or URL environment: './environment.json', // Environment file path, URL, or object globals: './globals.json', // Globals file path, URL, or object iterationData: './data.csv', // CSV or JSON data file for iterations iterationCount: 3, // Number of iterations folder: ['Auth Tests', 'User API'], // Specific folders to run reporters: ['cli', 'json'], // Active reporters reporter: { json: { export: './results/report.json' } // Reporter-specific options }, envVar: [ { key: 'baseUrl', value: 'https://api.example.com' }, { key: 'token', value: process.env.API_TOKEN } ], globalVar: [ { key: 'retryCount', value: '3' } ], timeoutRequest: 10000, // Request timeout in ms timeoutScript: 5000, // Script timeout in ms timeout: 60000, // Total run timeout in ms delayRequest: 200, // Delay between requests in ms bail: false, // Stop on first failure insecure: false, // Skip SSL verification ignoreRedirects: false, // Do not auto-follow 3xx redirects color: 'auto', // CLI color: 'auto' | 'on' | 'off' workingDir: '/app/test-assets', // Working directory for file reads insecureFileRead: true, // Allow reads outside workingDir suppressExitCode: false, // Override process exit code verbose: true // Show detailed request/response info }, function (err, summary) { if (err) { console.error('Run error:', err.message); process.exit(1); } const { stats, failures, timings } = summary.run; console.log(`Requests: ${stats.requests.total} total, ${stats.requests.failed} failed`); console.log(`Assertions: ${stats.assertions.total} total, ${stats.assertions.failed} failed`); console.log(`Duration: ${timings.completed - timings.started}ms`); if (failures.length) { failures.forEach(({ error, at, source }) => { console.error(`FAIL [${at}] ${source && source.name}: ${error.message}`); }); process.exit(1); } console.log('All tests passed.'); }); ```