Introduction to WebDriver part003

From Training Material
Jump to navigation Jump to search

<slideshow style="nobleprog" headingmark="⌘" incmark="…" scaled="false" font="Trebuchet MS" >

Title
Selenium with javascript
Author
David Parkin

</slideshow>

Introduction to Javascript⌘

Javascript and Java are different, don't get confused.

variables - defined by var variable

var num = 12;

use document.write, or doucment.element.innerHTML to display something.

document.write(num);

Introduction to Javascript - loops⌘

for, while

for (i = 0; i < 4; i++) {
        a[i] = i;

    }


Introduction to Javascript - if⌘

if

if(true){
do something
}

Introduction to Javascript - functions⌘

functions - first class

function myfunc(){
do something
}

to call the function

myfunc();

types - dynamicaly typed

Selenium-webdriver JS⌘

There are two popular bindings for Javascript (nodejs) – don't get confused.

We'll be using the offical selenium bindings

Writing scripts in JavaScript allows us to automate test runs, rather then having to manually run it from the IDE,
and also allows us to do more.

Natively webdriverJS only supports chrome, we will be user selenium server.

This allows us to run our tests on multiple browsers.

We can also run our tests on multiple machines.

webdriverJS is a completely asynchronous API.

Installing Selenium-webdriver JS⌘

First we need to install node.js.

for linux:

sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

For windows:

Go to nodejs.org and download the latest version.

Run the msi file and accept the default options.

You may need to restart windows before npm will work.

Press WindowsKey + R and type 'cmd' + Enter.

Type 'npm install selenium-webdriver' + Enter.

Install your favourite IDE/editor for Javascript, possibly netbeans.

download chromedriver and move to a suitable location.

Go to start, search for system variables and open > edit the system environment variables > click on enviroment variables.

Make sure the PATH variable links to your chromedriver location.

To add a path, put a ; at the end and then input the path to chromedriver. Dont remove the current paths.

Selenium-webdriver⌘

we can use a module using nodejs require.

to use webdriver

=require('selenium-webdriver');

we can assign this to a variable.

var webdriver = require('selenium-webdriver');

To execute our selenium commands we need to create a driver variable.

var driver = new webdriver.Builder().Build();

This will use default settings for browser.

we can set other capabilities between Builder() and Build().

var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();

The new keyword creates a new object instance of a class. We will talk about this more later.

Selenium-webdriver cont.⌘

There are many useful methods we can use with our driver variable.

Take a look at the api http://selenium.googlecode.com/git/docs/api/javascript/module_selenium-webdriver.html.

to open a specific url

driver.get('url');

to find an element(s)

var element = driver.findElement(s)(locator);

This represents a DOM element. Basically just a web element you can apply functions to.

findElements returns an array of all elements that match your locator.

We can apply different methods to our element

click() - clicks

sendKeys('keys') - sends keyboard input

clear() - clears a textfield

getText() - get text contained within the element

getAttribute(att) - gets a specific attribute of that element

submit() - submit a form


Example Code 2⌘

// simple test

var assert = require('assert'),
    webdriver = require('selenium-webdriver');
var driver;
describe('Google Search', function() {
  
  this.timeout(60000);
  
  driver = new webdriver.Builder().
  usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(webdriver.Capabilities.chrome()).build();
  
  


  it('should work', function(done) {
    driver.get('http://www.google.com');
    var searchBox = driver.findElement(webdriver.By.name('q'));
    searchBox.sendKeys('webdriver');
    searchBox.getAttribute('value').then(function(value) {
      assert.equal(value, 'webdriver');
       
    });
done();
  
  });

 after(function(done) {
    driver.quit().then(function(){
        done();
    }); }); 
});

Example Code 3⌘

// simple test

var assert = require('assert'),
    webdriver = require('selenium-webdriver');
var driver;
describe('Google Search', function() {
  
  this.timeout(60000);
  
  driver = new webdriver.Builder().
  usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(webdriver.Capabilities.chrome()).build();
  
  


  it('should work', function(done) {
    driver.get('http://www.google.com');
    var searchBox = driver.findElement(webdriver.By.name('q'));
    searchBox.sendKeys('webdriver');
    searchBox.getAttribute('value').then(function(value) {
      assert.equal(value, 'webdriver');
       done();
    });

  driver.quit();
  });

});


Sometimes you just have to Wait⌘

There are two kinds of waiting. Implicit and Explicit.

