Sunday, April 8, 2012

Scripting Selenium / WebDriver with JavaScript

This is the example code I wanted to write using JavaScript:

http://code.google.com/p/selenium/wiki/GettingStarted

Here is where I looked for help when it wouldn't work[1]:

http://stackoverflow.com/questions/10057163/cant-run-java-example-for-selenium-webdriver

To save you the trouble: my Java is poor.  :-)  That's okay, because I'm not a Java programmer.  I do want to script Java[2], however, using JavaScript and Mozilla Rhino.  A prime candidate for learning how to do so (for me) is writing Selenium / WebDriver tests against their Java API.

I finally got the example code to work.  Here is the command line:

alis-mac-pro:selenium ali$ java -cp ".:/Users/ali/Downloads/selenium-2.20.0/*:/Users/ali/Downloads/selenium-2.20.0/libs/*:/Users/ali/Downloads/rhino1_7R3/*" org.mozilla.javascript.tools.shell.Main -f example.js 
Page title is: Cheese! - Google Search

That's my input, and the program's output.  And here is the example.js file that Rhino executed:


importClass(org.openqa.selenium.By);
importClass(org.openqa.selenium.WebDriver);
importClass(org.openqa.selenium.WebElement);
importClass(org.openqa.selenium.htmlunit.HtmlUnitDriver);

// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface, 
// not the implementation.
var driver = new HtmlUnitDriver();

// And now use this to visit Google
driver.get("http://www.google.com");

// Find the text input element by its name
var element = driver.findElement(By.name("q"));

// Enter something to search for
element.sendKeys("Cheese!");

// Now submit the form. WebDriver will find the form for us from the element
element.submit();

// Check the title of the page
print("Page title is: " + driver.getTitle());




[1] - (BTW, before this, I asked for help on irc.freenode.net on #selenium and on #java and got nearly zero response.  The response was useful, though, but without any follow-up, I was left high and dry.  Theoretically, IRC and other live communication channels are wonderful resources for support, but I find that the reality falls way short of that theory.  Maybe it's just my theory?)

[2] - http://www.mozilla.org/rhino/ScriptingJava.html