Skip to content

Instantly share code, notes, and snippets.

@spikeheap
Created March 27, 2014 14:16
Show Gist options
  • Select an option

  • Save spikeheap/9808514 to your computer and use it in GitHub Desktop.

Select an option

Save spikeheap/9808514 to your computer and use it in GitHub Desktop.
Using Spock and Gradle to test JavaScript running on Rhino. See http://ryanbrooks.co.uk/posts/2014-03-27-testing-rhino-js-spock/ for the context.
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'eclipse'
repositories {
jcenter()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.1.5'
testCompile "org.spockframework:spock-core:0.7-groovy-2.0"
compile 'org.mozilla:rhino:1.7R4'
compile fileTree(dir: 'lib', include: '*.jar')
}
function addTogether(a, b, c){
return a + b + c;
}
package my.package
class LittleFunctionSpec extends Specification{
Context context
Scriptable scope
/**
* Setup, prior to every spec test
*/
void setup(){
context = Context.enter()
// Set version to JavaScript1.2 so that we get object-literal style
// printing instead of "[object Object]"
context.setLanguageVersion(Context.VERSION_1_8)
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed.
scope = context.initStandardObjects()
}
/**
* Teardown method, run after each test. This just ensures we've left the Rhino context.
*/
void cleanup(){
Context.exit();
}
/**
* Load a JavaScript file into the Rhino engine. For resources held within the project you will probably want a filename like:
* "src/main/js/componentX/script.js"
* @param fileName The name of the file to be loaded.
*/
void loadJSIntoContext(String fileName) {
File emulatorFile = fileName as File
context.evaluateString(scope, emulatorFile.text, emulatorFile.name, 1, null)
}
}
// Add into LittleFunctionSpec.groovy
def "check little function adds numbers together"(){
given: "I have littleFunction.js loaded"
loadJSIntoContext("src/main/js/littleFunction.js")
when: "I run the addTogether function for 1, 2, and 3"
String jsExercise = "var result = addTogether(1,2,3);"
context.evaluateString(scope, jsExercise, "TestScript", 1, null)
then: "The result is 6"
scope.get("result", scope) == 6
}
// Add into LittleFunctionSpec.groovy
@Unroll
def "check addTogether behaves for #a, #b, #c"(){
given: "I have littleFunction.js loaded"
loadJSIntoContext("src/main/js/littleFunction.js")
when: "I run the addTogether function for 1, 2, and 3"
String jsExercise = "var result = addTogether("+a+","+b+","+c+");"
context.evaluateString(scope, jsExercise, "TestScript", 1, null)
then: "The result is #c"
scope.get("result", scope) == (a + b + c)
where:
a | b | c
0 | 0 | 0
9 | 1 | 0
5 | 0 | 5
1 | 1 | 1
0 | 4 | 24
1231| 0 | 0
9999| 0 | 4325
0 | 035 | 230
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment