top

E2E testing with protractor in AngularJS

Unit testing is good, but not obviously enough. Programmers need to tests how their app behaves eventually when small units are assembled into what is known as a complete product. This is where end-to-end testing comes into picture.  E2E testing is about checking the integrity, behavior and flow of your complete application. It is a way to ensure that when your users use your app, they do not run into bugs or defects (For eg: a broken link). e2e testing can be done manually, but here we will see how we can automate e2e tests for our AngularJS applications using a tool known as Protractor and in doing so, we will programmatically replicate user behavior on our application. Protractor Protractor is an e2e testing framework for AngularJS applications. Protractor is a Node.js program and uses webdriver-manager to interact with the browser and replicate user actions. It uses Jasmine for its testing syntax. Protractor provides AngularJS specific locator-strategies which makes it the framework of choice for performing e2e tests on AngularJS applications. Setup Protractor requires node.js to run. So make sure you have node installed. Protractor 3 is compatible with node v4 and above, for lower versions of node use proractor@2. We will require a standalone selenium server to interact with the browsers,which requires Java Development Kit to be installed on our machine. After java installation in some cases, you might have to restart your machine for java to be available as an environment variable. We can verify this by running $ java -version in command line. Install Protractor Globally Install protractor globally by running $ npm install protractor -g. Note:  In windows, you may need to fire up the cmd window with administrator privileges and for Linux, sudo access might be required. This command will install protractor and webdriver-manager and make them available in command-line. To ensure if protractor was successfully installed run $ protractor --version. Next update your webdriver-manager by running $ webdriver-manager update Our App Our app is a simple one view todo app which lets user type-in a todo and add it to the list of todos. Since this is a simple demo app, we are following a simple flat directory structure. Here are the files. Index.html                              Todo App                                                                                          Zeolearn Todo App                                                 Todo List                                                                                                 {{item}}                                                                                                                                 Add todo                                                                                                                            Add                                                                                                        App.js angular.module('zeolearn', []) .controller('TodoCtrl', [function(){ var vm = this; vm.items = [  'Read book- How google works', 'Renew car insurance'      ]    vm.addTodo = function(item){    vm.items.push(item);    vm.newItem = "";      }}]);Make sure you run the app on a local server. You create a simple node server or simply use xampp.Protractor Configuration Now create a file named protractor.conf.js. This will be our protractor configuration file. Here we can configure our browsers to test with our framework of choice and other configurable items. Our protractor.conf.js looks like below. Protractor.conf.js // protractor.conf.jsexports.config = {framework: 'jasmine',   seleniumAddress: 'http://127.0.0.1:4444/wd/hub',specs: ['specs.js'],  jasmineNodeOpts: {     showColors: true, // Use colors in the command line report.},  capabilities: {   browserName: 'chrome'  }} Notice under specs we have specified a file as specs.js, this is where we will be writing our tests. The seleniumAddress is the url to the selenium server. Capabilities define the browsers on which you want to run the tests. We can add multiple browser capabilities using the multiCapabilities option in the below format. multiCapabilities: [{  'browserName': 'firefox' }, {   'browserName': 'chrome'}] Writing Tests Now that we have our machine configured for e2e tests with protractor let’s create a spec.js file and write a few tests. We are using jasmine for our testing syntax. Protractor also has partial support for mocha. The reason for choosing jasmine is that it is the default framework for writing e2e as well as unit tests in AngularJS. To begin with, we will write a very basic test that will access our app and verify our app title. Specs.js describe('Protractor Demo App', function() { /** This block runs before each it block */        beforeEach(function() {        browser.get('http://localhost/zeolearning/e2eprotractor'); //fetch your app replace the above by your apps url  });         it('should have a title', function() {          expect(browser.getTitle()).toEqual('Todo App');});}); Your tests can be divided into different describe blocks. As a good practice, you can have one describe block for one component or view of your app, although this is not necessary. The before each block contains all the things we need to do prior to running each spec. A spec in jasmine is an it block.  So here, we are fetching our app using the browser.get function provided by protractor. Later we have added one spec where we have an expectation that checks the title of our app. Running tests Now that we have our first test ready let’s run the test to see what happens.  Before doing so we need to have our selenium server running. Open up another window of your command line tool and start the selenium server by running $ webdriver-manager start To run the tests run $ protractor . So in our case, we can run by $ protractor protractor.conf.js On doing so you will notice browser windows opening up and closing. This is done by selenium, where it’s actually replicating the user behavior. After the tests are complete you should get the following output. Writing more tests Now that we successfully ran our first test. Let’s go ahead and add more specs, to test our complete app. Specs.js describe('Protractor Demo App', function(){ var items;  var count; /** This block runs before each it block */ beforeEach(function() {browser.get('http://localhost/zeolearning/e2eprotractor'); //fetch your app items = element.all(by.exactRepeater('item in todo.items'));items.count().then(function(originalCount){  //resolve initial count of the listcount = originalCount;   }); });it('should have a title', function() {expect(browser.getTitle()).toEqual('Todo App');}); /** The tests in the below it block can be skipped */  it('should have all required elements present', function(){  expect(element(by.exactRepeater('item in todo.items')).isPresent()).toBe(true); //if list presentexpect(element(by.model('todo.newItem')).isPresent()).toBe(true); // if model -input box presentexpect(element(by.buttonText('Add')).isPresent()).toBe(true); // if button present });  it('should have 2 todos initially', function(){ //checking no of items in list initially expect(count).toEqual(2); });  it('should add a todo', function(){  var newTodo = 'Complete my assignment';   element(by.model('todo.newItem')).sendKeys(newTodo);  // Typing in a todo  element(by.buttonText('Add')).click();  // clicking the add button  var list = element.all(by.exactRepeater('item in todo.items'));// get our todo list expect(list.count()).toBe(count + 1);// check if count increasesexpect(list.getText()).toContain(newTodo);// check if the newTodo is present });});  Below are the specs we have added. ●     should have all required elements present: Here we are checking if all the HTML elements required are present and rendered. ●     should have 2 todos initially: Here we verify the initial number of items in the todo list. ●     should add a todo: Here we make protractor add a new todo where it literally goes in and types into the text box, then clicks the add button just           like a user would. It also verifies if the todo was added successfully. Please read the comments inline along with the code for a functional explanation. Upon running the test using $ protractor protractor.conf.js we should get the below output. Conclusion At first, writing e2e tests might look time-consuming, but as your app starts to scale and grows in complexity, manually testing becomes cumbersome and inefficient. By automating e2e tests you only have to invest once and then perform tests any number of times. Automated e2e tests at later stages saves a huge amount of time and is more reliable than manual testing. Protractor, is the de-facto tool for e2e testing of AngularJS applications. In this tutorial, we learned how we can setup our machine and perform e2e testing on our AngularJS applications using protractor. References Protractor api: http://www.protractortest.org/#/api Jasmine: http://jasmine.github.io/2.0/introduction.html  
Rated 4.0/5 based on 20 customer reviews
Normal Mode Dark Mode

