Getting Started With jQuery QUnit for Client-Side Javascript Testing


Setup

First of all, I’m assuming you’re already using jQuery. If not, you should be :) QUnit may help you for non-jQuery testing, but it’ll work better with jQuery.

Second, you should start by downloading and setting up QUnit (from this link).  QUnit consists of a single JS file (testrunner.js) and a CSS file (testsuite.css).

Third, I recommend grabbing a patched testrunner.js from here (Ticket 3215).  We, at Dovetail, submitted this patch to the jQuery team. Some of the changes were accepted, some weren’t (and then the ticket was surreptitiously closed! How rude!).  One particular feature that was NOT accepted was the beforeEach/afterEach additions to achieve xUnit-style SetUp and TearDown (before each test/after each test) behavior.  I don’t know about you, but I consider SetUp/TearDown a critical feature for any would-be xUnit framework, regardless of language/platform.

Your First QUnit Test

To start testing, you’ll need to start by creating an HTML page (MyFooTests.htm, for example).  This page will need to reference the jquery core JS file, testrunner.js, testsuite.css, as well as the JS file containing the code you’re going to be testing. Lastly, the page will need some special HTML at the bottom with well-known ID’s so that QUnit can display its output.  When you’re done, you should have a rough skeleton like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Foo Tests</title>    
    <script language="javascript" src="../jquery-latest.js" type="text/javascript"></script>
    <script language="javascript" src="testrunner.js" type="text/javascript"></script>
    <!-- add a script reference to your library here -->
    <link media="screen" href="testsuite.css" type="text/css" rel="stylesheet"/>    
</head>
<body>

<script language="javascript" type="text/javascript">

qUnitTesting(function(config){

    config.beforeEach = function(){
    }
    
    config.afterEach = function(){
    }
    
    //TODO: Modules and tests go here
});

</script>

        <h1>My Foo Tests</h1>
        <h2 id="banner"></h2>
        <ol id="tests"></ol>
        <div id="results"></div>
        <div id="main"></div>        
        
        <!-- Any HTML you may require for your tests to work properly -->
        
</body>
</html>

If you save that HTML and open it in a browser, you should see something to the effect of:

image

Modules and Tests

QUnit has the concept of “modules” and “tests.”  Tests are, like you would expect, the individual test cases. Modules are merely grouping mechanisms to organize the display of tests on the results screen.

Let’s create our first module and first test case.  To keep things simple and illustrative for this blog post, I’m merely going to test that the show() and hide() methods in jQuery work properly.  Normally you would want to avoid testing framework stuff (assume it’s already well-tested unless proven otherwise).

First, near the bottom of the HTML, before the closing </body> tag, add a div with an id “testDiv”:

<div id="testDiv"></div>

Then, up higher, where the “TODO” is in our JavaScript, add a new test, like so:

module("Show and Hide");

test("should hide the element when hide is called", function(){

    $("#testDiv").hide();

    // actual, expected
    equals($("#testDiv").css("display"), "none", "The element should be hidden");
});

test("should show the element when show is called", function(){

    // Arrange
    $("#testDiv").css("display", "none");
    
    // Act
    $("#testDiv").show();

    // Assert
    // actual, expected
    equals($("#testDiv").css("display"), "block", "The element should be visible");
}); 

Which should yield two successes:

image

Where to go from here?

For me, QUnit opened up the possibility for serious TDD with client-side JavaScript. Previously, quality with my JavaScript code was always an issue and it never seemed that manual testing was enough.  With QUnit, I can breathe a little easier now.

If I can catch some time in the next few weeks, I’ll do a post or two on how mocking works in JavaScript (or rather, why it’s so dirt simple it’s almost not worth talking about), and then even show how to integrate your QUnit tests into your CI build (which isn’t as hard as you might think).


Posted Aug 28 2008, 10:26 PM by chadmyers
Filed under: ,

Comments

Reflective Perspective - Chris Alcock » The Morning Brew #168 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #168
on 08-29-2008 2:19 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #168

Dew Drop - August 29, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - August 29, 2008 | Alvin Ashcraft's Morning Dew
on 08-29-2008 8:03 AM

