Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Mar 9, 2021

API Testing 'A Beginners View': Response Validation With Assertions | Quick Guide on Assertions

The most important step in any API development is to check its functionality whether it is constructed to simulate the use of the API by end-user applications and fulfill the provided business requirements. There are several API testing frameworks and tools for getting the job done. Postman is one such tool that is handy and easy to use and offers features like create and send any HTTP requests, write test cases to validate response data, response times, analyze the responses sent by the API, create integration test suites and integrate with build systems.

Today we will discuss the commonly used Assertions while validating responses in POSTMAN.

Before jumping into the Test Scripts, let’s know some facts on Assertions.

Assertions: Assertion is nothing but code that can be used to check or analyze the response that is received from the server. An assertion is a code written in javascript in Postman that is executed after receiving the response. Assertions help us to assert that expected and actual values should match during a test run. If the actual and expected values don't match, then the test will fail with the output pointing to the failure.

Test cases in Postman:
(Note: In the Postman app, the request builder at the top contains the Tests tab where you write your tests. The response viewer at the bottom contains a corresponding Test Results tab where you can view the results of your tests)

To start building test cases quickly, commonly-used snippets are listed below.
Response to be asserted:
[
    {
        "type": "configuration/entityTypes/HCP",
        "tags": [
            "Jency Test Data",
            "Integration Testing",
            "FCQA"
        ],
        "attributes": {
            "Country": {
                "value": "Brazil"
            },
            "TypeCode": {
                "value": "Nurse"
            },
            "FirstName": {
                "value": "Daniele"
            },
            "LastName": {
                "value": "Bedward 2021-03-09 03:55:47"
            },
            "Prefix": {
                "value": "MISS."
            },
            "Gender": {
                "value": "Polygender"
            },
            "StatusIMS": {
                "value": "Active"
            },
            "PresumedDead": {
                "value": "false"
            },
            "InternationalHCP": {
                "value": "FALSE"
            },
            "ClinicalTrials": {
                "value": "false"
            },
            "PrivacyPreferences": [
                {
                    "value": {
                        "OptOut": {
                            "value": "false"
                        },
                        "AllowedToContact": {
                            "value": "false"
                        },
                        "PhoneOptOut": {
                            "value": "false"
                        },
                        "EmailOptOut": {
                            "value": "false"
                        },
                        "FaxOptOut": {
                            "value": "false"
                        },
                        "VisitOptOut": {
                            "value": "false"
                        },
                        "TextMessageOptOut": {
                            "value": "false"
                        },
                        "MailOptOut": {
                            "value": "false"
                        },
                        "RemoteOptOut": {
                            "value": "false"
                        },
                        "OptOutOneKey": {
                            "value": "false"
                        },
                        "KeyOpinionLeader": {
                            "value": "false"
                        },
                        "ResidentIndicator": {
                            "value": "false"
                        }
                    }
                }
            ],
            "Specialities": [
                {
                    "value": {
                        "SpecialtyType": {
                            "value": "Primary"
                        },
                        "Specialty": {
                            "value": "ENDOSCOPY"
                        },
                        "Rank": {
                            "value": 1
                        },
                        "PrimarySpecialtyFlag": {
                            "value": "true"
                        }
                    }
                }
            ],
            "ValidationStatus": {
                "value": "Valid"
            },
            "IsBlackListed": {
                "value": "false"
            },
            "RequiresAttention": {
                "value": "false"
            },
            "TriggerDCR": {
                "value": "false"
            },
            "Address": [
                {
                    "value": {
                        "PrimaryAffiliation": {
                            "value": "TRUE"
                        },
                        "AddressType": {
                            "value": "Private Practice"
                        },
                        "Country": {
                            "value": "Brazil"
                        },
                        "AddressLine1": {
                            "value": "100 Main Street"
                        },
                        "City": {
                            "value": "Rio de Janeiro"
                        },
                        "StateProvince": {
                            "value": "RJ"
                        },
                        "Zip": [
                            {
                                "value": {
                                    "Zip5": {
                                        "value": 10000
                                    }
                                }
                            }
                        ],
                        "VerificationStatus": {
                            "value": "Partially Verified"
                        },
                        "ValidationStatus": {
                            "value": "Valid"
                        },
                        "Status": {
                            "value": "Active"
                        },
                        "AVC": {
                            "value": "P22-I44-P2-100"
                        }
                    }
                }
            ]
        }
    }
]
Assertions to the above response is as below:
var resp = JSON.parse(responseBody);
console.log(resp);

//assert response time
pm.test("Response time Check", function () {
     pm.expect(pm.response.responseTime).to.be.below(3000);
     pm.expect(pm.response.responseTime).to.be.above(500);
});

//assert response status code
pm.test("Response is OK", function () 
{
    pm.response.to.have.status(200);
});
//assert - For checking status being BAD REQUEST
pm.test("Bad Request Check", function () {
     pm.response.to.not.be.badRequest;
});