An explicit wait will wait a certain amount of time before attempting something.

An implicit wait will act as soon as possible.

e.g. element.click() will act as soon as the element is visible,

if implicit wait times out before its visible, the command will error.

Implicit wait can be set by driver.manage().timeouts().implicitlyWait(ms).

There's also a driver.sleep(ms) function.

Testing with mocha⌘

run with mocha testname.js
install with npm install mocha -g

describe this is a description you can apply to a group of test cases

it - this is a particular test case

assert - assert something is what you expect, i.e assert(title, "google")
will cause the test to fail if the page titles is not google.

after(), before() and aftereach(), beforeeach() are very useful functions


You can use other assertion library's with mocha, such as chai, however it is recommended to use the selenium-webdriver asserting library by

requiring selenium-webdriver/testing/assert

Exercises1⌘

Write a test using only webdriver to load up google homepage

Example1⌘

var webdriver = require('selenium-webdriver');

driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();

driver.get('http://www.google.co.uk');
driver.quit();

Exercises2⌘

write a test to open google and enter some text

now add a submit

then make sure the test closes

Example2⌘

var webdriver = require('selenium-webdriver');

driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().timeouts().implicitlyWait(10000);
driver.get('https://www.google.co.uk');
driver.findElement(webdriver.By.id('gbqfq')).sendKeys('cheese');
driver.findElement(webdriver.By.name('btnG')).click();
driver.findElement(webdriver.By.partialLinkText("Wikipedia")).click();
driver.quit();

Exercises3⌘

integrate mocha into the simple google test

run test on standalone server

run test with firefox

run the test on both firefox and chrome

assert title of google page

Example3⌘

var webdriver = require('selenium-webdriver'),
	test = require('selenium-webdriver/testing');

drive = webdriver.Capabilities.chrome();
testG(drive);
drive = webdriver.Capabilities.firefox();
testG(drive);

function testG(drive){
test.describe('test google search', function()
{
	this._enableTimeouts = false;
		driver = new webdriver.Builder().usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(drive).build();
		driver.manage().timeouts().implicitlyWait(10000);
	
	test.it('searching cheese', function()
	{
		driver.get('https://www.google.co.uk');
		driver.findElement(webdriver.By.id('gbqfq')).sendKeys('cheese');
		driver.findElement(webdriver.By.name('btnG')).click();

                driver.quit().then(function()	{
			done();
		});
	});
	


});}

Exercises4⌘

Using the wallet application, write a test that logs in and then logs out.

Example4⌘

// simple test
var Name = process.env.NAME;
var drivers = "chrome";
var assert = require('assert'),
    test =  webdriver = require('selenium-webdriver/testing')
    webdriver = require('selenium-webdriver');
var driver;

drive = webdriver.Capabilities.chrome();
testG(drive);
drive = webdriver.Capabilities.firefox();
testG(drive);

function testG(drive){
test.describe('test google search', function()
{
    this._enableTimeouts = false;
    test.before(function()  {
        driver = new webdriver.Builder().usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(drive).build();
        driver.manage().timeouts().implicitlyWait(10000);
    });
 
 
 
 
  test.it('should Login', function() {
    driver.get('http://localhost/wallet/index.php');
    driver.findElement(webdriver.By.css('input[type=\'text\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'password\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'submit\']')).click();
 
 
});
 

 test.it('should Logout', function() {
    driver.findElement(webdriver.By.id('log-out')).click();
 
 
});
 
test.after(function(done) {
    driver.quit();
}); 
});
 
 
}
 


}

Exercises5⌘

Now write another test that creates an account.

Example5⌘

// simple test
var Name = process.env.NAME;
var drivers = "chrome";
var assert = require('assert'),
    test =  webdriver = require('selenium-webdriver/testing')
    webdriver = require('selenium-webdriver');
var driver;

drive = webdriver.Capabilities.chrome();
testG(drive);
drive = webdriver.Capabilities.firefox();
testG(drive);

