JavaScriptValidator { public JavaScriptValidationError validate(String script) { Context mozillaJavaScriptContext = Context.enter(); try { mozillaJavaScriptContext.compileString(script, "scriptToValidate", 1, null); return null; } catch (EvaluatorException e) { return new JavaScriptValidationError(e.getMessage(), e.lineNumber()); } }  JavaScriptValidationError validate(String script);  }
@Test public void detectsBrokenJavaScript() throws Exception { assertThat(javaScriptValidator.validate("this is not valid JavaScript"), is(not(nullValue()))); }
@Test public void providesCorrectLineNumberForError() throws Exception { String threeLineScript = "alert(1)\nalert(2)\nthis is not valid JavaScript"; JavaScriptValidationError validationError = javaScriptValidator.validate(threeLineScript); assertThat(validationError.getLineNumber(), is(3)); }
@Test public void doesNotComplainAboutSyntacticallyCorrectScripts() throws Exception { for (String validJavascript : VALID_JAVASCRIPTS) { assertThat(javaScriptValidator.validate(validJavascript), is(nullValue())); } }