Beginners guide to Writing Newman API Tests
Tags: postman, newman, javascript, beginners
Published: 2020-12-04 00:31:17

Hello there 🤓,

I trust you are well and keeping safe, today we will be doing a little __JavaScript-ing__ with [Postman](https://www.postman.com)'s [Newman](https://github.com/postmanlabs/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](https://dev.to/clonne101/beginners-guide-to-writing-postman-api-tests-32a4), 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](https://documenter.getpostman.com/view/323124/TVmMgxMP) which I have gone ahead to tweak for this test *(added test cases to assert their responses)*.

Let's go! 🏃🏽‍♂️

<hr/><br/>

## REQUIREMENTS 📝
* For windows users, open up [Powershell](https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/starting-windows-powershell?view=powershell-7.1)
* 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.

<hr/><br/>

## STEPS 🪜
* [Install NodeJS](#chapter-1)
* [Create Folder Structure](#chapter-2)
* [Install Postman's Newman](#chapter-3)
* [Run Newman Test](#chapter-4)
* [View Results](#chapter-5)

<hr/><br/>

### 💻 Install NodeJS <a name="chapter-1"></a>: 
Installing NodeJS is pretty straight forward, visit their download page [here](https://nodejs.org/en/download/), 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.

```bash
node -v && npm -v
```
You should see an output like the one below:

![Node and NPM version](https://dev-to-uploads.s3.amazonaws.com/i/2k7z5lcgtx6c4vhe90lt.png)

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

<hr/><br/>

### 📁 Create Folder Structure <a name="chapter-2"></a>:
Before we can run our tests programmatically we need to setup our working directories, run the command below in your terminal to proceed.

```bash
mkdir newman-training && cd newman-training
```

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

<hr/><br/>

### 🤸‍♂️ Install Postman's Newman <a name="chapter-3"></a>:
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.

```bash
npm install newman request rimraf newman-reporter-csv newman-reporter-html newman-reporter-htmlextra --save --force
```

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

![Newman and Request install](https://dev-to-uploads.s3.amazonaws.com/i/4d7u1hrfmw15vqihulpl.png)

<hr/><br/>

### 💥 Run Newman Test <a name="chapter-4"></a>:
Now that we have Newman installed and ready, lets start scripting, use the command below to create the file and edit using [`nano`](https://en.wikipedia.org/wiki/GNU_nano) in your terminal.

```bash
nano postman.js
```

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

```javascript
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");
      }
    );
  }
});
```

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.

```bash
node postman.js
```

![Newman Test Results](https://dev-to-uploads.s3.amazonaws.com/i/6w70vfezechp9j5ysfm4.png)

<hr/><br/>

### 🎉 View Results <a name="chapter-5"></a>: 
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](https://dev-to-uploads.s3.amazonaws.com/i/fr65clu3g8uz2nl6accf.png)

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

<hr/><br/>

Awesome! 👏, now we are all done, I urge you to try out some more Newman examples in your free time, Postman offers [Public APIs](https://www.postman.com/explore) you can play with. Happy `Newman Testing` 😉.

<hr/><br/>

### 🐱‍💻 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