Return to Snippet

Revision: 30044
at August 6, 2010 13:10 by cadrlife

Initial Code
package com.cadrlife.mywebapp;

import groovy.util.GroovyScriptEngine;

import org.apache.commons.lang.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.ScriptableObject;

import static org.junit.Assert.*

public class MyWebAppTest {
	private Context cx;
	private ScriptableObject scope;
	public void setup() throws Exception {
		cx = ContextFactory.getGlobal().enterContext();
		scope = cx.initStandardObjects();
		// Assumes we have env.rhino.js as a resource on the classpath.
		String envjs = getClass().getResourceAsStream("env.rhino.js").text;
		String printFunction = "function print(message) {java.lang.System.out.println(message);}";
		cx.evaluateString(scope, printFunction, "print", 1, null);
		cx.evaluateString(scope, envjs, "env.rhino.js", 1, null);
		// This will load the home page DOM.
		// Whatever script JS includes the home page has.
		def libs = ["/js/jquery-1.4.2.min.js",
		for (String lib : libs) {
			run(new URL("http://localhost:5000" + lib).text);
		// Whatever happens on document ready.
	public void navigation() throws Exception {
		def h1Text = '$("h1:first").text()';
		run('$(".nav .homeLink").click()');
		assertJsEquals('Request Sets', h1Text);
		run('$(".nav .dashboardLink").click()');
		assertJsEquals('Dashboard', h1Text);
		run('$(".nav .homeLink").click()');
		assertJsEquals('Sacrifice Pig', h1Text);
	private void assertJsEquals(String a, String b) {
	private void assertJsContains(String a, String b) {
		String result = run(b);
		assertTrue("${a} does not contain ${a}", result.contains(a));
	private String run(String js) throws Exception {
		Object result = cx.evaluateString(scope, js, "run", 1, null);
		return Context.toString(result);

Initial URL

Initial Description

Initial Title
Rhino env.js testing example

Initial Tags
javascript, DOM, groovy

Initial Language