Using PhantomJS to TDD QUnit

These are instructions for Ubuntu. It’s going to be pretty much the same for other operating systems, just need to get the phantomjs executable, instructions will be on their website.

We use quinit for this, here is a handy guide: http://qunitjs.com/intro/

  1. Install phantomjs
    sudo apt-get install phantomjs

    NOTE: you may have to fix an issue with the environment variables, where there are spaces, but no quotes around the value. Update the developer environment.

  2. Make sure you have a copy of the qunit.js and qunit.css
  3. Move these into a new ui unit test folder
  4. Get a copy of the phantomjs qunit runner and also put that in the folder
  5. Make sure you update the rake file so that jshint isn’t checking this folder for now, as it really doesn’t like qunit.js
  6. Create a new folder inside the ui test folder for your test (it’s going to have a html and a js file in there)
    - ui
    --- qunit.css
    --- qunit.js
    --- runner.js
    --- testQuotationRequest
    ------ test.html
    ------ tests.js
    
  7. create your test.html:
    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>QUnit Example</title>
    		<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css">
    	</head>
    	<body>
    		<div id="qunit"></div>
    		<div id="qunit-fixture"></div>
    		<script src="http://code.jquery.com/qunit/qunit-1.12.0.js"></script>
    		<script src="tests.js"></script>
    	</body>
    </html>
    
  8. create your tests.js
    test( "hello test", function()
    {ok( 1 == "1", "Passed!" );
    });
    
  9. ~/workspace/topcat/tests/ui$ phantomjs runner.js ./testQuotationRequest/test.html
  10. Add task to the rakefile:
    task :ui_tests do
    phantom_js('./tests/ui')
    end
    def phantom_js(test_location)&lt;br&lt;rake_sh "&lt;span="" class="hiddenSpellError" pre=""&gt;phantomjs #{test_location}/runner.js #{test_location}/testQuotationRequest/test.html"
    end

You will find all the code I created to make this tutorial here. Mr @iainjmitchell made another awesome repo to get you started, especially if you’re working on Windows.

It would definitely be worth your while checking out Grunt. It seems to be the Javascript version of Make, with a lot of JS goodness for free, such as running jshint and minification. This Grunt phantomjs plugin should get you on your way quite nicely. As I already had a rake file, I decided to stick with that, although in future I will be looking to get my rake file to run grunt, which will supercede the tasks for running jshint and the tasks created in this article.