Testing Rhino JavaScript with Eclipse, Gradle, Groovy and Spock

27 Mar 2014, 4 minute read

A colleague was wrangling with JavaScript testing, but with an unusual constraint: the code runs on the Rhino JS engine. After a bit of head-banging, I learned that continuously testing JavaScript written for Rhino needn’t be arduous.

Other potential solutions

There are a number of ways of tackling this problem. Initially we attempted to use one of the many existing JavaScript testing libraries, running on Rhino. Jasmine running on Karma was my first choice, but we soon hit issues with require not being present. Since giving up on that avenue I’ve discovered CommonJS for Rhino. That solution may be preferable because it allows you to write your tests in JavaScript, but I love Spock’s data driven capabilities and the cleanness of spec tests, so I’m not disappointed with our result.

Configuring Gradle

We need Gradle to download our dependencies and run the tests, so the first thing to do is initialise a Gradle project:

gradle init

And then edit the build.gradle file to look something like the following:

This will ensure we’ve got Rhino on our classpath, and can use Spock to write our tests. The last compile dependency allows us to include JAR files in a lib directory, which can be handy if you use libraries not available through Bintray or Maven.

We’ll use the standard Maven source locations, which we need to create manually:

mkdir -p src/{main,test}/{groovy,js}

We’ve now got a Gradle project which we can test with gradle check, although there’s not much to see at the moment.

Running tests

Running the tests is as easy as gradle check, or pushing the run button in Eclipse. Doing the former, your test results will be output into an easy-to-read HTML file as well as JUnit XML.

Conclusion

Using a few simple steps we’ve set up a Gradle project to run Spock tests over Rhino JavaScript, with the added bonus of being able to use Eclipse.

Because we can now run tests with a single command and interpret the result with most tools (either through the Gradle exit code or the JUnit output), adding this to a continuous build system like Travis or Jenkins is simple!

Discuss!

Was this post useful? Why not help others find it by sharing on twitter. While you're there, get in touch and let me know what you think!