Sunday, April 26, 2015

JavaScript Executor

JavaScriptExecutor its an Interface in Selenium WebDriver. It provides way to inject JavaScript in browser through WebDriver.

We have two methods in it :- 

1. executeScript(java.lang.String script, java.lang.Object... args).
2. executeAsyncScript(java.lang.String script, java.lang.Object... args).

Now, the question is why we need it and how we use it in our code ?

First, many times in our code we need to scroll page, click on particular element if failed with driver click, prompt user with some text on browser, to get the JS errors on page and many more. Basically it enhances coding capabilities and enables tester to  achieve end results. 

Below are the some examples using JavaScriptExecutor:- 

This is the syntax :- 

JavascriptExecutor js = (JavascriptExecutor) driver;   
js.executeScript(Script,Arguments); 

Examples:- 


Alert:- 
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello');");

To get the title of the page:- 
js.executeScript("return document.title");
need to cast in String and it will print the title of the page like this:-
String title=(String)js.executeScript("return document.title"); 
System.Out.Print(title);

To get the date and time of the last modification:- 
js.executeScript("return document.lastModified"); 

To get the errors on page:- 
String errorsOnPage =(String) js.executeScript("return window.jsErrors"); 

To get the URL :- 
String URL=(String)js.executeScript("return document.URL");  

To click on element:- 
js.executeScript("arguments[0].click();", element);

another way to move to particular element :- 
js.executeScript("var evt = document.createEvent('MouseEvents');" + "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" + "arguments[0].dispatchEvent(evt);",element);

To refresh the browser:- 
js.executeScript("history.go(0)");

To scroll vertically/horizontally by 100 pixels :- 
Vertical scroll -> js.executeScript("window.scrollBy(0,100)");
horizontal scroll ->  js.executeScript("window.scrollBy(100,0)");

To navigate to other page :- 
js.executeScript("window.location = 'http://www.google.com'");

To inspect and send some values:- 
js.executeScript("document.getElementById('xyz').value='xyz'");


Thursday, November 20, 2014

Mouse events

Using Selenium to perform drag-drop, Hover, move to particular coordinate, double click and right click we have Actions class for under "java.lang.Object org.openqa.selenium.interactions.Actions" to perform above actions according o the project needs.

Example 1:-
First we need to create object of Actions class by writing this :-                                    
                                           

          
It ask you to import package of Actions class, if you are using eclipse ide after importing package problem will resolve as it requires the argument of  WebDriver type.
Now that argument needs to be passed because the default constructor of the Actions class has predefined argument in it which is showing error. So to resolve this we need to pass variable of WebDriver type like this:-

WebDriver driver = new FirefoxDriver();

Actions actobj=  new Actions(driver);

Now to work on any element of web page we need to create WebElement of it and pass it to different methods of Actions class.

WebElement actionvariable = driver.findElement(By.xpath("//xpath"));

actobj.moveToElement(actionvariable).build().perform();

here build().perform(); is used because many times events are not there associated with the element, so build().perform() creates an event and performs the action.

Example 2:- 
Moving mouse to particular coordinates in the screen.

We have method  dragAndDropBy(source, xOffset, yOffset), here source is the WebElement of starting position  and xOffset, yOffset are the integer values of the x and y coordinates.
Now to fetch the values of x and y coordinates we need to use get location method

WebElement element = driver.findElement(By.xpath("//xpath"));
element.get location();

It will return the WebElement of Point type, so we need to store it in variable of Point type like this:-
Point p = element.get location();

Now, p.getX() and P.getY(); 
will return integer values for X and Y coordinates that we can pass it in dragAndDropBy(source, xOffset, yOffset) method and perform our desired action.

Example 3:- 
Sometimes we are able to inspect element but at the time of script execution we are not to perform click operation on particular button or link without any error using Selenium, to handle this situation Selenium has click method under Actions class syntax :-

click(webElement):Actions-Actions , we need to pass the WebElement in it. and we will be able to perform click method with Webelement as argument.

So again we need to create WebElement of particular element and then we need to pass it in Click(WebElement) as argument.

So, in this way we can perform task as per the requirements. Below is the image attachment for the different methods available under Actions class.

