Moving from Selenium to Protractor for Test Automation

Protractor is an end-to-end Testing Framework for testing Angular as well as AngularJS applications. It helps you runs tests against your application running in a real browser, interacting in exactly the same way a user would. The first version of Protractor was released in the month of July 2013, when the framework was just a prototype of a particular testing framework. Google, however, with the support of the testing community, is evolving the framework to follow the evolution of AngularJS and to meet the needs of the community that is using AngularJS.

Why use Protractor over Selenium?

Test Your Application like a User

Protractor framework is built on top of WebDriverJS, which uses native events and browser-specific drivers to interact with your application exactly like a user would. It is based on Behaviour Driven approach which allows even a non automation tester to test the application without expertise in automation tool. Example –

describe(‘angularjs homepage’, function() {
 it(‘should greet the named user’, function() {
   // Load the AngularJS homepage.
   browser.get(‘http://www.angularjs.org’);    
   element(by.model(‘yourName’)).sendKeys(‘Julie’);

   var greeting = element(by.binding(‘yourName’));

   // Used to assert that the text element has the required expected value.
   // Protractor patches ‘expect’ to understand promises.

   expect(greeting.getText()).toEqual(‘Hello Julie!’);
 });
});

Advantages over Selenium

JavaScript automation frameworks involve working on asynchronous execution, callbacks, anonymous functions and promise, which is a sequential activity just like finding an object and perform operations on it. Another advantage of transitioning to Protractor/JavaScript is that both the application and the test codebase would be written in the same language.

For Angular Apps

Protractor provides support for Angular-specific locator bindings, which allows you to test Angular-specific web elements without any need for additional setup effort. It has extra locators compared to selenium webdriver. Examples include model, repeater, binding etc.

Angular JS applications have some extra HTML attributes like ng-repeater, ng-controller, ng-model which are not included in Selenium locators. Selenium is not able to identify those web elements using today used Selenium code. Protractor on top of Selenium can handle and control these operations in Web Applications.

Example –

element(by.model(‘locator’)).sendKeys(‘text’);
element(by.binding(‘locator’)).click();

Automatic Waiting

When it comes to waiting for elements on a web page, there is no need to add waits and sleeps to your test. Protractor automatically executes the next step in your test the moment a webpage finishes all pending tasks. There is no need to worry about waiting for your test and webpage to sync in. Protractor, moreover, also speeds up your testing as it avoids the requirement for a lot of “sleeps” and “waits” in your tests, which in turn optimizes sleep and wait times.

Supports Extensibility

Since protractor is a node.js application, can utilize the wide variety of packages that are available in the node. One can extend the framework or add additional features by installing node packages. For example, if you need HTML report you can just use Jasmine HTML Reporter for the clean code you can install eslint or tslint. Likewise, you can install node packages of your choice.

Supports Control Flow

Application Programming Interface (API) is based on promises, which are managed by control flows and adapted for Jasmine. Protractor APIs are purely asynchronous. It maintains a queue of pending promises, called the control flow, to keep execution organized.

Jasmine System Architecture
Jasmine System Architecture

Asynchronous Behavior

Works on NodeJS, so that the asynchronous process helps to speeding up the execution.
Here is how you it is achieved.
 
1) Promise Manager/ Control Flow

It is an abstraction that makes every action to be called one by one, like a queue. Every action returns a special object – Promise. These represent the result of async operation.

2) Second way – async/await

It is new abstraction around promises objects and allows easily chaining actions one by one. The advantage in this is native language construction, instead of Promise Manager, which makes your code look like synchronized, with try/catch and other familiar constructions.