// assert on response and response type
pm.test("Response should be okay to process", function () { 
    pm.response.to.not.be.error; 
    pm.response.to.be.json;
});

// assert on Response Header
pm.test("Content-Type is present", function () {
     pm.response.to.have.header("Content-Type");
});

//assert on multiple status code
pm.test("Successful POST request", function () {
     pm.expect(pm.response.code).to.be.oneOf([200,201,202]);
});

//assert on an array
for (var i = 0;i<resp[0].tags.length;i++) 
{
    console.log("Length of array is: " + resp[0].tags.length);
    console.log("Index Value during iteration is: " + i);
    pm.test("Tag is: " + resp[0].tags[i], function () 
    {
        pm.expect((resp[0].tags[i]) != null).to.be.true;
    });
    console.log("Tag is: " + resp[0].tags[i]);
}

//compare value of a response with an already defined variable
// Getting values from response
var FirstName = resp[0].attributes.FirstName;
// Saving the value for later use
pm.globals.set("FirstName", FirstName);
pm.test("Variable usage check", function () {
    pm.expect(resp[0].attributes.FirstName).to.eql(pm.globals.get("FirstName"));
});

You can also write your own custom tests in JavaScript using "Chia Assertion Library": Click Me.

Note: The above snippet is appended in my public Collection “API Testing 'A Beginners View'”

This posts will be continued with more "Assertions" in the coming days…

Until then…
Happy Testing 😇

Nov 4, 2020

API Testing 'A Beginners View': JavaScript - Array.prototype.find() and Array.prototype.findIndex()

Array.prototype.find()

The find() method returns the value of the first value of the array to be tested which passes the condition specified. It checks all the values in the array and whichever value satisfies the condition first would be picked and displayed in the output. If the value is not found it returns undefined.


Let's check out some examples to understand it better;


Example1:  Using Arrow Function

Response Body:

{
"args": {},
"data": {
"FirstName": [
{
"value": "{{RandomFirstName}}"
}
],
"Specialty": [
{
"name": "NEUROLOGY",
"experience": "2"
},
{
"name": "Dermatology",
"experience": "2"
},
{
"name": "Ortho",
"experience": "2"
}
]
},
"files": {},
"form": {},
"headers": {
"x-forwarded-proto": "https",
"x-forwarded-port": "443",
"host": "postman-echo.com",
"x-amzn-trace-id": "Root=1-5fd86d42-7d196eb86048629c2b3ea2ca",
"content-length": "288",
"content-type": "application/json",
"user-agent": "PostmanRuntime/7.26.8",
"accept": "*/*",
"cache-control": "no-cache",
"postman-token": "065034d3-4e05-4d1b-872d-382f2579524d",
"accept-encoding": "gzip, deflate, br",
"cookie": "sails.sid=s%3A6n5cRYOmPZd0CgxhkfCCHO6rFlTzSFfw.9ZTgkbZcBTzwWSiBLXKE%2BktjLAb6IdSuIMFNxLxnK9Y"
},
"json": {
"FirstName": [
{
"value": "{{RandomFirstName}}"
}
],
"Specialty": [
{
"name": "NEUROLOGY",
"experience": "2"
},
{
"name": "Dermatology",
"experience": "2"
},
{
"name": "Ortho",
"experience": "2"
}
]
},
"url": "https://postman-echo.com/post"
}


Test Script:

//Using function how to find an object in array by 'find' method
var resp = JSON.parse(responseBody);
function find_result1(value) { 
  return value.name === 'Dermatology';
}
console.log(array_value.find(find_result1));

Console Output:


Example 2: Using function how to find an object in array by 'find' method

Test Script:

var resp = JSON.parse(responseBody);
console.log(resp);
const array_value = resp.data.Specialty;
console.log(array_value);
//Using arrow function how to find an object in array by 'find' method
const result = array_value.find( ({ name }) => name === 'NEUROLOGY' );
console.log(result);

Console Output:


The explanation for the above examples:

The above example is based on an array that has three values to it as below:

I have used the ‘find’ method in two different ways to identify the object that satisfies the conditions:

  • name === 'NEUROLOGY'
  • name === 'Dermatology'

After execution, the output returns the value which satisfied the condition.


Array.prototype.findIndex()

In continuation of the above feature, if we need to know the index of the element that we found, this can be done by the findIndex() method. It returns the index of the first element in the array that satisfies the condition we provide. If no element passes the test condition, it returns -1.


Example: In continuation to the above snippet when we add the below code, index will be returned

//How to find the index of the result

//Using function how to find an object in array by 'find' method
function find_result1(value) { 
  return value.name === 'Dermatology';
}
console.log(array_value.find(find_result1));
console.log(array_value.findIndex(find_result1)); //this is using function

Console Output:


Hope this was useful 😇
Happy Learning 😇