Wednesday, October 29, 2014

getText() and getAttribute("") method

To fetch the tooltip or text written on any webpage there are differences in the use of getText() and getAttribute() method. In this post I have explained with an example where to use getText() and getAttribute()

getText() will work only for those tags which has starting and ending tag

for example, you have span :-

<Span class="ankur"> sample text </span>

if you write
finddelement(By.xpath("//span[@class='ankur']")).getText();

Output :-sample text 

but if you have span like this i.e without ending tags

<Span class="ankur" value = "sample text"> 

and you write:-
finddelement(By.xpath("//span[@class='ankur']")).getText();

in this case it will not work, as getText method works only with those tags which has starting and ending tag in it and starting and ending tags mostly found in hyperlinks and static elements on the page.

So here we should use getAttribute method like this :-

finddelement(By.xpath("//span[@class='ankur']")).getAttribute("value");

Output:- sample text

Now moving to getAttribute("") method if you want to fetch the value from the text entered in the text field. Again here getText() will not work here you have to use getAttribute("value") with "value" as a parameter in it. As if whatever we write in text field it get saved in the value attribute of the element.

Example of firefoxDriver Class

Using selenium to simulate browser we have classes for different browser for example we have FirefoxDriver class for firefox browser. So any simulations can be performed on browser by methods of the class  FireforDriver and there are many methods written under it for instance close and open of the browser.
WebDriver is API it is available as "JAR" file or we can say its a zip file in JAVA. User can write their own script and making JAR of the same.

Lets discuss scenario of opening and closing of browser using WebDriver:-

FirefoxDriver objvar = new FirefoxDriver();
objvar.close();

this code will open/launch firefox browser and in next line will close the browser.

By writing new FirefoxDriver();

it will create a object of FirefoxDriver and to use we need to store it in a variable which needs to be of FireforDriver type.

i.e FirefoxDriver objvar = new FirefoxDriver();

Objvar is variable in which reference of the object of firefoxDriver class is stored .

Now when we write objvar. we will get list of all static and non-static methods and other variables available under FirefoxDriver class

At the time of execution it will open the firefox browser and then close it , just because at the time of object creation it calls the constructor of the class which has the code to launch the Firefox browser.

Other  basic method available are Click(), getText(), getAttribute("") and so on .

Lets take example in which we can validate that we have logged in the page successfully.
After login page says "Welcome username".

So we can fetch the text welcome and check if we get "welcome " we can say test case pass else fail

Example:-

String text =objvar.findelementByXPath("//xpathofwelocome").getText();
and then we can compare it to get results .

If we want to fetch that value from any attribute in that case we will write this
String attri = bjvar.findelementByXPath("//xpathofwelcome").getAttribute("attributename");  


Monday, October 27, 2014

Know your x-Path

Inspecting elements using xpath in particular page is the most crucial step while automating web app just because if your xpath is not unique and stable enough then your script is of no further use, in this post I will explain example on the following:-
  • Mixture of structure and attributed xpaths in-order to get stable and unique xpath.
  • Parents/child structure of html and finding xpath from it.
  • Elements having same tabname and info in that case, use of indexing to fetch the required element in page.
  •  Where to use "click" and "click at" method.
  •  Use of storeXpathCount.
lets start with all of this in detail :-

A. How to check that your xpath is stable and unique?  A good answer to this is tester should login and visit the page atleast 2 or 3 times and verify the same xpath.

B. Moving to next point i.e how to inspect element through text between the HTML tags below are the examples:-

//tagname[text()='text in the page']

we can also use with contains method if we have extra space in the heading or text in the page, so to avoid that problem tester should use contains method and below is the example

//tagname[contains(text(),'heading or text in page')]

If we have title attribute available and we want to use it with contains method so below is the example:-

//tagname[contains(@title,'heading or text in page')]

C. For parent child structure I have taken an example  to illustrate:-

 <td class = "searchUI" align= "left">
             <span> search</span>
  </td>

here you can see we do not have any attribute with span only we have tagname i.e span, so we can't say this is stable and unique if the text changes every time say currently it is "search" and on refresh it changes to "find".
So in that case we have to  look at the parent of that span which is "td"tag here, we can create xpath like this :-