E2E testing with protractor in AngularJS

Geneva Clark
Tutorials
07th Jul, 2016
E2E testing with protractor in AngularJS

Unit testing is good, but not obviously enough. Programmers need to tests how their app behaves eventually when small units are assembled into what is known as a complete product. This is where end-to-end testing comes into picture.

 E2E testing is about checking the integrity, behavior and flow of your complete application. It is a way to ensure that when your users use your app, they do not run into bugs or defects (For eg: a broken link). e2e testing can be done manually, but here we will see how we can automate e2e tests for our AngularJS applications using a tool known as Protractor and in doing so, we will programmatically replicate user behavior on our application.

Protractor

Protractor is an e2e testing framework for AngularJS applications. Protractor is a Node.js program and uses webdriver-manager to interact with the browser and replicate user actions. It uses Jasmine for its testing syntax. Protractor provides AngularJS specific locator-strategies which makes it the framework of choice for performing e2e tests on AngularJS applications.

Setup

Protractor requires node.js to run. So make sure you have node installed. Protractor 3 is compatible with node v4 and above, for lower versions of node use proractor@2.

We will require a standalone selenium server to interact with the browsers,which requires Java Development Kit to be installed on our machine. After java installation in some cases, you might have to restart your machine for java to be available as an environment variable. We can verify this by running $ java -version in command line.

Install Protractor Globally

Install protractor globally by running $ npm install protractor -g.

Note In windows, you may need to fire up the cmd window with administrator privileges and for Linux, sudo access might be required.

This command will install protractor and webdriver-manager and make them available in command-line.

To ensure if protractor was successfully installed run $ protractor --version.

Next update your webdriver-manager by running $ webdriver-manager update

Our App

Our app is a simple one view todo app which lets user type-in a todo and add it to the list of todos.

Zeolearn app

Since this is a simple demo app, we are following a simple flat directory structure. Here are the files.

Index.html

 

                           Todo App                                                  

                                    

 

Zeolearn Todo App

                                               