describe(‘angularjs homepage’, function() {
 it(‘should greet the named user’, async function() {
   await browser.get(‘http://www.angularjs.org’);
   await element(by.model(‘yourName’)).sendKeys(‘Julie’);
   var greeting = element(by.binding(‘yourName’));
   expect(await greeting.getText()).toEqual(‘Hello Julie!’);
 });

“await” is like “suspend code execution until a promise returned from the action is resolved”.

Images and Screenshots

Image comparison is very easy in protractor and it works great. Protractor helps you take screenshots on demand and create them in any place needed. You just need to specify the type of Reporter that you want to use.

Example –

jasmine.getEnv().addReporter(new HtmlReporter(){
this.specDone = function(result){
if(result.failedExpectations.length >  0){
//take Screenshot
}
}
}

Conclusion/ Summary

There is a big world of Protractor out there and there are hundreds of packages available in the market offered by NPM to add more features to your test in addition to simple test scenarios.

Page Object Model and Implementation in Selenium

In testing department of today’s IT sector, Automation has a significant role. IT companies are leaning towards automation testing because there are endless advantages of automating an application. For programming language, automation gives flexibility. There are distinct types of frameworks that companies use for automating their applications. Some of which are mentioned below, and one of which is Page Object Model also popular as POM.

●    Page Object Model (POM)
●    Hybrid
●    Data Driven
●    Keyword Driven

POM is a type of framework which is very easy to understand and easy to implement while making architecture of any automation process. It basically enhances the test maintenance and reduces the possibility of duplication of code, which is very concerned thing in test automation. In other words POM is a structured base object repository design.

In POM we create a page class for each corresponding web page in the application. Now, the page class that we have created contains all the web-elements of that page and also that methods that we will perform on those web-elements, so the name that we give to a method should be according to its functionality, for example- for a log-in page, the name of the method can be login() which only has few elements like user-name, password, log-in button, forget password link, etc. and methods like passing strings in the field and clicking the buttons.

For making a robust and easy to maintain framework we use POM with data driven by collating excel with POM. The best combination would be POM with data driven through excels and run test cases through TestNG

Below mentioned the flowchart will make it clearer to understand:

Flow Chart

Implementation Example in Selenium 

  1. Create a new package file as Practice; we will be creating different packages for Page Objects, Utilities, Test Data, Test Cases and Modular actions. It is always recommended to use this structure, as it is easy to understand, simple to use and easy to maintain.
  2. Create a new class file and refer the name to the actual page from the test object. In our case it is Home Screen and Login Screen.
  3. Create a static method for each element in Home Screen. Each method will have an argument (driver) and returns a value (element).

package Practice;

   import org.openqa.selenium.By;

    import org.openqa.selenium.WebDriver;

    import org.openqa.selenium.WebElement;

public class Home_Screen {

    private static WebElement element = null;

public static WebElement MyAccount(WebDriver driver){

    element = driver.findElement(By.id(“id”));

    return element;

    }

public static WebElement LogOut(WebDriver driver){

    element = driver.findElement(By.id(“logout”));

return element;

    }

}

4.Reason of passing driver as argument selenium is able to locate the element on the browser (driver). Element is returned so that action can be performed on it.
5.Method is declared as public static so that it can be called in any other method without creating instance of the class.
6.Follow same rule for creating another class LogIn Screen.

package Practice;

import org.openqa.selenium.*;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

public class LogIn_Screen {

        private static WebElement element = null;

    public static WebElement UserName(WebDriver driver){

         element = driver.findElement(By.id(“id”));

         return element;

         }

     public static WebElement Password(WebDriver driver){

         element = driver.findElement(By.id(“id”));

         return element;

         }

     public static WebElement LogIn(WebDriver driver){

         element = driver.findElement(By.id(“id”));

         return element;

         }

}

7. Now create a new class which will be our test case, let’s say we are creating it in package called Framework by name POM.

package Framework;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

// Import package pageObject.*

import pageObjects.Home_Screen;

import pageObjects.LogIn_Screen;

public class POM{

private static WebDriver driver = null;

public static void main(String[] args) {

driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.get(“http://www.store.demoqa.com”);

// Use page Object library now

Home_Screen.MyAccount(driver).click();

LogIn_Screen.UserName(driver).sendKeys(“testuser_1”);

LogIn_Screen.Password(driver).sendKeys(“Test@123”);

LogIn_Screen.LogIn(driver).click();

System.out.println(” Login Successfully, now it is the time to Log Off buddy.”)

Home_Screen.LogOut(driver).click();

driver.quit();

}

}

8.You will notice that once you type HomeScreen in your test script and the moment you press dot, all the methods in the Home Page will display. We can expose methods in order to reduce duplicated code. We are able to call these method multiple times. This will ensure a better maintainable test code, because we only have to make adjustments and improvements in one particular place.

**Implementation reference is taken from: toolsqa.com.