Design API Automation Using Newman & Integrate it on Jenkins

ShahNilay
4 min readJan 30, 2024

--

Part 1: Design API Automation

source: https://blog.testproject.io/2020/03/31/rest-api-testing-using-postman-newman-guide/

Overview

API automation is a crucial aspect of modern software development and testing. It ensures that the application’s APIs function as intended, facilitating continuous integration and delivery.

Purpose of API Automation

The purpose of API automation is to validate the functionality, reliability, and performance of APIs throughout the development lifecycle. Automated testing helps catch issues early, speeds up the release process, and enhances overall software quality, where you can simply perform a quick sanity check of all application features using one single click after each deployment.

Newman Introduction

Newman is a command-line collection runner for Postman, allowing the execution of Postman collections directly from the command line. It is a powerful tool for automating API tests, providing features for test scripting, request chaining, and test report generation.

Prerequisites

Before using Newman, ensure you have Node.js and npm installed on your machine. Additionally, have a Postman account to create and manage collections.

Install Newman globally using the npm package manager:

npm install -g newman

Basic Configuration

Create a Postman collection and export it as a JSON file. This file will be used by Newman for test execution.

Create API Test Cases

  1. Test Script: Utilize the powerful JavaScript-based scripting capabilities in Postman for creating versatile and dynamic API tests.
  2. Request Methods: Define various HTTP request methods (GET, POST, PUT, DELETE) to simulate different API interactions.
  3. Assertions: Implement assertions to validate API responses, ensuring the expected outcomes match the actual results.
  4. Variables: Use variables to parameterize your requests and make your tests reusable and easily maintainable.

Organizing Test Suites

  1. Collection Structure: Organize your API tests into logical collections to manage and execute them efficiently.
  2. Folder Structure: Group related tests into folders, providing a hierarchical structure for better organization.
  3. Environment Variables: Leverage environment variables to manage dynamic data across different testing environments.

Running Tests with Newman

create index.js file inside folder structure.

const newman = require('newman');

// Define the collection and environment file paths
const collectionFile = './TestSuiteFilename.postmanCollection.json';
const environmentFile = './EnvFilename.postmanEnvironment.json';

// Define the options for the Newman run
const options = {
collection: require(collectionFile),
environment: require(environmentFile),
reporters: ["cli", "htmlextra"], // types of reports which one want to generate.
};

// Run Newman
newman.run(options, function (err) {
if (err) {
console.error('Newman run encountered an error:', err);
process.exit(1); // Exit with a non-zero code to indicate an error
} else {
console.log('Newman run completed successfully');
process.exit(0); // Exit with code 0 to indicate success
}
});

Detailed documentation can be found here.

Part 2: Design Jenkins Pipeline

Overview:

This documentation guides you through the process of creating a Jenkins job that involves running a pipeline with multiple stages and sending an email notification upon completion. The email will include an HTML file attachment.

Prerequisites:

  • Jenkins installed and running
  • Jenkins plugins:
    1. NodeJS
    2. Email Extension Plugin

Steps:

1. Install Required Plugins:

Make sure the NodeJS and Email Extension plugins are installed on your Jenkins instance.

2. Configure NodeJS:

In Jenkins, navigate to Manage Jenkins > Global Tool Configuration. Find the NodeJS section and add a NodeJS installation named 'NodeJS-16' (or your preferred version). Ensure the installation is automatically installed.

3. Create a Jenkins Pipeline Job:

  1. Go to the Jenkins dashboard.
  2. Click on New Item to create a new job.
  3. Enter a name for your job (e.g., PipelineWithEmail).
  4. Choose Pipeline as the job type.
  5. Click OK to create the job.

4. Configure Pipeline Script:

In the job configuration:

pipeline {
agent any

environment {
NODEJS_HOME = tool 'NodeJS-16'
PATH = "${env.NODEJS_HOME}/bin:${env.PATH}"
}

stages {
stage('Git Pull') {
steps {
script {
// Assuming you have Git installed in your Jenkins environment
git branch: 'master', url: 'your newman github url'
}
}
}

stage('Install Node.js') {
steps {
script {
// Ensure the NodeJS tool installation 'NodeJS-16' is available
// You need to configure this tool installation in Jenkins
// Navigate to Jenkins > Manage Jenkins > Global Tool Configuration
// Add NodeJS-16 with the desired Node.js version
// Replace 'NodeJS-16' with your configured tool installation name
def nodejsTool = tool 'NodeJS-16'

// Add Node.js binary folder to PATH
env.PATH = "${nodejsTool}/bin:${env.PATH}"
}
}
}

stage('Print Node.js Version') {
steps {
script {
// Print Node.js version to verify the installation
sh 'node --version'
}
}
}

stage('Run npm install') {
steps {
script {
sh 'npm install'
}
}
}

stage('Run Node.js Application') {
steps {
script {
// Replace 'index.js' with your actual entry point file
sh 'node index.js'
}
}
}
}

post {
always {
// Archive the HTML file for later use
archiveArtifacts artifacts: 'detailedTestReport.html', fingerprint: true

// Send email notification with the attached HTML file
emailext subject: 'Jenkins Pipeline Completed',
// body: 'The Jenkins Pipeline has been completed successfully.',
body: readFile(file: 'detailedTestReport.txt').trim(),
to: 'receiver@email.com',
attachmentsPattern: 'detailedTestReport.html',
mimeType: 'text/html'
}
}
}

This pipeline script creates an HTML file during the build and sends an email with the HTML content as the body and an attached HTML file.

5. Save and Build:

Save the job configuration and manually trigger a build to test the pipeline.

6. Verify Email Notification:

After the build completes, check your email inbox for the email notification with the attached HTML file.

Conclusion:

You’ve successfully created a Jenkins pipeline job that generates an HTML file and sends an email notification with the HTML content as the body and an attached HTML file. Customize the pipeline script and configurations as needed for your specific use case.

--

--

ShahNilay
ShahNilay

No responses yet