Using the Protractor Automation Tool to Test AngularJS Applications

One of the applications that we are working on is being built using pure AngularJS. AngularJS is a framework that is gaining in popularity because it extends the functionality of HTML and can be used to quick launch applications. In our quest for a functional automation framework to automate the UI and functionality of the web application, we zeroed in on the Protractor Automation tool.

Protractor, formally known as E2E testing framework, is an open source functional automation framework designed specifically for AngularJS web applications. It was introduced during AngularJS 1.2 as a replacement of the existing E2E testing framework. The Protractor automation tool is also recommended by AngularJS for scenario testing. To read more about AngularJS, please refer to their “Guide to AngularJS Documentation.”

Salient features of the Protractor Automation tool:

  1. Built on the top of WebdriverJS and Selenium server
  2. Introduced new simple syntax to write tests
  3. Allows running tests targeting remote addresses
  4. Can take advantage of Selenium grid to run multiple browsers at once
  5. Can use Jasmine or Mocha to write test suites

Protractor is a wrapper (built on the top) around Selenium WebDriver, so it contains every feature that is available in the Selenium WebDriver. Additionally, Protractor provides some new locator strategies and functions which are very helpful to automate the AngularJS application. Examples include things like: waitForAngular, By.binding, By.repeater, By.textarea, By.model, WebElement.all, WebElement.evaluate, etc.

Protractor Installation

For this project, the Protractor framework is being used and configured on a Windows environment. Below are the steps for installation:

Install Protractor Globally

  • Step 1: Download and install NodeJS. http://nodejs.org/download/. After installation make sure its path is configured correctly, so that command execution can find Node.
  • Step 2: Open the command prompt and type in the following command to install protractor globally.
npm install –g protractor

Install Protractor Locally

You can install protractor locally in your project directory. Go to your project directory and type in the following command in the command prompt:

npm install protractor

Verify Installation

To verify your installation, please type in the command

Protractor --version

If Protractor is installed successfully then the system will display the installed version. Otherwise you will have to recheck the installation.

  • Step 3: If you don’t have the Selenium server on your machine, then download the latest version onto your machine. If you want to run tests on different browsers, then please download the respective drivers as well. For example, Chrome driver will come in handy to run tests on the Chrome browser.

Write your test cases:

Create a new folder and name it “test cases” or anything as per your convenience.

·         Create a test case spec file. For example: “grid_spec.js” file below, you can create multiple spec files as per your automation scope.

grid_spec.js

describe('HealthSense POC Grid', function() {
         beforeEach(function() {
           browser.get('http://Your Application URL');
            ptor = protractor.getInstance();
           });
 
        it('should click on the grid link', function() {
               element(by.xpath('//a[contains(text(),"Grid")]')).click();
           expect(element(by.xpath('//h1')).getText()).toEqual('Master Grid');
           });
           
        it('should enter ID in filter', function() {
                   ptor.actions().sendKeys(protractor.Key.HOME).perform();
          element(by.model('Model.ID')).sendKeys('10');
          results = element.all(by.repeater('value in testValues'));
               expect(results.count()).toEqual(5);
           element(by.model('Model.ID')).clear();
          ptor.actions().sendKeys(protractor.Key.SPACE).perform();
        });
           
        it('should change the number of records per page to 10', function(){
           element(by.xpath('//select')).click();
            element(by.css('option[value="10"]')).click();
            results1 = element.all(by.repeater('value in testValues'));
          expect(results1.count()).toEqual(10);
        });
});

·         Create a configuration: The configuration file is used to define some parameters which will be passed to Protractor to execute our spec files. Please note:

  1. Selenium server details (required)
  2. Location of our spec files (required)
  3. Browser capabilities for spec files (required)
  4. Jasmine node configuration options (required)
  5. Jasmine reporter configuration options (optional)

Below is a sample configuration file:

Conf.js

exports.config = {

  //The address of a running selenium server.
  seleniumAddress: 'http://localhost:4444/wd/hub',
 
  //Capabilities to be passed to the webdriver instance.
  capabilities: {
    'browserName': 'chrome'
  },
 
  //Specify the name of the specs files.
  specs: ['grid_spec.js'],
 
  //Options to be passed to Jasmine-node.
  jasmineNodeOpts: {
      onComplete: null,
      isVerbose: false,
      showColors: true,
      includeStackTrace: true
  }
};