Todo List

                          

  •                                
    •                                      {{item}}                                
    •                           
                                                                        

    Add todo

                                                                                                                               Add                                                                                                        App.js

    angular.module('zeolearn', [])

    .controller('TodoCtrl', [function(){

    var vm = this; vm.items = [  'Read book- How google works', 'Renew car insurance'      ]    vm.addTodo = function(item){    vm.items.push(item);    vm.newItem = "";      }}]);Make sure you run the app on a local server. You create a simple node server or simply use xampp.Protractor Configuration

    Now create a file named protractor.conf.js. This will be our protractor configuration file. Here we can configure our browsers to test with our framework of choice and other configurable items.

    Our protractor.conf.js looks like below.

    Protractor.conf.js

    // protractor.conf.jsexports.config = {framework: 'jasmine',   seleniumAddress: 'http://127.0.0.1:4444/wd/hub',specs: ['specs.js'],  jasmineNodeOpts: {     showColors: true, // Use colors in the command line report.},  capabilities: {   browserName: 'chrome'  }}

    Notice under specs we have specified a file as specs.js, this is where we will be writing our tests. The seleniumAddress is the url to the selenium server. Capabilities define the browsers on which you want to run the tests. We can add multiple browser capabilities using the multiCapabilities option in the below format.

    multiCapabilities: [{ 

    'browserName': 'firefox' }, {  

    'browserName': 'chrome'}]

    Writing Tests

    Now that we have our machine configured for e2e tests with protractor let’s create a spec.js file and write a few tests. We are using jasmine for our testing syntax. Protractor also has partial support for mocha. The reason for choosing jasmine is that it is the default framework for writing e2e as well as unit tests in AngularJS.

    To begin with, we will write a very basic test that will access our app and verify our app title.

    Specs.js

    describe('Protractor Demo App', function() { /** This block runs before each it block */        beforeEach(function() {        browser.get('http://localhost/zeolearning/e2eprotractor'); //fetch your app replace the above by your apps url  });         it('should have a title', function() {          expect(browser.getTitle()).toEqual('Todo App');});});

    Your tests can be divided into different describe blocks. As a good practice, you can have one describe block for one component or view of your app, although this is not necessary.

    The before each block contains all the things we need to do prior to running each spec. A spec in jasmine is an it block.  So here, we are fetching our app using the browser.get function provided by protractor.

    Later we have added one spec where we have an expectation that checks the title of our app.

    Running tests

    Now that we have our first test ready let’s run the test to see what happens.  Before doing so we need to have our selenium server running. Open up another window of your command line tool and start the selenium server by running $ webdriver-manager start

    To run the tests run $ protractor . So in our case, we can run by $ protractor protractor.conf.js

    On doing so you will notice browser windows opening up and closing. This is done by selenium, where it’s actually replicating the user behavior. After the tests are complete you should get the following output.

    Writing more tests

    Now that we successfully ran our first test. Let’s go ahead and add more specs, to test our complete app.

    Specs.js

    describe('Protractor Demo App', function(){ var items;  var count; /** This block runs before each it block */ beforeEach(function() {browser.get('http://localhost/zeolearning/e2eprotractor'); //fetch your app items = element.all(by.exactRepeater('item in todo.items'));items.count().then(function(originalCount){  //resolve initial count of the listcount = originalCount;   }); });it('should have a title', function() {expect(browser.getTitle()).toEqual('Todo App');}); /** The tests in the below it block can be skipped */  it('should have all required elements present', function(){  expect(element(by.exactRepeater('item in todo.items')).isPresent()).toBe(true); //if list presentexpect(element(by.model('todo.newItem')).isPresent()).toBe(true); // if model -input box presentexpect(element(by.buttonText('Add')).isPresent()).toBe(true); // if button present });  it('should have 2 todos initially', function(){ //checking no of items in list initially expect(count).toEqual(2); });  it('should add a todo', function(){  var newTodo = 'Complete my assignment';   element(by.model('todo.newItem')).sendKeys(newTodo);  // Typing in a todo  element(by.buttonText('Add')).click();  // clicking the add button  var list = element.all(by.exactRepeater('item in todo.items'));// get our todo list expect(list.count()).toBe(count + 1);// check if count increasesexpect(list.getText()).toContain(newTodo);// check if the newTodo is present });});

     Below are the specs we have added.

    ●     should have all required elements present: Here we are checking if all the HTML elements required are present and rendered.

    ●     should have 2 todos initially: Here we verify the initial number of items in the todo list.

    ●     should add a todo: Here we make protractor add a new todo where it literally goes in and types into the text box, then clicks the add button just           like a user would. It also verifies if the todo was added successfully.

    Please read the comments inline along with the code for a functional explanation. Upon running the test using $ protractor protractor.conf.js we should get the below output.

    Conclusion

    At first, writing e2e tests might look time-consuming, but as your app starts to scale and grows in complexity, manually testing becomes cumbersome and inefficient. By automating e2e tests you only have to invest once and then perform tests any number of times. Automated e2e tests at later stages saves a huge amount of time and is more reliable than manual testing. Protractor, is the de-facto tool for e2e testing of AngularJS applications. In this tutorial, we learned how we can setup our machine and perform e2e testing on our AngularJS applications using protractor.

    References

    Protractor api: http://www.protractortest.org/#/api

    Jasmine: http://jasmine.github.io/2.0/introduction.html

     

Geneva

Geneva Clark

Blog Author
Geneva specializes in back-end web development and has always been fascinated by the dynamic part of the web. Talk to her about modern web applications and she and loves to nerd out on all things Ruby on Rails.

Leave a Reply

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

SUBSCRIBE OUR BLOG

Follow Us On

Share on

other Blogs

20% Discount