1. Tests integrate with your existing Spock / JUnit-powered test suite, reporting, and IDE.
3. You get all of the things you love about Spock: power assertions, data-driven testing, mocks, and most importantly: readable tests.
Red, red, red, red, green, refactor
Let’s write our test first:
And let’s stub out our function:
As you would expect, we get a failed test. Let’s implement that:
And here you get the power of the Groovy power assertion. Rather than a generic “Expected James, got undefined”, you get this:
Let’s change “first” to “firstName” and “last” to “lastName”:
And we have a green, passing test!
As with any other Spock test, you can use the data table to easily repeat tests with various values:
What about interaction? Suppose we have a JS function that needs to call a callback function. We can pass a closure to stub out the behavior:
But we’re really not validating the interaction. We trust that it called the stub, but it’s not ideal. Instead, let’s try a Spock Mock:
We can also mock out functions that would normally be defined elsewhere, such as alert():
You can pass any implementation of an interface that is annotated with @FunctionalInterface: Consumer, Predicate, Supplier, etc. I chose Function here because it is the most flexible.
• Nashorn blog