Execute your tests:

Once you are ready with your test cases and configuration file, the next step is to execute the test and see the results. Please follow these steps to execute the tests:

Run selenium server

  • Make sure the Selenium server (which is specified in the configuration file) is running.

 

If you want to run the Selenium server manually, then run the following command

java -jar selenium/selenium-server-standalone-2.35.0.jar -Dwebdriver.chrome.driver=./selenium/chromedriver

Run tests

Finally, you are ready to run the tests. Type the following command in the command prompt:

protractor Conf.js
  • You should be able to see the test execution progress and its status on the command line and also generate the test reports in an XML format. Please see the next section for details.

Generate Reports:

Protractor supports integration with Jasmine reporters. Jasmine reporters have a collection of JavaScript Jasmine reporter classes. We have used the JUnitXMLReporter which provided the test execution results in XML format. Please follow the following steps to configure the reporter.

Install Jasmine reporter

Install Jasmine reporter by typing the following command on command promptnpm install -g jasmine-reporters

Update Configuration file

After successful installation, create a report output directory inside your project folder and specify the report output directory name in the configuration file. Add the following code into your configuration

file.require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter('outputdir/', true, true));

XML output report

After execution of your tests again, you can find the test execution report XML in the output directory. Below is a sample of an XML report.

Sandeep Kumar

Sandeep Kumar

Quality Assurance Lead

Sandeep Kumar is a Quality Assurance Lead at 3Pillar Global. He has expertise in manual and automation testing (functional and performance/load). He is a Microsoft and ISTQB certified professional, deeply involved in designing Automation frameworks for functional and performance testing of web applications. He has worked on projects like Starfish, Axiell and Proprocure and designed automation solutions in other projects like heathsense and cigital-ESP. Prior to joining 3Pillar Global, he has worked for a couple of product and service based companies including Safaltek and Finantix.

