Sunday, June 12, 2016

Take screenshot of failed test cases with Protractor.

With Protractor we can take screenshot of failed test cases. It is a good practice to take screenshot of webpage when the test case fails. Because from the screenshot you may have a idea why the test case failed. Looking at a screenshot is easier then reading many lines of error message.

In Protractor browser.takeScreenshot() is the basic command to take the screenshot. Now here is the code to take screenshot after the failure of each test cases.
      afterEach(function() {  
           takeScreenshotWithProtractor();  
      });  
      var takeScreenshotWithProtractor = function() {  
           // Note: this is using Jasmine 2 reporter syntax.  
           jasmine.getEnv().addReporter(new function() {  
                this.specDone = function(result) {  
                     // if testcase fails  
                     if(result.failedExpectations.length > 0) {  
                          // take screenshot after failure  
                          browser.takeScreenshot().then(function(png) {  
                           // If screenshot folder does not exist it will create a screenshot folder.       
                     var dir = "./screenshot/";  
                     try {  
                      fs.mkdirSync(dir);  
                     } catch(e) {  
                       if ( e.code != 'EEXIST' )   
                       throw e;  
                     }  
                     try {  
                          // Create your image file if not exists. Image file name is test case name.  
                          var stream = fs.createWriteStream(path.join(dir, result.description + '.png'));  
                           stream.write(new Buffer(png, 'base64'));  
                           stream.end();  
                         } catch(e) {  
                          if ( e.code != 'EEXIST' )   
                             throw e;  
                         }  
                          });  
                     }  
                }  
           });  
      };  

Here this chunk of code will help you to take screenshot of web page after each failed test case. This also will create a screenshot folder inside your project folder to store the screenshots. Screenshot name will be test case name.

You have to install two node module for this. One is fs and another is path. The command is 
npm install fs 
npm install path

Here is the full code of the test on this webpage : http://mahmudulhasan.github.io/ToDoAngular/

Last test case is the failed one :
 describe('Basic protractor test', function() {  
     var todoTextBox = element(by.id('todotask'));  
     var addNewButton = element(by.id('addtodotask'));  
     var removeTaskButton = element(by.css('button'));  
     var fs = require('fs');  
     var path = require('path');  
     // All the list item   
     var todoList = element.all(by.repeater('x in todoList'));  

     afterEach(function() {  
         takeScreenshotWithProtractor();  
     });
  
     var takeScreenshotWithProtractor = function() {  
         // Note: this is using Jasmine 2 reporter syntax.  
         jasmine.getEnv().addReporter(new function() {  
             this.specDone = function(result) {  
                 // if testcase fails  
                 if(result.failedExpectations.length > 0) {  
                     // take screenshot after failure  
                     browser.takeScreenshot().then(function(png) {  
                      // If screenshot folder does not exist it will create a screenshot folder.       
                  var dir = "./screenshot/";  
                  try {  
                   fs.mkdirSync(dir);  
                  } catch(e) {  
                    if ( e.code != 'EEXIST' )   
                    throw e;  
                  }  
                  try {  
                      // Create your image file if not exists. Image file name is test case name.  
                      var stream = fs.createWriteStream(path.join(dir, result.description + '.png'));  
                       stream.write(new Buffer(png, 'base64'));  
                       stream.end();  
                     } catch(e) {  
                      if ( e.code != 'EEXIST' )   
                         throw e;  
                     }  
                     });  
                 }  
             }  
         });  
     };  

     it('Page should load properly', function() {  
         // Load demo angular site  
         browser.get('http://mahmudulhasan.github.io/ToDoAngular/');  
         // Check that todo textbox and Add New button is present  
         expect(element(by.id('todotask')).isPresent()).toBe(true);  
         expect(element(by.id('addtodotask')).isPresent()).toBe(true);  
     });  

     it('Should add a todo task in the todo list', function() {  
         var numOfListItem = null;  
         // Count list item then add another todo task list item no will increase by 1  
         todoList.count().then(function(result) {  
             console.log(result);   
             numOfListItem = result;  
             // Add another todo task  
             todoTextBox.sendKeys("Second todo task");  
             addNewButton.click();  
             expect(todoList.count()).toEqual(numOfListItem+1);  
         });  
     });  

     it('Should remove all the task in todo list', function() {  
         todoList.count().then(function(result) {  
             for(var i=0;i<result;i++) {  
                 todoList.get(i).element(by.model('x.done')).click();  
             }  
             removeTaskButton.click();  
             expect(todoList.count()).toEqual(0);  
         });  
     });  

     it('This test case should fail', function() {  
         expect(todoList.count()).toEqual(1);  
     });  
 });  
 
Run this from terminal with protractor conf.js . It will create a folder named "screenshot" inside project folder. It will also create an image named "The test case should fail.png" . 

In the last test case we are expecting that there will be one todo list item in the web page but our resulted image shows us that there is no todo list item. So from the picture we can understand why the test case failed.




The full code is stored in :  https://github.com/MahmudulHasan/AutomateTodoProtractor

Thanks for your patience. Next post will be on Updating test run result in test rail through Protractor.

~~ A picture is worth a thousand words ~~ 

 
 

