JavaScript Executor in Selenium WebDriver - selenium-webdriver

I want to use JavaScript for my script.
I have created an object of JavaScriptExecutor, but executeScript() method is not present. It shows error when I use executeScript() method.
This is the code I have used:
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;
public class GetDomain_JS {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.manage().window().maximize();
System.out.println(driver.getCurrentUrl());
JavaScriptExecutor js=(JavaScriptExecutor) driver;
String domain_name=(String) js.executeScript("return document.domain");
System.out.println(doamin_name);
}
}

It works for me; you had a mistake on JavaScriptExecutor with upper case S. Instead, you should have javascriptExecutor with lower case s.
Try this code:
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class GetDomain_JS {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.manage().window().maximize();
System.out.println(driver.getCurrentUrl());
JavascriptExecutor js=(JavascriptExecutor) driver;
String domain_name=(String) js.executeScript("return document.domain");
System.out.println(domain_name);
}
}
This works for me!! Please thumps up if it does for you!

Please make sure you have imported the correct package.
Expected package for working with Java Script:
import org.openqa.selenium.JavascriptExecutor;
Try this package. This should solve your error.

Explanation:
Add latest jar (I'm using 3.0 beta selenium jar). Import Javascript library package. Take web driver object by casting to JavascriptExecutor and run whatever java script you want to run.
Code:
import com.thoughtworks.selenium.webdriven.JavascriptLibrary;
Object ob = ((JavascriptExecutor) webDriver()).executeScript("return document.domain").toString();
System.out.println(ob);

You can return an Object from executeScript. Later you can get the text out of it.
Object domain_name = js.executeScript("return document.domain");
System.out.println(domain_name.toString());
In this way, you can return values of any type and not just string.

Related

Test Case breaking when running the application as a TestNG test

I wrote a java application to use the selenium webdriver to automate few web application tasks. They all worked fine when run as a Java application.
To use the TestNG reporting feature, I ran the application as a TestNG test instead of JAVA application. The same test which was working as JAVA application is failing when I run as testNG.
However, I'm guessing I've setup the TestNG properly since the first testcase which is used to login to the webapp is passing (webLogin method in the code below)
I'm using chromeDriver. I tried removing the main method to run it as testNG application. But it did not work. I made sure that the element path locators I'm using are still valid while using testNG.
package myPackage;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;
import com.google.common.base.Function;
public class checkNavigation {
public static WebDriver driver;
public static WebDriverWait wait;
public static void main(String args[]) throws InterruptedException{
Configure();
wait = new WebDriverWait(driver, 30);
webLogin();
addClient();
addGoal();
addInsurance();
validateInputs();
endSession();
}
#BeforeTest
public static void Configure() {
System.setProperty("webdriver.chrome.driver", "/Users/divyakapa/Desktop/automation/chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.get("https://example.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test
public static void webLogin() {
getElement(By.xpath("//*[#id=\"id\"]")).sendKeys("admin");
getElement(By.xpath("//*[#id=\"pw\"]")).sendKeys("password");
getElement(By.xpath("//*[#id=\"ember383\"]/div/div/form/button/span")).click();
}
#Test
public static void addClient() {
getElement(By.xpath("//*[#id=\"ember744\"]/button/div")).click();
getElement(By.xpath("//*[#id=\"ember744\"]/div/button[1]/div[2]/div")).click();
getElement(By.xpath("//*[#id=\"newInputFirst\"]")).sendKeys("firstName");
getElement(By.xpath("//*[#id=\"newInputLast\"]")).sendKeys("lastName");
getElement(By.xpath("//*[#id=\"newPersonInputBirthday\"]")).sendKeys("1991");
Select location = new Select(driver.findElement(By.xpath("//*[#id=\"newUserInputProvince\"]")));
location.selectByVisibleText("Place1");
Select isRetired = new Select(driver.findElement(By.xpath("//*[#id=\"alreadyRetiredDropdown\"]")));
isRetired.selectByVisibleText("No");
Select age = new Select(driver.findElement(By.xpath("//*[#id=\"newRetirementAge\"]")));
age.selectByVisibleText("60");
getElement(By.xpath("//*[#id=\"data-entry-modal\"]/div[2]/div/div[1]/div[2]/button[2]")).click();
}
#Test
public static void addGoal() {
getElement(By.xpath("//*[#id=\"ember2328\"]/button/div")).click();
getElement(By.xpath("//*[#id=\"ember2328\"]/div/div[1]/div[2]/button[3]")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"ember2464\"]/ul/li[1]/div/div/div[2]/div/span"))).click();
getElement(By.xpath("//*[#id=\"basicExpenseInputAmount\"]")).clear();
getElement(By.xpath("//*[#id=\"basicExpenseInputAmount\"]")).sendKeys("90000");
getElement(By.xpath("//*[#id=\"ember2563\"]/div/div[2]/div[2]/button[2]")).click();
// Add income
getElement(By.xpath("//*[#class=\"add-button \"]")).click();
getElement(By.xpath("//*[#data-test-model-type=\"income\"]")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#class=\"list-group\"]/li[1]"))).click();
getElement(By.xpath("//*[#id=\"employmentInputName\"]")).clear();
getElement(By.xpath("//*[#id=\"employmentInputName\"]")).sendKeys("Company");
getElement(By.xpath("//*[#id=\"employmentInputSalary\"]")).sendKeys("95000");
getElement(By.xpath("//*[#id=\"employmentInputBonus\"]")).sendKeys("5000");
getElement(By.xpath("//*[#id=\"employmentInputBenefitsInKind\"]")).sendKeys("1000");
getElement(By.xpath("//*[#aria-label=\"Save\"]")).click();
}
#Test
public static void addInsurance() {
getElement(By.xpath("//*[#class=\"add-button \"]")).click();
getElement(By.xpath("//*[#data-test-model-type=\"protection\"]")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#class=\"list-group\"]/li[1]"))).click();
getElement(By.xpath("//*[#id=\"termLifeName\"]")).clear();
getElement(By.xpath("//*[#id=\"termLifeName\"]")).sendKeys("BlueCrossBlueShield");
getElement(By.xpath("//*[#id=\"ukTermProtectionSalaryMultiplier\"]")).clear();
getElement(By.xpath("//*[#id=\"ukTermProtectionSalaryMultiplier\"]")).sendKeys("5");
Select empId = new Select(driver.findElement(By.xpath("//*[#id=\"termLifeInsuranceEmploymentId\"]")));
empId.selectByVisibleText("Company");
getElement(By.xpath("//*[#aria-label=\"Save\"]")).click();
}
#Test
public static void validateInputs() {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if(!(driver.findElements(By.xpath("//*[#data-test-accordion-header=\"goals\"]")).size() > 0)) throw new NullPointerException("Income Failed to ADD");
if(!(driver.findElements(By.xpath("//*[#data-test-accordion-header=\"income\"]")).size() > 0)) throw new NullPointerException("Income Failed to ADD");
if(!(driver.findElements(By.xpath("//*[#data-test-accordion-header=\"protection\"]")).size() > 0)) throw new NullPointerException("Income Failed to ADD");
}
public static WebElement getElement(final By locator) {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver).ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
#Override
public WebElement apply(WebDriver arg0) {
return arg0.findElement(locator);
}
});
return element;
}
#AfterTest
public static void endSession() {
driver.close();
driver.quit();
}
}
Running the above code, the get the following error :
Default suite
Total tests run: 5, Failures: 4, Skips: 0
I also see that it takes a lot of time (about 10 seconds) before the page is logged in even though that test passes. This does not happen when I run the code as a Java application
Can you show which tests are actually failing? if you are looking for order in testng test execution, it doesn't come by default , so if you have to run test2 after test1 and test3 after test2 etc then you have to use priority(lower the number higher the priority) for ex,
#Test(priority=1)
public void Test1() {
}
#Test(priority=2)
public void Test2() {
}
#Test(priority=3)
public void Test3() {
}
hope this helps
No, testng never guarantees ordering by default
TestNG relies on reflection. The Java Reflection APIs does not guarantee the method order when we use it to introspect a class to find out what are the test methods that are available in it. So the order of independent methods (Methods that dont have either soft or hard dependency) execution is never guaranteed.
Soft dependency - This is usually achieved in TestNG by using the priority attribute for the #Test annotation. Its called a soft dependency because TestNG will continue to execute all the methods even though a previous method with a higher priority failed.
Hard dependency - This is usually achieved in TestNG by using either dependsOnMethods (or) dependsOnGroups attribute for the #Test annotation. It's called a hard dependency because TestNG will continue to execute a downstream method if and only if an upstream method ran successfully.
By default testng executes methods in alphabetical order of the method names. Typically you would not be using main method for testng. Annotations along with priority are used to set the sequence of executions
Testng framework will run the test methods in alphabetical order. I could see your test methods are dependent and it should in the order. You can set the priorities for your test methods the way you want it to run.
You can refer the below link to set the priority.
TestNG priority set

