Unit Testing JavaScript With QUnit And Phing

Recently I’ve been using both Phing for my PHP builds, and QUnit for my JavaScript unit tests, so I’ve been looking for a way to run these QUnit tests when Phing builds my application.

By default Phing can run PHPUnit tests, but not QUnit. However Martin Jonsson has come to the rescue with his Qunit Phing Task.

QUnit Phing Tasks lets QUnit tests be run during a build and Phing can either pass or fail based on these results. As QUnit is written in JavaScript, QUnit Phing Task runs PhantomJS to call a JavaScript wrapper that passes the output back to PHP and Phing. PhantomJS is a headless JavaScript browser that can excute on a command line.

Using QUnit Phing Task

To run the QUnit Phing Task you need to install PhantomJS. I downloaded a binary and placed it in /usr/local/bin on my system.

You need to download the QUnit Phing Task. I placed the files in a local ./lib directory in my project.

You will also need to download QUnit. I placed the files in a local ./tests directory in my project.

In the ./tests directory I created an HTML file called runner.html. This is the page we need to call to run our tests.

I also create a JavaScript file called ./test.js in ./tests to hold my JavaScript tests in.

Finally, I create a build.xml for my Phing build.

In this I am specifying a path to my ./lib directory as this is where the QUnit Phing Task code is. The path is then used in the taskdeftask which is used to create the <qunit> task. Now when I call <qunit> in my qunit target I just pass in the location of the executable – in this case where PhantomJS is, whether Phing should halt if the QUnit tests fail, and where to find the the JavaScript that runs QUnit. Inside the task, we pass in where our runner pages are, as we only have the one in this example we include it by name tests/runner.html.

Running this gives us the following…

So we can see our tests have passed. Let’s change our test.js so that it fails.

This test should fail, as false is not true and will fail the ok assertion.

So we can see that Phing has failed our build due to the QUnit tests failing, which is what we want.

Summary

Although a very simple and contrived example, I hope this has shown you how to add JavaScript unit tests using QUnit to your Phing build.

Leave a Reply