NashTech Blog

Accelerate API Testing with Azure Pipelines: Best CI Practices

Table of Contents

Introduction

In the current landscape of web development, it is of utmost importance to guarantee the dependability and efficiency of APIs. Automated testing assumes a pivotal role in upholding the quality and uniformity of APIs, and the integration of these tests into CI/CD pipelines such as Azure DevOps further strengthens the process. This blog will briefly discuss the effective methods of API testing.

Azure Pipeline: An Overview of API Testing

API testing is the process of validating that the APIs fulfil the expected functionality, reliability, performance, and security requirements.

This service, offered by Azure DevOps, enables us to consistently build, test, and deploy applications.

By integrating API tests into our Azure Pipeline, we can ensure that any modifications made to our codebase do not disrupt the existing API functionalities.

What is the significance of Automated API Testing?

Automating API testing provides a multitude of advantages:

  • Reliability: Automated tests are consistent and run uniformly each time, minimising the possibility of human mistakes.
  • Productivity: Automated tests can be carried out swiftly without the need for manual involvement, thus conserving time and resources.
  • Timely Identification: Problems can be detected at an early stage in the development process, averting expensive corrections in the future.
  •  Incorporation: Automated tests can be smoothly integrated into CI/CD pipelines, guaranteeing ongoing quality assessments.

Azure Pipelines: Flow diagram

API testing

This diagram illustrates the Continuous Integration and Continuous Deployment (CI/CD) process in software development.

Creating a work environment

Before exploring the Azure Pipeline setup, we must establish a fundamental Node.js project for conducting API testing using Playwright.

Create a Node.js Project

Start by creating a new directory for the project and initialising it using npm.

mkdir api-test
cd api-test
npm init -y

Install the necessary packages.

Let’s proceed with installing the essential packages required for API testing.

  • Playwright is used for browser automation and API testing.
  • Axios is a promise-based HTTP client that makes API requests.
  • Mocha is a testing framework.
  • Chai is an assertion library.

Develop a Simple Test Script

Moving on, establish a folder for testing materials and generate a document specifically for API testing procedures.

mkdir test 

touch test/api.test.js

Revise test/api.test.js to add a fundamental API test.

const {test, expect} = require('@playwright/test');
 const axios = require('axios');
 test('GET request to JSONPlaceholder', async () => {
   const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
   expect(response.status).toBe(200);
   expect(response.data).toHaveProperty('id', 1);
 });

Setting up Azure Pipeline

Additionally, after setting up the Node.js project, the subsequent task involves setting up an Azure Pipeline to execute the tests. We should follow the instructions below to create and configure the pipeline.

Create a New Pipeline

Within the Azure DevOps project, go to Pipelines and initiate a new pipeline. Select the repository and configure the pipeline to utilise a YAML file.

Define the Pipeline in YAML

Generate a file named azure-pipelines.yml in the main directory of the project and include the subsequent configuration:

trigger: - main 

pool: vmImage: 'ubuntu-latest' 

steps: 

- task: UseNode@2 

inputs: 

version: '14.x' 

displayName: 'Install Node.js' 

- script: | npm install 

 displayName: 'Install dependencies' 

- script: | npx playwright install 

 displayName: 'Install Playwright browsers'
- script: | 

npx mocha test/api.test.js 

 displayName: 'Run API tests'
This setup outlines the subsequent procedures:

Trigger: Indicates that the pipeline is to be executed upon modifications to the main branch.

Pool: Specifies the virtual machine image to be utilised for the build agent.

Procedures:

Install Node.js.

Create projects and resolve dependencies.

Set up Playwright browsers.

Execute the API tests using Mocha.

Ensure to commit changes and then proceed to push them to the repository
git add. 

git commit -m "Add API testing setup" 

git push origin main

Initiating this action will prompt the pipeline to commence running and performing API tests.

Improving Test Coverage

To enhance the reliability and thoroughness of API tests, it is recommended to expand the coverage by testing various HTTP methods such as GET, POST, PUT, and DELETE.

For instance:

test('POST request to JSONPlaceholder', async () => { 

const response = await axios.post('https://jsonplaceholder.typicode.com/posts', { 

title: 'foo', 

body: 'bar', 

userId: 1

 }); 

expect(response.status).toBe(201); 

expect(response.data).toHaveProperty('id');

 });
Parameterized tests

It is a useful tool for executing the same test with various inputs. One way to achieve this is by utilising Mocha’s ‘describe‘ and ‘it’ functions.

const testCases = [ 

{ id: 1, title: 'foo' }, 

{ id: 2, title: 'bar' }

 ]; 

describe('Parameterized API tests', () => { 

testCases.forEach(({ id, title}) => {

 it(`should return post with id ${id}`, async () => { 

const response = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`); 

expect(response.status).toBe(200); 

expect(response.data).toHaveProperty('title', title); 

}); 

}); 

});
Engaging Environmental Variables

It is recommended to store sensitive information such as API keys in environment variables in order to maintain the security of tests.

const API_KEY = process.env.API_KEY; test('GET request with API key', async () => { 

const response = await axios.get('https://api.example.com/data', { 

headers: { 'Authorization': `Bearer ${API_KEY}` }

 }); 

expect(response.status).toBe(200); 

});

Within the pipeline setup, we can securely establish these environment variables.

- script: | 

API_KEY=$(API_KEY) npx mocha test/api.test.js 

 displayName: 'Run API tests with environment variable'
Managing Tasks with Different Timings

Consequently, make sure that our tests can correctly handle asynchronous operations. By utilising the async/await syntax and implementing appropriate error-handling techniques.

test('GET request with error handling', async () => { 

try { 

const response = await axios.get('https://jsonplaceholder.typicode.com/invalid-endpoint'); 

expect(response.status).toBe(404); 

} catch (error) { 

expect(error.response.status).toBe(404); 

}

 });

Conclusion

Basically, automating the testing of APIs and integrating it into an Azure Pipeline guarantees the consistent and efficient testing of our APIs. Meanwhile, by utilising Node.js and Playwright, we can establish robust and adaptable tests that encompass various aspects of our API’s functionality. Through the following steps provided in this blog, we can create a seamless CI/CD workflow that enhances the reliability and performance of our APIs.

Hence, by conducting continuous testing on our APIs, we can identify issues at an early stage, ensure the release of high-quality software, and maintain the trust of our users.

package com.nashtech.tdm.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

Picture of Ankit Kumar

Ankit Kumar

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top