Pingback from  Dew Drop - August 29, 2008 | Alvin Ashcraft's Morning Dew

Tom Opgenorth wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 08-29-2008 8:16 AM

Very timely for me.  Thanks Chad.

jQuery releases Javascript pain « maonet technotes wrote jQuery releases Javascript pain &laquo; maonet technotes
on 08-29-2008 10:31 AM

Pingback from  jQuery releases Javascript pain &laquo; maonet technotes

QUnit for jQuery | Fragmented Code wrote QUnit for jQuery | Fragmented Code
on 08-29-2008 10:43 AM

Pingback from  QUnit for jQuery | Fragmented Code

DotNetKicks.com wrote Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 08-29-2008 10:52 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Paul Cowan wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 08-29-2008 11:06 AM

I've been thinking about writing a nant task to parse the results using regular expressions.

I'll be very interested to see your approach to hooking it into CruiseControl

Southwestern Virginia Developers Forum » Javascript Unit Testing… Whoda thunk? wrote Southwestern Virginia Developers Forum &raquo; Javascript Unit Testing&#8230; Whoda thunk?
on 08-30-2008 12:21 AM

Pingback from  Southwestern Virginia Developers Forum &raquo; Javascript Unit Testing&#8230; Whoda thunk?

Joshua Flanagan wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 08-30-2008 8:55 PM

Paul - we currently drive the QUnit tests in our CI build using WATIN:

private IE _ie;

[TestFixtureSetUp]

public void TestFixtureSetUp()

{

_ie = TestBrowser.GetInternetExplorer();

}

[TestFixtureTearDown]

public void TestFixtureTearDown()

{

_ie.Dispose();

}

[Test]

public void TagEditorTester_tests_should_pass()

{

RunQUnitTests("tageditortester.htm");

}

private void RunQUnitTests(string testPage)

{

_ie.GoTo(string.Format("localhost/.../tests{0}", testPage));

_ie.WaitForComplete(5);

_ie.Element("TESTRESULTS").Text.ShouldEqual("0");

}

Joe Ocampo wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 08-31-2008 1:16 PM

@Josh

nice!

chadmyers wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 08-31-2008 2:27 PM

@Joe:

Right now all it tells us is whether all the tests passed or not, which is good enough for basic CI integration.  At some point, in our copious amounts of free time, I'd like to be able to have all the tests matched somehow in C# so that a.) they add to our total test count b.) we can get better visibility when something goes wrong and c.) we can get (maybe) some test timings out of TeamCity.

Oh yeah, the whole TESTRESULTS thing is a customization we made for QUnit's testrunner.js.  I believe this change was accepted into the JQuery trunk, so it should be there. if not, it should be trivial to add yourself.

I've been thinking about forking the QUnit trunk to make it more xUnit-style (it isn't right now, and the jQuery folks don't seem to be too interested in making it so).  Plus, I was thinking some basic expectation-based mocking might be useful, too.  Right now we're doing test double-style mocking which gets annoying after just a few of them.

nap wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 08-31-2008 10:21 PM

Great writeup chad, many thanks!

Peter Eysermans wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 09-03-2008 4:33 AM

Nice introduction of QUnit, I've been using it in some of my projects.

I'm really looking forward to the article(s) about mocking with JavaScript, especially mocking QUnit resultsets (like $('div.my-class'). I'm currently struggling with that one and it's been holding me back when trying to test client side code.

Ajaxian » QUnit: A simple look at the jQuery unit test framework wrote Ajaxian &raquo; QUnit: A simple look at the jQuery unit test framework
on 09-03-2008 5:12 AM

Pingback from  Ajaxian &raquo; QUnit: A simple look at the jQuery unit test framework

Mika Tuupola wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 09-03-2008 6:56 AM

Good timing on article. I just wrote my first unit tests two days ago using QUnit.

www.appelsiini.net/.../tests

Ajax Girl » Blog Archive » QUnit: A simple look at the jQuery unit test framework wrote Ajax Girl &raquo; Blog Archive &raquo; QUnit: A simple look at the jQuery unit test framework
on 09-03-2008 8:15 AM