66 Responses to “Using the Protractor Automation Tool to Test AngularJS Applications”
  1. Sneh Mani Tripathi on

    Can we use Selenium IDE with Protractor?

    Reply
  2. Vivek Anand on

    Protractor can be used without running a Selenium server and using chromeDriver configuration instead.

    In Protractor Config JS, add the following property:
    chromeDriver: ‘<PATH TO Chrome Driver EXE'

    Reply
  3. Arun on

    Hi Sandip , I installed node.js but i am getting error while executing command “npm install –g protractor” . I think it is due to Node.js path not configured correctly. can u help me on this? I am getting below error while executing “npm install –g protractor” through command prompt.

    Error: ENOENT, stat ‘C:\Users\arudash\AppData\Roaming\npm’

    Reply
  4. Swarup Dukuria on

    Hi Sandeep,
    Thanks for the article. Can you please suggest performance/load testing tool for Angular JS application?
    I selected JMeter but seems it’s not recording all the application flow.
    Thanks,
    Swarup

    Reply
  5. Hema on

    Hi Sandeep,

    Can you please provide the steps to get a report using mocha instead of jasmine.

    Regards,
    Hema

    Reply
  6. Bhawani on

    Hello Sandeep,
    Thanks for the info..
    I am getting error on adding the below scripts to confi file.
    file.require(‘jasmine-reporters’);
    jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter(‘outputdir/’, true, true));

    Error:
    file.require(‘jasmine-reporters’) ,
    ^
    ERROR – failed loading configuration file
    SyntaxError: Unexpected token .
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at ConfigParser.addFileConfig

    Kindly Advise…

    Reply
  7. Bhawani on

    Hi Sandeep,
    Regarding the report generation using the Jasmine reporter, i am not getting any output nor any errors in protractor.
    My code:
    onPrepare: function() {
    require(‘C:\\Users\\bhawani.prasad\\AppData\\Roaming\\npm\\node_modules\\jasmine-reporters’);
    outputdir: ‘C:\\Users\\bhawani.prasad\\Desktop\\Protractor\\PageObject\\xmlreport’ ;
    jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter(‘outputdir’, true, true))

    } ,

    Reply
  8. Shinos Mohamed on

    I tried to install the Protractor . I intalled it globaly. but am not able to intsall it in Project Folder. Kindly help me in this with Example.

    Reply
    • Damayanti on

      Hi Shinos,

      i am trying same. Trying to install protractor locally in a project folder but not able to do that.

      did you able to install? Anyone please help!!

      Reply
  9. sanjay on

    how to extract data from Excel from protractor testing (give me some example codes using protractor)

    Reply
    • Gautam Jangra on

      Follow the below mentioned steps to set it up :

      Install xlsjs
      npm install xlsjs
      Define a JavaScript utility function as :
      cellFromXLS = function (cellId) {
      ‘use strict’;
      //Define sheetNumber
      var sheetNumber = 0;
      //Define file Path name
      var fileNamePath = path.join(dirPath, ‘data1.xls’);
      //NodeJs read file
      var XLS;
      if (typeof require !== ‘undefined’) {
      XLS = require(‘xlsjs’);
      }
      //Working with workbook
      var workbook = XLS.readFile(fileNamePath);
      var sheetNamelist = workbook.SheetNames;
      var value = workbook.Sheets[sheetNamelist[sheetNumber]][cellId].v;
      return value;
      };
      Call function as:
      var email = cellFromXLS(‘B1’);

      Reply
      • Kotni saikiran on

        HI Gautam Jangra,

        Thank you for the information may I have the sample code for retriving the entire row of data from the excel file instead of single cell values or any predefined methods in the xlsjs for getting the row and column count.

        Thank you.

        Reply
  10. Harsha on

    Hi Sandeep,

    I have an application which runs on AngularJS and Worklight adapters, but the webpages are loaded in android webview container and not in Chrome Browser or android standalone browser. Can I use Protractor in this case. If yes, please explain me how.

    Thanks

    Reply
  11. Haripriya on

    Hi Sandeep,

    I have installed Proctrator in my system and created one sample script.

    The script which I got from web is working. But, the script which I created is showing the below error.

    Failures:
    encountered a declaration exception

    Message: ReferenceError: Element is not defined at

    Please help me out here.

    Thanks
    Haripriya

    Reply
  12. Ashok on

    Hi Sandheep,
    Is it possible to do pass input data (excel parameterization) to create data driven framework in protractor?

    Reply
  13. Usman on

    Hi Sandeep,
    I installed the jasmine reporter successfully and updated the conf.js also with required details.
    While running tests I am seeing the below error. can you plz suggest the solution.

    C:\Users\musman\protractorws>protractor conf.js
    ERROR – failed loading configuration file conf.js
    C:\Users\musman\protractorws\conf.js:9
    file.require(‘jasmine-reporters’);
    ^^^^
    SyntaxError: Unexpected identifier
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at ConfigParser.addFileConfig (C:\Users\musman\AppData\Roaming\npm\node_modu
    les\protractor\lib\configParser.js:174:22)
    at Object.init (C:\Users\musman\AppData\Roaming\npm\node_modules\protractor\
    lib\launcher.js:107:18)
    at Object. (C:\Users\musman\AppData\Roaming\npm\node_modules\prot
    ractor\lib\cli.js:141:23)

    Reply
  14. Vibhor Mehrotra on

    Hi Sandeep,
    I am using protractor-html-screenshot-reporter for report generation. I am able to generate the report along with the json file.Can we send the report created by protractor to different email ID’s either using the above plugin or some other?
    Please suggest.

    Reply
  15. Manish Sharma on

    Hi Sandeep,

    I have read your blog, would appreciate if you can also explain sync/async behavior of JavaScript functions in protractor. Also, how can you debug your code using protractor ?

    Even if you write your code using IDE, will debug of protractor tool good enough for debugging automation code. This blog is as same as it was explained in Angular site, common flaws of protractor tool like sync/async behavior & debug is nowhere mentioned.

    Please revert with your findings.

    Thanks !

    Regards,
    Manish Sharma

    Reply
  16. Sunil Arora on

    How can i check my website full functionality on regular basis ,like fare search to last payment page of website .

    Reply
  17. Alagarsamy on

    Will PROTRACTOR supports mobile automation? will this tool can be used with any other open source mobile automation tools(Appium/MonkeyTalk/Calabash)?

    Reply
  18. Mani on

    Hi Sandeep,

    Can you suggest some automation tools for automation of our desktop application which is now being developed on Node webkit/Node.js/Angular.Js

    Reply
    • Vysakh on

      Hi Mani,

      I am also trying to automate a native app built on Node webkit/Node.js/Angular.Js running on chromium. Can you please share the details of the tools used, if you have any success writing scripts for automating your app?

      Reply
  19. Rahul on

    Hi sandeep,
    Can we use protractor with selenium webdriver.. Means few of the concepts were developed by using angular JS in my web application. So far we use the Webdriver for this application, but in middle of the webdriver script ‘its saying unable to locate element ‘, even we have given valid Xpath, finally we came to know that the element was implemented by Angular JS. So can we use ‘Protractor with in selenium webdriver’ ? Or ‘Is there any way to switch from selenium webdriver to protractor and vice versa? ‘. This would be very helpfull why because my web application has used Angular JS partially…. If i try to automate total application by Protractor it does not work and even i was unable to automate total application by using selenium webdriver…

    Thanks,
    Rahul.

    Reply
    • vittal on

      May be you can use commands which are specific to protractor for angular js part of your web page and can use the common webdriver commands for the non-angular part

      Reply
  20. makkar1610 on

    I need to test a global application using Protractor, how do I do it..??

    Reply
  21. Lokesh Mahalingam on

    Can some one help me in finding FREE Opensource tool for writing and executing Protractor scripts. I am new to Protractor. I have tried webstorm but it is paid and trial version.
    Also Can Eclipse be used in writing and executing the protractor scripts.

    Reply
  22. Swati on

    Hi Sandeep,

    I have few queries:
    1. Is it possible to automate canvas graphs/charts using protractor. If yes, then please suggest the code.

    2. Is there any workaround available with protractor by which we could enter captcha?

    Reply
  23. Raj on

    I am using allure reports and it is generating xml output and screenshots. How can i convert it to html Report?

    Reply
    • Rahul on

      You can use maven to run this and generate a nice formatted HTML output of the same. You need to run the two commands

      mvn site -Dallure.results_pattern=allure_results

      mvn jetty:run -Djetty.port=1234

      where allure_results is the directory, where you’re storing the xml outputs and screenshots and 1234 is port where you want to run a formatted report.

      Reply
  24. Alexander on

    Hi Sandeep,
    How can I test inner app pages with token authorization? It always throw me on login page with test failure. I added in config file ‘accessToken’ with token value, but without success.

    Reply
  25. balu on

    Hi,

    Nice blog and something new. my project is developed with leaflet.js & enyo.js framework. and there are maps in this, on the maps there are markers,locators..etc. Could you please let me know whether it can be tested by protractor ?? or any other way ?? I need your help , please guide me

    Reply
  26. Suraj Gupta on

    Can we automate windows cross platform application using Appium+Protractor?

    There websites says we can automate cross platform app but I am doubtful regarding Windows mobile application automation..

    Reply
  27. Vinayak on

    HI All,

    As any one have any idea on Canvas automation using protractor

    1. How i can access canvas objects
    2. is there any work around

    Reply
  28. Waleed Deea on

    Hi Sandeep,

    I hope you are well.

    Recently i have just started to experiment with developing the automation framework using selenium webdriver and selenium grid with Javascript, protractor and Mocha.

    Is there a way to create individual reports for each instance of browser running on the grid in html format? lets say i have 10 instances running – i would like to get 10 individual reports – is that possible?

    Reply
  29. Balaji on

    Hi,

    Your sandeep, I liked your ideas and view on protractor . But just want to know how you perform if conditions in protractor tests .

    Lets say for example

    if ( A==10)
    {
    do this
    }
    else
    {
    do this
    }

    Or take another example

    if you login to gmail for example if you want to check gmail login is successfull or not with respect to title of page then how would you do it.

    if ( title.equals( ” Gmail login”))
    {

    print – login failed
    }
    else
    {
    print login passed
    }

    With Regards,
    Balaji Singh

    Reply
    • Rahul on

      You can use the expect() method from jasmine to match this title. or otherwise use the === operator

      for example, it would be something like

      if (browser.getTitle()===’ABCD’){
      console.log(‘Matched title’);
      }else{
      console.log(‘Can’t match title’);
      }

      Reply
  30. Balaji on

    Hi Sandeep,

    I have an question for you in protractor automation – How will run your tests in IE browser.

    ofcourse i do know that we can change the browser parameter in config as “Internet Explorer” but still this doesnt work.

    With Regards,
    Balaji singh

    Reply
    • Sowjanya on

      Hello Balaji

      In cmd prompt, got to your protractor_project folder

      cd node_modules\.bin\

      Step 1 : Run the command : webdriver-manager update –ie
      Step 2: In your config file,
      capabilities: {
      ‘browserName’: ‘ie’,
      },

      Reply
  31. amrit on

    I am new to protactor , can you guide me which editor i should use, for example earlier i am using eclipse for selenium and java and also can we use eclipse for this too or not, if not then please tel me which editor i should use and how to do setuo?

    Reply
  32. Sandeep on

    hi, i wanted to set up selenium framework designed in angualar js ng model on windows using java. I tried with normal driver.findElement(By.xpath or driver.findElement(By.id( ….to select the elements on from page, but every time i am getting Exception in thread “main” org.openqa.selenium.NoSuchElementException: no such element.

    I found there is Protractor need to have to work with angularjs in selenium; can u please help me in this

    Reply
  33. Ajitabh on

    Hi Sandeep,

    I want to write a common action and re-use it multiple times in protractor. Can we do it?

    eg- there are N number of form fill-up in my test. All actions are same but all locators are different in different scenario. So can I write a common form fill-up action in another Page Object file and call it every time when required.

    Reply
  34. Rashmi on

    Thank you so much for such a wonderful Article. Very helpful.

    Reply
  35. HItesh on

    Hi Sandeep,
    I have installed the protractor in defalt location . and project is created in D: drive.

    I am facing issues in calling a common function from one Js file to another spec js file.

    I used require statement, but still getting Error Function is not defined.

    Under src folder i have 2 Js file- Once common js file and one spect file.

    Please help me in resolving the issue.

    Reply
  36. Deepti on

    Hi Sandeep,

    I want to learn the protector. Can you please advise any online training .

    Thanks,

    Reply
  37. raghu on

    Can we automate angular js 2.0 applications using protractor ? if we can .Could you please provide any sample of that

    Reply
  38. Vishal Gaur on

    HI Sandeep
    I am new to Protractor and am trying to install it. I installed node v6.10.03 and can see NPM –version as v3.10.10. when I am trying to install protractor through npm install -g protractor , I am getting an ETIMEDOUT error. Can you help me.

    Reply
  39. Sekhar on

    I want to move the scroll bar down. How to do that in Protractor, will you please suggest me.
    Thanks,
    Sekhar

    Reply
    • teja on

      please some one help me on this I want to move the scroll bar down. How to do that in Protractor, will you please suggest me.

      Thanks,
      Teja.

      Reply
      • Sowjanya on

        Hello Sekhar, Use the below code

        browser.executeScript(‘window.scrollTo(0,document.body.scrollHeight);’).then(function () {

        //Your code e.g. element(by.id(‘Next’)).click();
        }

        Reply
  40. vedant kumar on

    Hii Sandeep,
    Can you Please Look into this Problem and do let me know i you need some more clarification about my question
    https://sqa.stackexchange.com/questions/27936/unable-to-add-attach-screenshot-and-test-steps-in-report

    Reply
  41. Jyotirmayee Priyadarshini on

    I have just started learning Protractor..need to gain more knowledge on this.

    Reply
  42. Joseph on

    Hi Sandeep,
    I am getting error while launching the application as below:
    WebDriver Error: Error communicating with the remote browser. It may have died.

    E/launcher – Process exited with error code 1

    Reply
  43. Steve on

    Great article. Would you happen to have an example of how to save a value (i.e. getText results) into a global variable to be available for use in other specs?

    Reply
  44. Bake on

    Does the config file not need to point to the spec file? What is the link between the config file and the spec file?

    Reply
  45. Praveen on

    Hi Sandeep,

    I am selenium Automation tester. I work selenium with JAVA.

    To learn protractor Tool should I need to learn again JAVA Scripting from the scratch.

    Please guide.

    Reply
  46. Girija on

    I am trying to automate a login form by Selenium Webdriver (JavascriptExecutor) which is built in AngularJS. The script is entering data in textbox; but when submit button is clicked error message shows that textbox is not filled. I have also used events like onkeyup(), blur(); but error shows these are not functions.
    Textbox validation works fine with sendkeys() and it takes time; but facing issue when JavascriptExecutor is used.

    Reply
Leave a Reply