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 com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.common.io.Resources;
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;
	
	@Before
	public void setup() throws Exception {
		cx = ContextFactory.getGlobal().enterContext();
		cx.setOptimizationLevel(-1);
		cx.setLanguageVersion(Context.VERSION_1_5);
		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.
		run("window.location='http://localhost:5000'");
		// Whatever script JS includes the home page has.
		def libs = ["/js/jquery-1.4.2.min.js",
				"/js/jquery-ui-1.8.2.custom.min.js",
				"/js/app.js"];
		for (String lib : libs) {
			run(new URL("http://localhost:5000" + lib).text);
		}
		// Whatever happens on document ready.
		run('appInit()');
		
	}
	
	@Test
	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) {
		assertEquals(a,run(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
Groovy