function testG(drive){
test.describe('test google search', function()
{
    this._enableTimeouts = false;
    test.before(function()  {
        driver = new webdriver.Builder().usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(drive).build();
        driver.manage().timeouts().implicitlyWait(10000);
    });
 
 
 
 
  test.it('should Login', function() {
    driver.get('http://localhost/wallet/index.php');
    driver.findElement(webdriver.By.css('input[type=\'text\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'password\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'submit\']')).click();
 
 
});
 
test.it('should Create account', function() {
    driver.get('http://localhost/wallet/index.php');
    driver.findElement(webdriver.By.id('add-account')).click();
    driver.findElement(webdriver.By.css('input[type=\'text\']')).sendKeys(Name);
    driver.findElement(webdriver.By.css('input[type=\'submit\']')).click();
 
});

 test.it('should Logout', function() {
    driver.findElement(webdriver.By.id('log-out')).click();
 
 
});
 
test.after(function() {
    driver.quit();
}); 
});
 
 
}

Exercises6⌘

Write a test that will delete an account.

Example6⌘

// simple test
var Name = process.env.NAME;
var drivers = "chrome";
var assert = require('assert'),
    test =  webdriver = require('selenium-webdriver/testing')
    webdriver = require('selenium-webdriver');
var driver;

drive = webdriver.Capabilities.chrome();
testG(drive);
drive = webdriver.Capabilities.firefox();
testG(drive);

function testG(drive){
test.describe('test google search', function()
{
    this._enableTimeouts = false;
    test.before(function()  {
        driver = new webdriver.Builder().usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(drive).build();
        driver.manage().timeouts().implicitlyWait(10000);
    });
 
 
 
 
  test.it('should Login', function() {
    driver.get('http://localhost/wallet/index.php');
    driver.findElement(webdriver.By.css('input[type=\'text\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'password\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'submit\']')).click();
 
 
});
 
it('should Delete', function() {
    driver.findElement(webdriver.By.xpath('//span[contains(@id,\'details\')]/a')).click();
    driver.findElement(webdriver.By.id('edit-account')).click();
    driver.findElement(webdriver.By.id('delete-account')).click();
 
 
});

 test.it('should Logout', function() {
    driver.findElement(webdriver.By.id('log-out')).click();
 
 
});
 
test.after(function() {
    driver.quit();
}); 
});
 
 
}

Exercises8⌘

Run your test on multiple browsers.

Verify if an account exists before logging out.

How can we deal with creating an account with a name that already exists and then deleting it.

Example8⌘

// simple test
var Name = process.env.NAME;
var drivers = "chrome";
var assert = require('selenium-webdriver/testing/assert'),
    webdriver = require('selenium-webdriver'),
    test = require('selenium-webdriver/testing');
var driver;
var fs = require('fs');
for (i=0; i<1; i++)   {
test.describe('Google Search', function() {
 
  this.timeout(10000);
 
  test.before(function() {
        if (drivers === "chrome")  {
        driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().timeouts().implicitlyWait(10000);}
        else{
        driver = new webdriver.Builder().
    usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(webdriver.Capabilities.firefox()).build();
driver.manage().timeouts().implicitlyWait(10000);}
 
    });
 
 
 
 
  test.it('should Login', function() {
    driver.get('http://localhost/wallet/index.php');
    driver.findElement(webdriver.By.css('input[type=\'text\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'password\']')).sendKeys("test");
    driver.findElement(webdriver.By.css('input[type=\'submit\']')).click();
 
 
});
 
test.it('should Create account', function(done) {
    driver.get('http://localhost/wallet/index.php');
    driver.findElement(webdriver.By.id('add-account')).click();
    driver.findElement(webdriver.By.css('input[type=\'text\']')).sendKeys(Name);
    driver.findElement(webdriver.By.css('input[type=\'submit\']')).click();
    var named = driver.findElement(webdriver.By.css("span[id^='account'"));
    //var title = named.getText();
   var name = named.getText();
        assert(name).equalTo('Account: david');
    
    
    driver.takeScreenshot().then(function(data) {
  writeScreenshot(data, 'out1.png');
});
           
     });
 
 function writeScreenshot(data, name) {
  name = name || 'ss.png';
  var screenshotPath = '/home/ubuntu/Desktop/';
//ubuntu path /home/ubuntu/Desktop/
 
  fs.writeFileSync(screenshotPath + name, data, 'base64');
 
};
 
test.after(function() {
    drivers = "firefox";
    driver.quit();
}); 
});
 
 
}

Exercise9⌘

Write a test using ActionSequences.

Go to hover menu and click on an item.

Example9⌘

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().timeouts().implicitlyWait(5000);
driver.get('http://54.75.220.18');
var element1 = driver.findElement(webdriver.By.css('#om-leaf-om-u1-1981824389-1>a'));
Actions = new webdriver.ActionSequence(driver).
        mouseMove(element1).perform();