Sunday, June 5, 2016

Create and run test with Protractor

Protractor interacts with your application in a real browser. You will be able to automate the functionality of your application by using Protractor. Generally Protractor uses Jasmine framework as it's testing interface. Now we will learn how to write and run test by using Protractor. For this purpose we will use this simple todo angular application :  http://mahmudulhasan.github.io/ToDoAngular/








 
Write test : 
  • Create a project folder and give it a name.
  • Create a folder name "src" inside your project folder.
  • Create a file named basicTest_spec.js
  • Copy this code into the file
 describe('Basic protractor test', function() {  
      it('Page should have a textbox and a button', function() {  
           // Load demo angular site  
           browser.get('http://mahmudulhasan.github.io/ToDoAngular/');  
           // Check that todo textbox and Add New button is present  
           expect(element(by.id('todotask')).isPresent()).toBe(true);  
           expect(element(by.id('addtodotask')).isPresent()).toBe(true);  
      });  
 });  

Here describe meant a test suite and it meant a test case. Then by browser.get() function we can load a url in the browser. Then expect is used to check that certain conditions are met. 

Configuration : 

  • Create a file name conf.js inside main project folder.
  • Copy this code into the file.


 exports.config = {  
  seleniumAddress: 'http://localhost:4444/wd/hub',  
  specs: ['./src/basicTest_spec.js']
 };  

Here seleniumAddress is the address of selenium server and specs shows where your test files are.

Run Test : 


Start selenium server in the command line/terminal with

 webdriver-manager start  


Then open another instance of command line/terminal and run 
 protractor conf.js  

Now it will open a chrome browser as chrome is default for Protractor. Then it will perform test and show out put like :
 [07:52:32] I/hosted - Using the selenium server at http://localhost:4444/wd/hub  
 [07:52:32] I/launcher - Running 1 instances of WebDriver  
 Started  
 .  
 1 spec, 0 failures  
 Finished in 2.794 seconds  
 [07:52:38] I/launcher - 0 instance(s) of WebDriver still running  
 [07:52:38] I/launcher - chrome #01 passed  

Now lets add another test case where it will add a new todo task. Then it will check that todo task count is increased by 1.
 it('Should add a todo task in the todo list',function() {  
           var todoTextBox = element(by.id('todotask'));  
           var addNewButton = element(by.id('addtodotask'));  
           // All the list item   
           var todoList = element.all(by.repeater('x in todoList'));  
           var numOfListItem = null;  
           // Count list item then add another todo task list item no will increase by 1  
           todoList.count().then(function(result) {  
                console.log(result);   
                numOfListItem = result;  
                // Add another todo task  
                todoTextBox.sendKeys("Second todo task");  
                addNewButton.click();  
                expect(todoList.count()).toEqual(numOfListItem+1);  
           });  
      });  
 
The next test case will remove all the todo task from todo list.
 it('Should remove all the task in todo list', function() {  
           var removeTaskButton = element(by.css('button'));  
           // All the list item   
           var todoList = element.all(by.repeater('x in todoList'));  
           todoList.count().then(function(result) {  
                for(var i=0;i<result;i++) {  
                     todoList.get(i).element(by.model('x.done')).click();  
                }  
                removeTaskButton.click();  
                expect(todoList.count()).toEqual(0);  
           });  
      });  
This is all for now. Full code is uploaded in github : https://github.com/MahmudulHasan/AutomateTodoProtractor

Thanks for your patience. Next post will be about Taking screenshot of failed test cases with Protractor.

~~ Let us be kind and help others in need. Let us make this world a better place.
"Peace begins with a smile." - Mother Teresa ~~  

Saturday, June 4, 2016

AngularJS application automation with Protractor (Environment Setup)

The popularity of AngularJS is very high and it is increasing more and more. AngularJS is maintained by Google and Protractor till now is the best end-to-end test framework for AngularJS applications. I want to share my experience with Protractor through this blog.

Protractor Websitehttp://www.protractortest.org/

Protractor API Documentationhttp://www.protractortest.org/#/api

Protractor GitHub urlhttps://github.com/angular/protractor

Environment Setup for Protractor

* Java and NodeJS is needed to create the environment. Download and install :

Java http://www.oracle.com/technetwork/java/javase/downloads/index.html

NodeJS http://nodejs.org/

Open terminal and run "node -v" command to check if NodeJS installed properly.

* Install Protractor globally with npm :

 npm install -g protractor  


Now run "protractor --version" to make sure it installed properly. After installing protractor "webdriver-manager" will also be installed. "webdriver-manager" is a helper tool to run Selenium Server. Download necessary binaries of "webdriver-manager" with : 

 webdriver-manager update

Start Selenium server with : 
 webdriver-manager start  

This will start the Selenium server and you can see the server status at http://localhost:4444/wd/hub .

Congrats you have successfully completed the environment setup for Protractor. kudos for your effort :) . Next blog on Protractor will be >> How to create and run test. 

Thanks for your time. Leave any comment and please suggest if i should add or improve anything.

~~ Automation is important but 
Man is still the most extraordinary computer of all.—John F. Kennedy
 :) ~~