//td[@class='searchUI']/span

Now if we have multiple span with some attribute under the same "td" then we can go for attribute like
//td[@class='searchUI']/span[@class='module']

it will look for "td" then it will look for "span" which has class attribute.

Again now what if there is no attribute available and multiple spans under tag 'td':-

xpath=(//td[@class='searchUI']/span)[2]

this is called indexing.

Below is the pictorial representation of Google search page and its her-racy :-











D. In general we do use "click" method over "click at" as the execution of "click at" is slow as comapred to "click", so "click at" is preferred to use when you are not able to click on particular button using "click".

E. Lets discuss one more error in the page i.e you are able to inspect element on page but its not visible when you click i.e  UI has no element but u are able to inspect

Usually in tables we have some hidden buttons or elements  available so we can count the all buttons available and filter out which is visible or which is not in use by using storeXpathCount.

So on the basis of available xpath on page it will give count of the xpath

storeXpathcount ->command in selenium ide

x ->variable to store result of the above command

echo ${x}-> to view the results

Below is the pictorial representation:- 


Wednesday, October 15, 2014

Ways to implement WebDiver Wait

In previous post I had discussed about locating element whose x-path is dynamic, so in continuation to the same in this discussion  I will share a very common problem i.e errors of exception for no such element.

So what's the issue and how we should cater this ?

Problem:-
The ajax in page to get new data or info and it takes a few seconds more after page load to load that element which you are looking for.

Solution:-
To handle this in Selenium Webdriver we have 3 ways as per below:-
1. Thread.sleep().
2. implicit Wait().
3. Explicit wait.

Explanation:-
1. Thread.sleep(milliseconds)

It will stop the execution of thread to sleep as per the number defined in milliseconds as parameter for instance:-
Thread.sleep(10000);
It will throw Interrupted Exceptions for which  you need to add try catch or add exceptions for the same. It will pause your script for the time that you mentioned as parameter.

Not recommended to use this as it increases execution time and its  preferred to use when element is loaded but its not visible or enabled.

2. Implicit Wait()

It will tell  WebDriver to wait for that particular element if not available at that moment. So,  WebDriver will not throw the exception of no such element immediately.

Syntax:-
driver.manage().timeouts().implicitlywait(90,TimeUnit.SECONDS);

Here we have passed 2 arguments i.e "90" and "TimeUnit.SECONDS" of java.util.concurrent.TimeUnit.SECONDS so, it will wait for 90 secs and will not throw Exception of no such element till that time.

3. Explicit wait or Webdriver wait()
It will check in every 500 millisec until it throws successful or timeout.

Syntax:-
WebDriverWait wait = new WebDriverWait(driver, 90);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("some path")));

Expected conditions with explicit wait can be of following which is not there in implicit wait is as per below :-

elementToBeClickable
elementToBeSelected

and many more options are avalible just hit crtl+space after period sign.

Thursday, September 18, 2014

Finding relative x-path of dynamic headings/text on pages whose attribute is unavailable.

For instance, We are on web page which has dynamic heading(its being changing everytime whenever we refresh the same page) like this 
In first visit page heading was 
"My first example 1",
after refresh its now 
"My first example 2" 
and then 
"My first example 3" 
and
"My first example 4" and so on....
when we check this in web debugger their HTML is as follows:-

<span>My first example 1</span>
<span>My first example 2</span>
<span>My first example 3</span>
<span>My first example 4</span>.... here we have starting tag box and ending tag box without any attribute.

From above span we can say that we don't have any attribute with this, If it has class attribute then it will appear as 
<span class= "example">My first example 1</span>, 
then we could have used that attribute to create xpath //span[@class='example']
but here scenario is different,So to pick that heading we will use 'contains' and 'starts-with function' to make relative x-path as follows:-
//span[contains(text(),'My first example ')]
Or we can use 
//span[starts-with(text(),'My first example')]
Webdriver will look into our HTML it will search for 'span'(tagname) which contains any text with 'My first example' regardless of its being changed to 'My first example 2', 3 , 4 and so on...
Note:- This will work for those elements which has both starting and ending tags like in above example <span>......</span>