var element2 = driver.findElement(webdriver.By.linkText('General Item 1'));
Actions = new webdriver.ActionSequence(driver).
        click(element2).perform();


driver.quit();

Multiple browsers⌘

we can only run chrome natively remember, we need to install selenium standalone server.

We just need to set capabilities to different browser.

IE is annoying and needs you to do some stuff before you can use it. (please don't have IE 11)

https://code.google.com/p/selenium/wiki/InternetExplorerDriver

Don't forget to downloads chromedriver.

Other capabilities⌘

other options for setting capabilites

 new webdriver.Builder().
	usingServer("http://127.0.0.1:4444/wd/hub").
   withCapabilities(webdriver.Capabilities.chrome()).
   build(); 

new webdriver.Builder().
	usingServer("http://127.0.0.1:4444/wd/hub").
   withCapabilities(webdriver.Capabilities.firefox()).
   build(); 

new webdriver.Builder().
	usingServer("http://127.0.0.1:4444/wd/hub").
   withCapabilities(webdriver.Capabilities.ie()).
   build();

Page Object Model⌘

The Page Object Model is a widely used design pattern for selenium.

When you have a large suite of tests, code can become repetitive.

The page object model makes it easier to maintain scripts, and to create new ones.

Here is an example. (hopefully)

https://github.com/jamesottaway/js-page-object

function PageObject(testdriver, url)	{
	this.Assert = require('assert');
	this.base_url = url;
	this.driver = testdriver;

	
}

PageObject.prototype.url = function(inputURL) {
		driver.get(inputURL);
	}

PageObject.prototype.find = function(locator) {
	driver.findElement(locator);
}

function GoogPage(testdriver, url, input)	{
	PageObject.call(this, testdriver, url);
	this.input = input;
}

GoogPage.prototype = Object.create(PageObject.prototype);
GoogPage.prototype.constructer = GoogPage;

GoogPage.prototype.search = function(page, keys)	{
	driver.findElement(webdriver.By.name('q')).sendKeys(keys);
	driver.findElement(webdriver.By.name('go')).click();
}


var webdriver = require('selenium-webdriver');
 driver = new webdriver.Builder().
    usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(webdriver.Capabilities.chrome()).build();

var page = new GoogPage(driver, "http://www.bing.com", "cheese");
page.url("http://www.bing.com");
page.search("cheese");
driver.quit();


Page Object Model Login⌘

function PageObject( url)	{
         this.webdriver = require('selenium-webdriver');
	this.Assert = require('assert');
	this.base_url = url;
	this.driver = this.driversb(this.webdriver);

	
}

PageObject.prototype.driversb = function(webdriver)	{
	return driver = new webdriver.Builder().
    usingServer("http://127.0.0.1:4444/wd/hub").withCapabilities(webdriver.Capabilities.chrome()).build();
}

PageObject.prototype.url = function(inputURL) {
	inputURL = inputURL || this.base_url;
		driver.get(inputURL);
	}

PageObject.prototype.find = function(locator) {
	return driver.findElement(locator);
}

function Login( url)	{
	PageObject.call(this, url);

}

Login.prototype = Object.create(PageObject.prototype);
Login.prototype.constructer = Login;

Login.prototype.user = function(username){
	driver.findElement(this.webdriver.By.css('input[type=\'text\']')).sendKeys(username);
}

Login.prototype.pass = function(pass){
	
    driver.findElement(this.webdriver.By.css('input[type=\'password\']')).sendKeys(pass);
}

Login.prototype.submit = function(){
	driver.findElement(this.webdriver.By.css('input[type=\'submit\']')).click();
}


function GoogPage( url)	{
	Login.call(this, url);
}

GoogPage.prototype = Object.create(Login.prototype);
GoogPage.prototype.constructer = GoogPage;

GoogPage.prototype.search = function(keys)	{
	this.find(this.webdriver.By.name('q')).sendKeys(keys);
	driver.findElement(this.webdriver.By.name('go')).click();
}


module.exports.GoogPage = GoogPage;


var PageObject = require('./log.js');

var webdriver = require('selenium-webdriver');

var page = new PageObject.GoogPage("http://localhost/wallet/index.php", "cheese");
page.url();
page.user("demo");
page.pass("demo");
page.submit();
driver.quit();