Selenium-RC: Writing tests in JavaScript Using the Java Client Driver

JavaDoc reference is available

You can use Selenium RC to write your tests in JavaScript, using the Rhino JavaScript interpreter for Java. Rhino lets you write JavaScript against arbitrary Java classes; Selenium RC provides Java classes, so you can use those Java classes to write your tests.

First, download js.jar from the Rhino website. You can start the JS shell by running "java -jar js.jar". See JavaScript Shell for more information about starting the JS interpreter. Check out the Rhino documentation for scripting Java for more information about how to automate Java classes.

Before you begin, make sure you've already started the Selenium Server separately in another process. The Selenium Server should remain up and running throughout this process; you shouldn't need to start/stop it each time you use the Client Driver. (Though, of course, if you need to start and stop the server, you certainly can, just by automatically starting it from the command line.)

To use js.jar with the Selenium Java Client, you'll need to have both js.jar and the Selenium client jar in your classpath, like this:

java -cp selenium-java-client-driver.jar;js.jar org.mozilla.javascript.tools.shell.Main
That will start the shell with the Java client on your classpath.

With that, you're ready to create a new DefaultSelenium object, and use it like this:

importClass(Packages.com.thoughtworks.selenium.DefaultSelenium);
var selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com");
selenium.start();
selenium.open("http://www.google.com/webhp");
selenium.type("q", "hello world");
selenium.click("btnG");
selenium.stop();

You'll need to specify the hostname and port of the Selenium Server, the browser string to use with "getNewBrowserSession", and the base URL at which we'll start testing. When you're ready to begin, run the .start() method on your DefaultSelenium object; when it's time to close the browser, use the .stop() method.

The DefaultSelenium object is full of handy methods that handle your Selenium Commands. If one of them has an error (or if an "assert" command fails) the method will throw an exception with a handy error message, which you can wrap up in a try/catch block if you like.

Running the tests like this probably doesn't provide very much advantage over just writing the tests in Java, but if you like it, then so do we! Note that there's not really a good automated testing framework that runs under Rhino, so if you want to run your tests automatically under continuous integration, we recommend you write your tests in Java, together with a testing framework like JUnit or TestNG. With that said, a testing framework is not required; you can use the Java Client Driver with any program whatsoever to automate tasks in your browser.