how to click dynamic links like ads on a webpage using selenium

I am new to Selenium webdriver, and trying to test a webpage which has some dynamic links (dynamic ads). Example : ads on https://mail.rediff.com/cgi-bin/login.cgi
I tried with xpath ,classname and id but none of these is working.It is happening because every time new content is displaying on the page so it is not able to find the element and throwing Exception in thread "main":
org.openqa.selenium.NoSuchElementException: Unable to locate element: #map.
my code is :
package Selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Image_Link {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//System.setProperty("webdriver.chrome.driver", "E://chromedriver_win32//chromedriver.exe");
//driver = new ChromeDriver();
System.setProperty("webdriver.gecko.driver", "E://geckodriver-v0.21.0-win64//geckodriver.exe");
driver = new FirefoxDriver();
Actions actions = new Actions(driver);
driver.get("https://mail.rediff.com/cgi-bin/login.cgi");
//WebElement Dynamic_ads=driver.findElement(By.className("rhs-area floatR"));
WebElement Dynamic_ads=driver.findElement(By.id("map"));
actions.moveToElement(Dynamic_ads).perform();
WebElement ad_Link = driver.findElement(By.cssSelector("#map > area:nth-child(2)"));
actions.moveToElement(ad_Link);
actions.click();
actions.perform();
//driver.navigate().to("www.google.com");
//String value = driver.findElement(By.id("hplogo")).getAttribute("title");
}
}
The elements for the dynamic ads cannot be found because it isn't fully loaded yet on load page. I recommend adding an explicit wait time for the specific add you're looking for. You can check out this link here for more information.
Anyhow, here's your solution:
1.)Implement WebDriverWait: WebDriverWait wait = new WebDriverWait(driver, 20);
2.) Change your Dynamic_ads data to wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("map"))); then do Dynamic_ads.click(); afterwards.
OR
2.) Change your Dynamic_ads data to wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//map[#id='map']/*"))); then do Dynamic_ads.click(); afterwards. NOTE: This will pick the first child node.

