Friday, March 16, 2012

JavaScript unit testing in Grails

Recently I wanted to test some complicated JavaScript code and surprisingly there is no a lot of options to choose from in Grails. Fortunately, I was already using Geb and it is extremely easy in this case.
I decided to use QUnit testing framework and all that needs to be done in this case is to place few static files in JS, CSS and HTML folders, create Geb page for QUnit reports and Geb Spec for launching browser. For development everything can be done (and much faster) with QUnit alone. Geb is basically only needed to run tests from CI (Jenkins in my case).

There is my Geb Spec:

package my.test.specs

import spock.lang.Stepwise
import my.test.pages.QUnitPage

class QUnitSpec extends GebScreenshotsSpec {

  def "run QUnit tests"() {
    to QUnitPage

    at QUnitPage
    failedCount == '0'


Geb page:

package my.test.pages

import geb.Page

class QUnitPage extends Page {
  static url = "http://localhost:"+System.getProperty("server.port", "8080")+"/my-test/js/tests/qunit.html"

  static at = { $("#qunit-header") }

  static content = {
    failedCount(wait:true) {$('#qunit-testresult .failed').text()}

qunit.html and all it's content is just plain QUnit framework.

Disadvantages are that reports are not persisted or summarized with other testing frameworks, but if you have screenshots in your Geb tests, it will provide some feedback. Another issue is if you are not using Geb, than this can be overkill to use it only for JS unit tests.
But in case you already have Geb this is super-simple and lightweight approach.

No comments:

Post a Comment