DEV Community

Cover image for Beginners guide to Writing Newman API Tests
Jeffery Osei
Jeffery Osei

Posted on

Beginners guide to Writing Newman API Tests

Hello there 🤓,

I trust you are well and keeping safe, today we will be doing a little JavaScript-ing with Postman's Newman tool! 😍.

So to start with, I just want to say, Newman is an awesome Postman command line tool. Newman basically helps you automate your Postman tests with ease.

In my previous post here, I explained in layman's terms how to write basic Postman tests for your APIs and today we will be running something similar using Newman but with a public Space-X Api which I have gone ahead to tweak for this test (added test cases to assert their responses).

Let's go! 🏃🏽‍♂️



REQUIREMENTS 📝

  • For windows users, open up Powershell
  • For Linux users, use this key combination to start your terminal Ctrl + Shift + T
  • For Mac users, Open the search prompt Command + Space (bar) and type terminal, press enter to open it up.


STEPS 🪜



💻 Install NodeJS :

Installing NodeJS is pretty straight forward, visit their download page here, download your platform version to install. Kindly make sure its version 10 or higher.

After installing, head to your Terminal and enter the command below to check if everything is good to go.

node -v && npm -v
Enter fullscreen mode Exit fullscreen mode

You should see an output like the one below:

Node and NPM version

📝 If your versions printed do not match the above, do not worry, you are good to go! 💪🏽.



📁 Create Folder Structure :

Before we can run our tests programmatically we need to setup our working directories, run the command below in your terminal to proceed.

mkdir newman-training && cd newman-training
Enter fullscreen mode Exit fullscreen mode

This will create our working directory and change directory into it.



🤸‍♂️ Install Postman's Newman :

Now that we have our working directory setup, we need to install newman and a couple more NodeJS modules we need, use the command below.

npm install newman request rimraf newman-reporter-csv newman-reporter-html newman-reporter-htmlextra --save --force
Enter fullscreen mode Exit fullscreen mode

If everything went well you should see an output similar to the one below:

Newman and Request install



💥 Run Newman Test :

Now that we have Newman installed and ready, lets start scripting, use the command below to create the file and edit using nano in your terminal.

nano postman.js
Enter fullscreen mode Exit fullscreen mode

Now copy and paste the code snippet below in your terminal.

const fs = require("fs"); // require node file system
const rimraf = require("rimraf"); // require rm package
const request = require("request"); // require node js request
const newman = require("newman"); // require newman
const postman_collection_url =
  "https://raw.githubusercontent.com/clonne101/newman-training/main/space_x.json";
const postman_collection_name = "space_x.json";

// method responsible for obtaining our collection
function getCollectionFile(postman_collection_url, postman_collection_name) {
  return new Promise((resolve, reject) => {
    // check if postman collection json exist, if not download it
    fs.readFile("./" + postman_collection_name, function (err) {
      if (err) {
        // write to log
        console.log(
          postman_collection_name + " collection file not found, downloading..."
        );

        // get the file contents
        request(postman_collection_url, function (error, response, body) {
          if (!error && response.statusCode == 200) {
            // write to log
            console.log("Retrieved file successfully, saving...");

            // write to file
            fs.writeFile(postman_collection_name, body, function (fail) {
              if (fail) {
                console.log(fail);
                reject(fail);
              }

              // write to log
              console.log(postman_collection_name + " saved successfully!");
              resolve(true);
            });
          } else {
            console.log(err);
            reject(err);
          }
        });
      } else {
        // write to log
        console.log(postman_collection_name + " exist proceeding...");
        resolve(true);
      }
    });
  });
}

// promise declaration
const promises = [
  getCollectionFile(postman_collection_url, postman_collection_name),
];

// promise resolver
Promise.all(promises).then((result) => {
  if (result) {
    // add space
    console.log("\n");

    // remove reporter folder
    rimraf("./newman", function () {
      console.log("Old newman reporters removed successfully...");
    });

    // call newman.run to pass `options` object and wait for callback
    newman.run(
      {
        collection: require("./" + postman_collection_name),
        reporters: ["html", "csv", "json"],
      },
      function (err) {
        if (err) {
          throw err;
        }
        console.log("\nCollection run complete!\n");
      }
    );
  }
});
Enter fullscreen mode Exit fullscreen mode

To save and close the file, use these keyboard combination Ctrl + x and then Y and lastly press your Enter key.

Lets quickly recap on what the file we just created contains, so we begin by requiring modules we need, we then went ahead to download our postman collection json file, saved it and then went ahead to run newman which upon completion outputs the results to .csv, .json and .html files into a newman folder for review.

Now to run the test, use the command below and you should get a response similar to the screenshot below.

node postman.js
Enter fullscreen mode Exit fullscreen mode

Newman Test Results



🎉 View Results :

Now that we all done, lets go see how we did on our tests (Wheew! 😅). Head to your file explorer or finder if you are on a Mac. Navigate to your newman-training folder and in there you would find the newman folder which contains our results.

Double-click on the .html file and you should have a view like the one below show up in your default browser! 😍.

Newman reporter results

In the above screenshot we see all our test cases passed and further more summary for each of our request.



Awesome! 👏, now we are all done, I urge you to try out some more Newman examples in your free time, Postman offers Public APIs you can play with. Happy Newman Testing 😉.



🐱‍💻 Resources:

Kindly find below links to resources you can use as a guide and also links to my social media should you need to make contact for any challenges you might have or just to have a short conversation if you are starting out.

Postman: https://www.postman.com
Postman Public APIs: https://www.postman.com/explore
Postman Learning: https://learning.postman.com/docs/getting-started/introduction
Postman Newman: https://learning.postman.com/docs/running-collections/using-newman-cli/command-line-integration-with-newman/

GitHub repository for the test code:
https://github.com/clonne101/newman-training

Social Links:
Website: https://jefferyclonne.com
Twitter: https://twitter.com/@clonne101
LinkedIn: https://www.linkedin.com/in/jeffery-osei-551626a6

Top comments (0)