Testing JavaScripts via JUnit

It appears that JDK 1.6 introduces a new javax.script API which allows to run script languages on the server side. Currently only JavaScript is supported. So I’ve decided to try this out for testing of some of my simple JS scripts via JUnit.

Below is the snippet I’ve used to test data

import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import org.junit.Assert;
import org.junit.Test;

public class JSTest {
    @Test
    public void testIt() {
        ScriptEngineManager manager = new ScriptEngineManager();

        // Getting script engine.
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {

            // Declaring function.
            engine.eval("function sum(a, b) { if(false) { return a+b; }");
            Invocable invEngine = (Invocable) engine;


            // Invoking function

            Object result = invEngine.invokeFunction("sum", 1, 2);

            
            // Asserting result.
            Assert.assertEquals(3.0, result);
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        }
    }
}

Of course you can include JavaScript files to test them. You should do something like this:

engine.eval(this.getClass().getResourceAsStream("test.js");

Unfortunately this approach has limitations since it was designed to run on the server. For example something like alert or document.getElementById can’t be invoked. However you can do a sort of refactoring and move these items out from the testable script file to another script file which will be replaced in case of testing by stub stuff.

Please refer to http://download-llnw.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html for more instructions and details.