Rhino env.js testing example


/ Published in: Groovy
Save to your folder(s)



Copy this code and paste it in your HTML
  1. package com.cadrlife.mywebapp;
  2.  
  3. import groovy.util.GroovyScriptEngine;
  4.  
  5. import org.apache.commons.lang.RandomStringUtils;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8.  
  9. import com.google.common.collect.Lists;
  10. import com.google.common.io.Files;
  11. import com.google.common.io.Resources;
  12. import org.mozilla.javascript.Context;
  13. import org.mozilla.javascript.ContextFactory;
  14. import org.mozilla.javascript.ScriptableObject;
  15.  
  16. import static org.junit.Assert.*
  17.  
  18. public class MyWebAppTest {
  19.  
  20. private ScriptableObject scope;
  21.  
  22. @Before
  23. cx = ContextFactory.getGlobal().enterContext();
  24. cx.setOptimizationLevel(-1);
  25. cx.setLanguageVersion(Context.VERSION_1_5);
  26. scope = cx.initStandardObjects();
  27. // Assumes we have env.rhino.js as a resource on the classpath.
  28. String envjs = getClass().getResourceAsStream("env.rhino.js").text;
  29. String printFunction = "function print(message) {java.lang.System.out.println(message);}";
  30. cx.evaluateString(scope, printFunction, "print", 1, null);
  31. cx.evaluateString(scope, envjs, "env.rhino.js", 1, null);
  32. // This will load the home page DOM.
  33. run("window.location='http://localhost:5000'");
  34. // Whatever script JS includes the home page has.
  35. def libs = ["/js/jquery-1.4.2.min.js",
  36. "/js/jquery-ui-1.8.2.custom.min.js",
  37. "/js/app.js"];
  38. for (String lib : libs) {
  39. run(new URL("http://localhost:5000" + lib).text);
  40. }
  41. // Whatever happens on document ready.
  42. run('appInit()');
  43.  
  44. }
  45.  
  46. @Test
  47. public void navigation() throws Exception {
  48. def h1Text = '$("h1:first").text()';
  49. run('$(".nav .homeLink").click()');
  50. assertJsEquals('Request Sets', h1Text);
  51. run('$(".nav .dashboardLink").click()');
  52. assertJsEquals('Dashboard', h1Text);
  53. run('$(".nav .homeLink").click()');
  54. assertJsEquals('Sacrifice Pig', h1Text);
  55. }
  56.  
  57.  
  58. private void assertJsEquals(String a, String b) {
  59. assertEquals(a,run(b));
  60. }
  61.  
  62. private void assertJsContains(String a, String b) {
  63. String result = run(b);
  64. assertTrue("${a} does not contain ${a}", result.contains(a));
  65. }
  66.  
  67. Object result = cx.evaluateString(scope, js, "run", 1, null);
  68. return Context.toString(result);
  69. }
  70. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.