verify search working proprly using Selenium

I am beginner for Selenium, just I want to check that search of the website working properly. Means when I enter any keyword in the search box and click on search is it provides correct search result. How to Check using Selenium WebDriver. Please guide me.
You should provide more details about your query
for example you should include the URL your are working on or a similar URL for the one you are working on
You can use an item property from the search result page as an assertion point for your test
Try below code
package StackOverFlow.StackOverFlow;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class App
{
#Test
public void test () throws InterruptedException{
System.setProperty("webdriver.chrome.driver", "C:\\Chrome\\2\\chromedriver.exe");
WebDriver Dr = new ChromeDriver();
Dr.manage().window().maximize();
Dr.get("http://www.conns.com");
Thread.sleep(4000);
WebElement ele = Dr.findElement(By.xpath(".//*[#id='search']"));
ele.sendKeys("furniture");
ele.sendKeys(Keys.ENTER);
Thread.sleep(4000);
String result= Dr.findElement(By.xpath("/html/body/div[3]/div/div[4]/div[2]/div/div[1]/h1")).getText();
Assert.assertEquals("Furniture & Mattresses", result);
}
}
I used a very obvious element (Furniture & Mattresses) on the page to assert against its text

Selenium sample program: Getting Error org.openqa.selenium.WebDriverException: expected expression, got end of script

I am trying to do a sample program with selenium webdriver. I am using libraries from Selenium-java-2.53.1.
Here is my sample program
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
public class ScrollWebPage {
WebDriver driver;
String URL="https://www.gmail.com";
#BeforeClass
public void setUp(){
driver = new FirefoxDriver();
driver.get(URL);
driver.manage().window().maximize();
}
#Test(priority=1)
public void scrollingToBottom(){
((JavascriptExecutor) driver).executeScript(URL, "window.scrollTo(0,document.body.scrollHeight)");
}
#AfterClass
public void tearDown(){
driver.quit();
}
}
The page is getting opened but it is not able to scroll down. seems an issue with executeScript()
Please help
.executeScript() expecting JavaScript string expression as first arguments while you are providing simply a String as Url which is not an JavaScript expression as exception says, You need to change :-
((JavascriptExecutor) driver).executeScript(URL, "window.scrollTo(0,document.body.scrollHeight)");
to
((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)");
Note :- .executeScript() expect arguments like String arg0, Object... arg1 which means first arguments should be String but it should be JavaScript expression and second arguments should be Array of Object like Object[]
In your case no need to provide URL as arguments if you simply want to execute scrolling function.
Hope it will help you..:)
Simply Use as below to see the scroll working. Try in some other page because gmail don't have a much bigger page to feel the scroll.
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,2500)");

NullPointerException in WebDriverBackedSelenium

I'm new to selenium and still exploring it. I'm trying to test an ajax element on a site. On clicking the element some text pops on some area on the page. I've run this test on RC as well as WebDriver. It's working fine. Now I want(just out of curiosity) to test it via WebDriverBackedSelenium. But it's throwing an error. The code is:
import com.thoughtworks.selenium.SeleneseTestBase;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.internal.WrapsDriver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CheckElements extends SeleneseTestBase {
#Before
public void setUp() throws Exception {
String baseUrl = "path/to/the/site";
WebDriver driver = ((WrapsDriver) selenium).getWrappedDriver();
selenium = new WebDriverBackedSelenium(driver, baseUrl);
}
The error is:
java.lang.NullPointerException
at com.CheckElements.setUp(CheckElements.java:17)
I believe the main problem is in setup method. I'm using selenium standalone server 2.0 and junit 4.7. Can you please tell where am I going wrong?
Another Question??
If I write the same test as below, the test runs fine but it doesn't give error even if the text doesn't matches what is required.
import com.thoughtworks.selenium.SeleneseTestBase;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class New extends SeleneseTestBase {
WebDriver driver;
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
String baseUrl = "path/to/the/link";
selenium = new WebDriverBackedSelenium(driver, baseUrl);
}
I hope I'm clear in my questions. Thanks.
I would highly expect this to be the issue:
WebDriver driver = ((WrapsDriver) selenium).getWrappedDriver();
The driver instance is probably null.
The difference being in your other test, you are explicitly creating it into a FirefoxDriver:
driver = new FirefoxDriver();

Resources