Pingback from  Ajax Girl  &raquo; Blog Archive   &raquo; QUnit: A simple look at the jQuery unit test framework

QUnit: A simple look at the jQuery unit test framework | "IT" - I LIKE "IT" ! wrote QUnit: A simple look at the jQuery unit test framework | "IT" - I LIKE "IT" !
on 09-03-2008 10:00 AM

Pingback from  QUnit: A simple look at the jQuery unit test framework | "IT" - I LIKE "IT" !

Mrasnika’s Lair » QUnit: jQuery unit test framework wrote Mrasnika&#8217;s Lair &raquo; QUnit: jQuery unit test framework
on 09-03-2008 1:32 PM

Pingback from  Mrasnika&#8217;s Lair &raquo; QUnit: jQuery unit test framework

Javascript News » Blog Archive » QUnit: A simple look at the jQuery unit test framework wrote Javascript News &raquo; Blog Archive &raquo; QUnit: A simple look at the jQuery unit test framework
on 09-03-2008 7:51 PM

Pingback from  Javascript News  &raquo; Blog Archive   &raquo; QUnit: A simple look at the jQuery unit test framework

?? ???????????????????????? (IDN) ?????????????? wrote ?? ???????????????????????? (IDN) ??????????????
on 09-04-2008 12:35 AM

Pingback from  ?? ???????????????????????? (IDN) ??????????????

james wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 09-05-2008 4:17 PM

i need this to listen to music

Ken Ko wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 09-07-2008 10:46 AM

Hi, I've written a mock framework for jquery's jqUnit framework, but haven't been able to get the word out. Have a look if you are interested!

code.google.com/.../jqmock

ph wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 09-10-2008 3:35 AM

When I copied the first program the outcome is only

"My Foo test" and nothing... Something wrong?

Getting Started With jQuery QUnit for Client... [ JavaScript Dot Com ] wrote Getting Started With jQuery QUnit for Client... [ JavaScript Dot Com ]
on 09-11-2008 3:48 PM

Pingback from  Getting Started With jQuery QUnit for Client...  [ JavaScript Dot Com ]

Joshua Flanagan wrote Running jQuery QUnit tests under Continuous Integration
on 09-18-2008 6:24 PM

Setup This post assumes you are already writing unit tests for your JavaScript code. If not, check out

Enlight Solutions ?? Dan Pickett’s Blog » Client Side TDD with JQuery and QUnit wrote Enlight Solutions ?? Dan Pickett&#8217;s Blog &raquo; Client Side TDD with JQuery and QUnit
on 09-29-2008 10:21 AM

Pingback from  Enlight Solutions ?? Dan Pickett&#8217;s Blog &raquo; Client Side TDD with JQuery and QUnit

Craig Buchek wrote re: Getting Started With jQuery QUnit for Client-Side Javascript Testing
on 09-30-2008 10:00 PM

It appears that your SetUp and TearDown features are already included in QUnit, as optional arguments to module(). Admittedly, it's a bit odd place to put them, especially since the options are collectively called "lifecycle".

QUnit: jQuery unit test framework : ?????????????????????? wrote QUnit: jQuery unit test framework : ??????????????????????
on 11-07-2008 7:08 PM

Pingback from  QUnit: jQuery unit test framework : ??????????????????????

Chad Myers' Blog wrote 1 Year Anniversary
on 11-21-2008 11:05 AM

I’m generally not one for sentimentality, so it should come as no surprise to anyone that knows me that

Links for 2009-02-17 at hocuspokus wrote Links for&nbsp;2009-02-17 at hocuspokus
on 02-17-2009 5:05 PM

Pingback from  Links for 2009-02-17 at hocuspokus

CONDG Meeting - February 2009 – Blue Cog Blog wrote CONDG Meeting - February 2009 &#8211; Blue Cog Blog
on 02-26-2009 10:56 PM

Pingback from  CONDG Meeting - February 2009 – Blue Cog Blog

Copyright Los Techies 2008, 2009. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems