API Testing in Protractor

I have been trying to explain this API in a simple way but somehow I was having difficulty but finally got an explanation in simple terms, so if something is wrong with explanation please do forgive me.

socket-api-selenium

I hope You have seen this thing in your everyday life, if not ( at least you must be sure that this is not a lemon ).

This is an Indian electrical socket, if you are from another county then instead of circle rounds then you might have come across vertical ones.

Certainly, I am not an electrical engineer but Mechanical engineer

An API is nothing but similar to an electrical socket

This socket provides 240V power supply, we can connect electrical devices like fan, TV, Washing Machine, Radio, Air Conditioner and so on.

different-connections-to-api Similar to this socket is API exposes an URL, to which different websites can connect and those websites could be developed using different technologies. A Major use of the API is exposing and modifying the data.

Fan, RAdio, TV are developed for different purposes but they will connect to the same Socket and they will achieve their purpose either by adjusting the voltage.

Similarly, using API the developers will build their application and UI based on their website need and manipulate it.

standard-api-selenium Can you guess, Which take less time to execute UI or API ?
You are right, The one which doesn't have UIless i.e API.

It doesn't mean every website will have API, based on the functionalities developers use APIs, usage of API is solely dependent on the business.

Protractor Interview Questions

How API testing Works

API testing is not a big deal, as everyone says you have to test the URL and check the Response body and response status code.

Is it All about API Testing ? Nah, testing an URL is the first part of API Testing. API testing couple of stages ( I am not sure about the number of stages that is why mentioned 'couple').

API is tested in multiple stages but all these stages are solely dependent on your team and organization.

  1. Hit the API url for the given data (unique id or something)
  2. Check the database for the same data with hat unique id
  3. Navigate to the UI of the API and verify the details of the product
  4. Hit the API URL with required Operation, Operations could be Post, Put, Delete
  5. Hit the GET url of the API and verify the changes
  6. Test the database whether API operation is successful, and data is changed or removed
  7. Navigate to the UI of the API and verify the product details

We would be performing individual operations and once we learn we will learn API Testing processes, then we would be doing all above-mentioned scenario.

Inherited Locators in protractor

Our API URL for API Testing in protractor

I don't want my reader to depend on the third-party APIs, because of which I have created a dummy API (I am not a developer so please do expect some issues and error).

my-api-design I have created this API using the tutorial and example present on the Internet, this API has the following features.

  • This API is built using PHP and angular with reach
  • You can create products using this API
  • You can delete the created Product or exiting Products
  • You can edit new/Existing products
  • This API is not behind authentication
  • You can view all the products or specific products based on id, name, price but you cannot mix them.
  • You are not restricted to perform any operation on this API and it doesn't restrict sharing or performing changes
  • This API has a UI at : https://chercher.tech/sample/api-ui

Apart from these thanks to gitHub, and I want you to perform or test the functionalities of the API UI using the above URL so that you will be familiar with operations

The UI and the API both point to the same place in Db and the only change is how these calls the target.

It is something like we can call a person with the first name as well as with the second name if no other person is with the same name. But you cannot do the same thing with my name because 3 out of 10 people have my name. silly.

Below are few Endpoints of our API, these endpoints change from product to product and sometimes some products will have only one endpoint for all the urls

Sample API for GET all : https://chercher.tech/sample/api/product/read

Sample API for GET Specific: https://chercher.tech/sample/api/product/read?id=90

Sample API for PUT : https://chercher.tech/sample/api/product/create

Sample API for POST : https://chercher.tech/sample/api/product/update

Sample API for DELETE : https://chercher.tech/sample/api/product/delete

Manipulate the API using just URL bar :


Sample API for GET all : https://chercher.tech/sample/api/product/read

Sample API for GET Specific: https://chercher.tech/sample/api/product/read?id=50 instead of ?id you can also use name or price wit respective value, you must not use any single/Double quotes in url even for string parameters as well.

Sample API for PUT : https://chercher.tech/sample/api/product/create?name=xyz&description=desc of xyz&price=30

Sample API for POST : https://chercher.tech/sample/api/product/update?id=40&name=xyz&description=desc of xyz&price=30

Sample API for DELETE : https://chercher.tech/sample/api/product/delete?id=50

What is ElementArrayFinder

request npm module with protractor Jasmine with Typescript

Duck, duck, Duck I have been trying from afternoon to write an article on this API package in typescript but I was not able to do it.

Finally, I am writing this now, let's skin this topic.

Request package provides the capability to handle the API operations like

  • GET
  • POST
  • DELETE
  • PUT

This tutorial will help with both javascript and Typescript way of testing the API.

Install the request module using below npm command.


npm install request
install-mysql-database-node-protractor

pageLoadTimeout

GET method in API with Protractor

The GET method is used to extract information from the given server using a given URI. While using GET request, it should only extract data and should have no other effect on the data.

End Point : https://chercher.tech/sample/api/product/read

Below URl will only return the details for the id 90 :
End Point : https://chercher.tech/sample/api/product/read?id=90

done() is very very important, this is one will enable to integrate the request module with Typescript otherwise you cannot integrate request module.

function(done){ part in it block is also important to work with above mentioned point.


import { browser, element, by } from "protractor";
var Request = require("request");
describe("Errors in Protractor",function(){
  browser.ignoreSynchronization = true; // for non-angular websites
  it("Error handleing in protractor",function(done){
  
    Request.get({
      "headers": { "content-type": "application/json" },
      "url": "https://chercher.tech/sample/api/product/read?id=90"
      
      }, (error, response, body) => {
        if(error) {
            return console.dir(error);
        }
        console.dir("Body : ******");
        console.dir(JSON.parse(body));
        
        console.log("\n\n\nResponse Code ****:"+response.statusCode)
		expect(response.statusCode).toBe(200)
        // this below line took half day of research
        done();
    });  
  });
});
read-api-protractor

Limiting execution time in Jasmine

Put method in request with Protractor Typescript

Put method is different from get() method, put method creates details or resource the server/database.

It is up to the developer whether an end point API url support the both Create an Update or either of them, the API we are using in below example will create the resource but will not have the capability to update

When the target resource exists it overwrites that resource with complete new body. That is PUT method is used to CREATE or UPDATE a resource.

Status Codes of PUT

  • 201 OK: The request was successful, we updated the resource and the response body contains the representation.
  • 202 ACCEPTED: The request has been accepted for further processing, which will be completed sometime later.
put method is like an UPDATE query in SQL which inserts or updates a record depending upon whether the given record exists
put() method in API may return 201 status code with message 'Created' if everything is successful.

import { browser, element, by } from "protractor";
var Request = require("request");
describe("Errors in Protractor",function(){
  browser.ignoreSynchronization = true; // for non-angular websites
  it("api Testing in protractor",function(done){
  
    Request.put({
      "headers": { "content-type": "application/json" },
      "url": "https://chercher.tech/sample/api/product/create",
      "body": JSON.stringify({
        "name": "some stupid guy",
        "description": "90033"
      })
      
      }, (error, response, body) => {
        if(error) {
            return console.dir(error);
        }
        console.dir("Body : ******");
        console.dir(response.body);
        
        console.log("\n\nHeader ****:")
        console.log(response.headers)
        
        // this below line took half day of research
        done();
    });  
  });
});

Console output put-method-api-testing-protractor-request


Now just visit, UI of the api at https://chercher.tech/sample/api-ui api-ui-protractor-put-method-request-npm-package

Scope of Implicitly Wait

POST API Method in Request with protractor

"Post" means "after"; if you have a collection of entities and you tack a new one onto its end, you have posted to the collection.

You can't post an existing entity, and it's common (though not always required) to use the collection’s URI to post.

Status Codes of POST

  • 201 OK: The request was successful, we updated the resource and the response body contains the representation.
  • 202 ACCEPTED: The request has been accepted for further processing, which will be completed sometime later.
post method is like an INSERT query in SQL which always creates a new record in the database.

End Point: https://chercher.tech/sample/api/product/update

Every API will provide some unique parameter for every product, using that parameter we have to update the details for this example I would be using id Below program will update the details of the product which has id as 130


import { browser, element, by } from "protractor";
var Request = require("request");
describe("Errors in Protractor",function(){
  browser.ignoreSynchronization = true; // for non-angular websites
  it("api Testing in protractor",function(done){
  
    Request.post({
      "headers": { "content-type": "application/json" },
      "url": "https://chercher.tech/sample/api/product/update",
      "body": JSON.stringify({
		"id":"130",
        "name": "some stupid guy",
        "description": "90033",
		"price":"4500"
      })
      
      }, (error, response, body) => {
        if(error) {
            return console.dir(error);
        }
        console.dir("Body : ******");
        console.dir(response.body);
        
        console.log("\n\nHeader ****:")
        console.log(response.headers)
        
        // this below line took half day of research
        done();
    });  
  });
});

Verify whether details got updated or not, using API https://chercher.tech/sample/api/product/read api-post-method-selenium-rest-assured You might want to verify the Ui of the Api., Visit :
https://chercher.tech/sample/api-ui api0ui-post-method-selenium-rest-api

JavascriptExecutor

Delete method in API

DELETE- Removes data from the target resource/ database given by a URI.

Status Code of DELETE

  • 202 ACCEPTED: The request has been accepted for further processing, which will be completed sometime later.
  • 204 OK: The request was successful; the resource was deleted.
delete method is like a DELETE query in SQL which inserts or updates a record depending upon whether the given record exists
delete-api-rest-selenium

@Test
public void deleteDetails()
{   
	// request the server
	RequestSpecification reqSpec = RestAssured.given();
	
	JSONObject jo = new JSONObject();
	jo.put("id", "94");
	
	reqSpec.body(jo.toString());
	
	Response resp = reqSpec.delete("https://chercher.tech/sample/api/product/delete");
}		


Verify whether details got updated or not, using API : https://chercher.tech/sample/api/product/read You might want to verify the Ui of the Api, Visit : https://chercher.tech/sample/api-ui

PATCH

PATCH is used to partially update an existing entity with new information. You can’t patch an entity that doesn’t exist. You would use this when you have a simple update to perform, e.g. changing a user’s name.

patch method is like an UPDATE query in SQL which sets or updates selected columns only and not the whole row.

Handling Cookies

HTTP codes

HTTP Status Codes

Before diving into the communication with other APIs, let's review the HTTP status codes we may encounter during the process. They describe the outcome of our requests and are essential for error handling.

  • 1xx - Informational
  • 2xx - Success: These status codes indicate that our request was received and processed correctly. The most common success codes are 200 OK, 201 Created and 204 No Content.
  • 3xx - Redirection: This group shows that the client had to do additional action to complete the request. The most common redirection codes are 301 Moved Permanently, 304 Not Modified.
  • 4xx - Client Error: This class of status codes is used when the request sent by the client was faulty in some way. The server response usually contains the explanation of the error. The most common client error codes are 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict.
  • 5xx - Server Error: These codes are sent when the server failed to fulfill a valid request due to some error. The cause may be a bug in the code or some temporary or permanent incapability. The most common server error codes are 500 Internal Server Error, 503 Service Unavailable.

If you'd like to learn more about HTTP status codes, you can find a detailed explanation about them here. ​

SetUp winston Logging

API Testing vs Unit Testing

API Testing

  • API testing is done by testers.
  • In API testing we test end to end functionality.
  • Tester not allowed to access the source code.
  • Testing can be done after a build is created.
  • Broader in scope.

Unit Testing

  • Unit testing is done by developers.
  • Developers can access the source code.
  • In unit testing separated functionality tested.
  • Usually ran before check-in
  • Limited in scope.

Pros and Cons of Protractor

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Bharath
    if i use request.get inside function it is not executing. What will be the reason?
    
    describe("Hello World Server1", function() {
    	var request = require('request');
    	
    	it('Should reach google.com', done => {
    		
    		
    		aaa();
    		done();	
    		
    	});
    
    function aaa(){
    	var url = 'some url';
    	
    		request(url, function (error, response, body) {
    			console.log('error:', error); // Print the error if one occurred
    			console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
    			console.log('body:', body); // Print the HTML for the Google homepage.
    			done(); //informs runner that the asynchronous code has finished
    		});
    	}
    
    Reply
  • Vivek
    How can this be integrated with cucumber , mainly on the assertions for cucumber, tried but failing as i'm not able to properly resolve the promises
    Reply
  • can we integrate cucumber with request module
    Reply
  • in form data?
    
    Reply
  • how to send the post request for mp4 file
    
    Reply