Running a postman collection with newman alongside plugins (newman-reporter-htmlextra | pdf-export | pdf-parse)
Tags: postman, newman, htmlextra
Published: 2022-06-14 09:52:44

> **This guide is for running a collection of api tests, generating html report of results and generating pdf file from the API body response (_the pdfData_) from base64 encoded string.**

**What is covered with this tutorial:**
**1)** Running postman collection with newman.
**2)** Custom environment location with newman.
**3)** **Reporter-htmlextra** with custom template location to export the test result report.
**4)** **PDF Export** - get the response object search for binary encoded pdf string, generate decoded pdf file and place it with the report.html file in a newly created folder by current date.
**5)** **PDF Parse** - the generated pdf file - access it and search for specific metadata or custom text content or string from that pdf.

**We may start now: 👀**
Let's assume you already have a postman collection of requests and the next step is to export that collection.json file in the specific directory where the following steps are needed.

**Requirements:**
**1)** Postman application installed (for exporting the collection)
**2)** NodeJs installed ([https://nodejs.org/en/download/](https://nodejs.org/en/download/))

**Setup:**
**1)** Setup a local path on your pc and inside project directory open terminal/cmd and do command `npm init`
- this will generate the package.json file.

**2)** Install newman ` npm i newman --save-dev `
**3)** Install newman-reporter-htmlextra ` npm i newman-reporter-htmlextra --save-dev `
**4)** Install pdf-parse ` npm i pdf-parse --save-dev `
**5)** Install date formatter ` npm i dateformat@1.0.2-1.2.3 --save-dev `
**6)** Create index.js file in the root project and let's start filling it with code.

```javascript
const dateFormat = require('./node_modules/dateformat/lib/dateformat.js');
const fs = require('fs');
const now = new Date();
const currentData = dateFormat(now, "dd.mm.yyyy HH.MM");
const newman = require('newman');
// add the path to your exported postman collection
const collection = require('./Newman.postman_collection.json');
const reportName = 'report.html';

newman.run({
    collection,
    // if you use environments from different json file excluded from the postman collection, otherwise comment it
    environment: `./environment/dev.json`,
    reporters: ['cli', 'htmlextra'],
    iterationCount: 1,
    reporter: {
        htmlextra: {
            // commented lines are the all possibilities available to be set for the report document
            export: `./${currentData}/${reportName}`,
            /*
            this is the original location of the template but can be copied modified, moved and linked to it
            if you don't specify template path will use the default one ./node_modules/newman-reporter-htmlextra/lib/dashboard-template.hbs
            */
            template: './node_modules/newman-reporter-htmlextra/lib/dashboard-template.hbs',
            // logs: true,
            // showOnlyFails: true,
            // noSyntaxHighlighting: true,
            // testPaging: true,
            browserTitle: "Newman report",
            title: 'Report - ' + currentData,
            titleSize: 5,
            // omitHeaders: true,
            // skipHeaders: "Authorization",
            // omitRequestBodies: true,
            // omitResponseBodies: true,
            // hideRequestBody: ["Login"],
            // hideResponseBody: ["Auth Request"],
            showEnvironmentData: true,
            // skipEnvironmentVars: ["API_KEY"],
            // showGlobalData: true,
            // skipGlobalVars: ["API_TOKEN"],
            // skipSensitiveData: true,
            // showMarkdownLinks: true,
            showFolderDescription: true,
            // timezone: "Australia/Sydney",
            // skipFolders: "folder name with space,folderWithoutSpace",
            // skipRequests: "request name with space,requestNameWithoutSpace",
            // displayProgressBar: true
        }
    }
}).on('request', (error, data) => {
    const requestName = data.item.name;
    const fileName = `${requestName}.pdf`;
    let content = data.response.stream.toString();

    /* You need to modify this in order to get the specific
 data of encoded string from your API response */
    let pdfEncodedString = JSON.parse(content).pdfData;

    if (error) {
        console.log(error);
        return;
    }

    if (JSON.parse(content).message === 'Forbidden') {
        console.log('There has been error. Get renewed access token!');
        return;
    }

    if (pdfEncodedString !== undefined) {

        if (!fs.existsSync(currentData)) fs.mkdirSync(currentData, { recursive: true });

        fs.writeFile(currentData + '/' + fileName, pdfEncodedString, 'base64', function (error) {
            if (error) {
                console.error(error);
            } else {
                const pdf = require('pdf-parse');
                let dataBuffer = fs.readFileSync(currentData + '/' + fileName);
                pdf(dataBuffer).then(function (data) {
                    /*  number of pages    
                    console.log(data.numpages);     
                    //number of rendered pages    
                    console.log(data.numrender);     
                    //PDF info    
                    console.log(data.info);     
                    //PDF metadata    
                    console.log(data.metadata);      
                    //PDF.js version     
                    check https://mozilla.github.io/pdf.js/getting_started/    
                    console.log(data.version);     PDF text    console.log(data.text);
                    */
                    console.log('Content: ', data.text);
                    console.log('Specific word: ', data.text.includes('some_text_you_want_to_find'));  // you can use any js logic here or regex
                    console.log('number of pages:', data.numpages);
                    console.log('number of rendered pages:', data.numrender);
                    console.log(data.info);
                });
            }
        });
    } else {
        console.log('Pdf encoded string not found in the body response')
    }
});

```

**7)** Running the script with the command ` node . ` inside the terminal window of the project root

- After command finishes the tests will be generated in a new folder by current date and time inside the root of project:
    - If some test fails then will be no visible pdf file in the folder.

<hr>
<p><i><b> For any questions or information about me you can reach out by scanning or clicking on the following qr code:</b></i></p>
<br>
<a href="http://delovski.net/qr" alt="find more about me"><img src="https://dev-to-uploads.s3.amazonaws.com/i/xtl2ad51u4zxctqvq8e2.PNG" alt="scan qr code to find more about me"/></a>