Archive

Posts Tagged ‘qunit’

jQuery and testing — JSUnit, QUnit, JsSpec [Part 2]

November 15th, 2008 No comments

Trying QUnit with jQuery

In the JSUnit entry, one of the main problems was with the sequencing of calls. Let’s see how QUnit handles this. QUnit has a simple implementation to this problem: stop() and start() commands to synchronise sequences. The basic approach is that it calls a test function. With the stop() command, it will not call the next test until you say start(). But it does complete the rest of the current test.

The code that I ended up with was just what I wanted compared to JsUnit. Previously, I had said that basically I wanted to call my function and then process the result that it was in fact what I wanted. Here is the main javascript code (it’s nice and concise).

One point about the code at this stage. The tests had to be inside the success function to be run. I wonder if this is going to create a code smell in the long run. Plus there is no setup/teardown cycles, again I wonder what that will mean in the long run. Perhaps not?

module("XML to object");

test("Check the xml to object conversion without showing the tree", function() {
  
  expect( 5 )
  stop();
  
   $().storyq({
        url: 'data/results-01.xml', 
        load: '',
        success: function(feed) {
          ok( feed, "is an object" )
          ok( !$.isFunction(feed), "is not a function" )
          ok( feed.version, "has a version: " + feed.version )
          ok( feed.items, "has items")
          same( feed, reference, "is the same as the reference object in data/results-01.js")
          start();
        }
    });

});

Honestly, it is that easy.

Here’s a couple of features that took me half an hour to work out restated from above. (1) stop() and start() almost work as you expect – but I had to put some alerts in to check the order of execution. Basically, a stop() halts any new tests from executing but it keeps the current test executing. The effect of this is that the asynchronise call can be completed. start() then tells the tests to start running again. If you don’t have a start() then you will find that your test runner halts altogether. There is another option and that is to put a timer on the stop and then you don’t need a start. I prefer to keep the tests running as quickly as possible.

Just another note. I decided to do a same() comparison. I have saved and preloaded an object from a file for ease. This kept the test easy to read – my reference object here is quite long. You can see the insertion of this file in the entire code below <script type="text/javascript" src="data/results-01.js"/>

&lt;html>
&lt;head>
  &lt;title>Unit tests for StoryQ Results viewer&lt;/title>
  &lt;link rel="stylesheet" href="../../lib/qunit/testsuite.css" type="text/css" media="screen" />

  &lt;link rel="stylesheet" href="../../lib/treeview/jquery.treeview.css" />
  &lt;link rel="stylesheet" href="../../src/css/storyq.treeview.css" />
  &lt;link rel="stylesheet" href="../../src/css/storyq.screen.css" />

  &lt;script src="../../lib/jquery/jquery.js">&lt;/script>
  &lt;script src="../../lib/jquery/jquery.cookie.js" type="text/javascript">&lt;/script>
  &lt;script src="../../lib/treeview/jquery.treeview.js" type="text/javascript">&lt;/script>
  &lt;script src="../../src/storyq.js" type="text/javascript">&lt;/script>
  &lt;script src="../../src/storyq.treeview.js" type="text/javascript">&lt;/script>
  &lt;script src="../../src/storyq.xml.js" type="text/javascript">&lt;/script>
  &lt;script src="../../src/storyqitem.js" type="text/javascript">&lt;/script>
  &lt;script src="../../src/storyqresults.js" type="text/javascript">&lt;/script> 

  &lt;script type="text/javascript" src="../../lib/qunit/testrunner.js">&lt;/script> 
  &lt;script type="text/javascript" src="data/results-01.js">&lt;/script>  
  
  &lt;script type="text/javascript">
    module("XML");

    test("Check the xml to object conversion without showing the tree", function() {

      expect( 5 )
      stop();

       $().storyq({
            url: 'data/results-01.xml', 
            load: '',
            success: function(feed) {
              ok( feed, "is an object" )
              ok( !$.isFunction(feed), "is not a function" )
              ok( feed.version, "has a version: " + feed.version )
              ok( feed.items, "has items")
              same( feed, reference, "is the same as the refefence object in data/results-01.js")
              start();
            }
        });

    });
  &lt;/script>
  
&lt;/head>
&lt;body>
  
 &lt;h1>QUnit tests&lt;/h1>
 &lt;h2 id="banner">&lt;/h2>
 &lt;h2 id="userAgent">&lt;/h2>
 &lt;ol id="tests">&lt;/ol>

 &lt;div id="main">&lt;/div>

&lt;/div>
&lt;/div>

&lt;/body>
&lt;/html>

The output results from QUnit are nice to look at and easy to read. I didn’t have a couple of errors that weren’t the easiest to debug given the output. Partly though because I was new to it, I was taking too big a step at times!

I’m happy with QUnit – and there are plenty of examples in the JQuery test suite. I can see that I would do TDD with this.

Being a BDD type of guy, I’m now off to see what JsSpec has to offer.

jQuery and testing – JSUnit, QUnit, JsSpec [Part 1]

November 15th, 2008 No comments

Trying JsUnit with JQuery

I have started first with JSUnit because it is tried and true (and to tell the truth I thought it would be fine and didn’t bother with a quick search for alternatives).

For the impatient, I won’t be going with JSUnit and here are some reasons:

  • the problem is that the integration of a setup (ie onload – pausing) to load the data doesn’t integrate well with jQuery. JSUnit has its own setup and document loader but I am still wondering how to do this transparently (ie I didn’t actually get the test to work – I wasn’t exhaustive but then again I don’t think that I should have needed to be to get this test going)
  • Firefox 3.0 on mac doesn’t integrate well (ie it doesn’t work), but safari does! Unfortunately, I am a little bound to firebug for development.
  • JSUnit doesn’t report tests well either

I went and had a look at how JSUnit does it. (Remember that this framework has been around a lot longer than jQuery.) Here is the extract from the code/test samples. The basic setup is to hook into an existing testManager that existing within a frame and then get the data from there. Furthermore, you need to manage your own flag that the process has been complete. JSUnit then looks through all functions that start with test in this case testDocumentGetElementsByTagName checks expected data. Here I assume that the tests are run in a particular frame (buffer()) that testManager gives us access to.

var uri = 'tests/data/data.html';

function setUpPage() {
    setUpPageStatus = 'running';
    top.testManager.documentLoader.callback = setUpPageComplete;
    top.testManager.documentLoader.load(uri);
}

function setUpPageComplete() {
    if (setUpPageStatus == 'running')
        setUpPageStatus = 'complete';
}

function testDocumentGetElementsByTagName() {
    assertEquals(setUpPageStatus, 'complete');
    var buffer = top.testManager.documentLoader.buffer();
    var elms = buffer.document.getElementsByTagName('P');
    assert('getElementsByTagName("P") returned is null', elms != null);
    assert('getElementsByTagName("P") is empty', elms.length > 0);
}

Below is the rewritten code to exercise my code. Here’s a couple of the features:

  • for setup, pass in the correct xml file via uri variable (obviously)
  • to test, I have written a test testXML2Object.

    p. There is one major design problem with the code itself that didn’t allow me to use my own data loader. You will see the line var feed = new StoryQResults(buffer);. Where did that come from? It is nothing close to the code I said that I wanted to exercise. It is infact from within the code I want to exercise. The major issue I found here is that to load and test data I had to use the testManager rather than use my own ().storyq() call.

The other problem was it wouldn’t return the result that I wanted either. I was expecting my feed variable to be an object of the results. Instead I was getting a reference to function StoryQResults – given now that it wasn’t running in Firefox and I didn’t have Firebug life was getting a little hard.

var uri = '../../xml/results-01.xml';

function setUpPage() {
    setUpPageStatus = 'running';
    top.testManager.documentLoader.callback = setUpPageComplete;
    top.testManager.documentLoader.load(uri);
}

function setUpPageComplete() {
    if (setUpPageStatus == 'running')
        setUpPageStatus = 'complete';
}

function testXML2Object() {
    assertEquals(setUpPageStatus, 'complete');
    var buffer = top.testManager.documentLoader.buffer();
    
    var feed = new StoryQResults(buffer);               

    assertEquals(feed.version, '0.1')
    assertEquals("Number of stories", $(feed).size(), 1)
    $.each(feed, function(){
      alert(this)               
    })

}

Even though I know that I getting a function returned instead of an object I am still going to see if I can invoke my own loading function within JSUnit. Here’s what the code would look like below. I wouldn’t recommend running it – just take a look at it. The code to me is a mixtures of styles that start to bloat the code. On the one hand, JSUnit has this setup phase with explicit flags and no anonymous functions. On the other hand, because I am using JQuery conventions, I encapsulate alot of that logic. For example, jQuery(function(){}) waits for the page to be loaded before executing ("#tree").story(), Then I have the callback function inline. It looks good from the outside, but it doesn’t work.

The order of calls is: loading, in test and then loaded. Indicating that my JQuery function runs after the test has been run. The order should have been loading, loaded and then in test. In this sense, while setUpPage runs within its own setup/test/teardown cycle. But my JQuery call isn’t linked into this. JQuery waits is waiting on a document flag rather than a custom flag (within testManager). At this point, I do not wish to dig into these libraries to work them out to get it to all play nicely. It wasn’t designed to work this way. Let’s find one that was.

var data = '';

function setUpPage() {
    setUpPageStatus = 'running';
    alert('loading')
    jQuery(function() {
      $("#tree").storyq({
          url: '../../xml/results-01.xml', 
          success: null, 
          load: function(feed) {
            data = feed;
            alert('loaded')
            setUpPageComplete()
            }
          });
    });
}

function setUpPageComplete() {
    if (setUpPageStatus == 'running')
        setUpPageStatus = 'complete';
}

function testXML2Object() {
    alert('in test')
    assertEquals(setUpPageStatus, 'complete');

    assertEquals(data.version, '0.1')
    assertEquals("Number of stories", $(feed).size(), 1)
}

I’m invoking the two-feet principle: I’m moving onto the next framework (after a quick search): QUnit

jQuery and testing – JSUnit, QUnit, JsSpec [Part 3]

November 14th, 2008 No comments

Trying JsSpec with jQuery

This is part three of three. The previous two have been focussed around managing the problem of timing: JSUnit got too hard and QUnit is easy but you still have to manage timings yourself. With JsSpec there is no problem because it is all managed for you. Nice work! Here’s the code I had to write.

A couple of things to writing it. I had to dig into the code to find out the setup/teardown lifecycle keywords. There turns out to be setup/teardown per test (eg before) and per test suite (eg before all). I also had to dig around to find then comparators (eg should_be, should_not_be_null). I couldn’t find any documentation.

describe('I need to read the xml and convert into object', {
  'before all': function() {
    target = {};
    $().storyq({
        url: 'data/results-01.xml', 
        load: '',
        success: function(feed) {
          target = feed
      }
    })
   
  },
  
  'should return an object': function() {
    value_of(target).should_not_be_null()
  },
  
  'should not be a function': function() {
    value_of(typeof target).should_not_be(typeof Function )
  },
  
  'should have a version': function(){
    value_of(target.version).should_be('0.1')
  },
  
  'should have items': function(){
    value_of(target.items).should_not_be_empty()
  },
  
  'should have the same value as the reference object in data/results-01.js': function(){
    value_of(reference).should_not_be_undefined()
    value_of(target).should_be(reference)
  },
  
})

Ihe output looks nice too ;-) Here’s the overall code. Notice that I have also used the technique of a reference object in results-01.js:

&lt;html>
&lt;head>
&lt;title>JSSpec results&lt;/title>
&lt;link rel="stylesheet" type="text/css" href="../lib/jsspec/JSSpec.css" />
&lt;script type="text/javascript" src="../lib/jsspec/JSSpec.js"/>

&lt;script src="../lib/jquery/jquery.js"/>
&lt;script src="../lib/jquery/jquery.cookie.js" type="text/javascript"/>
&lt;script src="../lib/treeview/jquery.treeview.js" type="text/javascript"/>
&lt;script src="../build/dist/jquery.storyq.js" type="text/javascript"/>

&lt;script type="text/javascript" src="data/results-01.js"/>
&lt;script type="text/javascript" src="specs/treeview.js"/>  

&lt;script type="text/javascript">

  describe('I need to read the xml and convert into object', {
    'before all': function() {
      target = {};
      $().storyq({
          url: 'data/results-01.xml', 
          load: '',
          success: function(feed) {
            target = feed
        }
      })

    },

    'should return an object': function() {
      value_of(target).should_not_be_null()
    },

    'should not be a function': function() {
      value_of(typeof target).should_not_be(typeof Function )
    },

    'should have a version': function(){
      value_of(target.version).should_be('0.1')
    },

    'should have items': function(){
      value_of(target.items).should_not_be_empty()
    },

    'should have the same value as the reference object in data/results-01.js': function(){
      value_of(reference).should_not_be_undefined()
      value_of(target).should_be(reference)
    },

  })
&lt;/script>

&lt;/head>
    &lt;body>
      &lt;div style="display:none;">&lt;p>A&lt;/p>&lt;p>B&lt;/p>&lt;/div>
    &lt;/body>
&lt;/html>

JSSpec isn’t written using JQuery. So there are a couple of issues that I can’t pin down. When I get errors it stops the tests completely. I suspect that this is because these tests are using callbacks and they don’t return an (JQuery) object. JQuery does alot of object chaining and JsSpec isn’t cut out for it (I think).

Well, that’s it.

jQuery and testing – JSUnit, QUnit, JsSpec [Introduction]

November 12th, 2008 No comments

I had been writing a jQuery parser and then realised once I had spiked it that I hadn’t actually written any tests. So, these are some results from a spike in unit testing a jQuery plugin.

Some background, the plugin is a results viewer from an xml feed from storyq. So, I have run some tests and have results. Now I want to see them in html format. The plugin merely transforms the xml to be displayed using the treeview plugin. I wanted to avoid handing in a json feed formatted specifically for the treeview. I wanted all this to happen client side.

The tests have two aspects:

  • xml loading and parsing into an object
  • rendering the object into a tree (at that point treeview takes over)

    In short, I want to test the code underlying this call that returns the feed before populating an <ul id="tree"> element:
$('#tree').storyq({
    url: 'tests/data/results-01.xml',   
    success: function(feed) {

      $("#tree").treeview(); //populate the tree
  
  }    
});

Problem for any framework: sequencing

Let’s take a look at what I want as test code. In this code, I want to populate data with the feed variable returned in the success callback. The test can then check for values. Take a look at the code below. When I run the code, I should (ideally) see the sequence of alerts: loaded, start test, end test. Of course, I don’t. I see start start test, end test, loaded as the sequence. That should be obvious that the callback success hasn’t been called as yet: javascript is run sequentially. Okay, nothing here is surprising. I laboured this point because any of the frameworks must deal with this problem.

var data = {};

jQuery(function() {
  $().storyq({
      url: '../../xml/results-01.xml', 
      success: function(feed) {
        data = feed;
        alert('loaded')       
        }
      });
});

function testXML2Object() {
  alert('start test')
  assertEquals(data, {"result"}, "Assume that result is a real/correct object");
  alert('end test')     
}

Frameworks looked at

I looked at three frameworks for xml loading and parsing:

Conclusions

  • In short, QUnit and JsSpec are both as easy as the other. JSUnit seems now to be too heavy given what we now have.
  • QUnit is a TDD framework is used by jQuery itself. I suspect it might survive longer. There are no setup/teardown phases.
  • JsSpec is a BDD framework and doesn’t use jQuery at all but can easily be used with JQuery plugins. There are good setup/teardown phases for tests and suites.
  • Your choice between the two is likely to be your preference between TDD or BDD. It probably depends upon which boundaries you want to test and how you want to go about specifying.

What I didn’t do:

  • integration with a CI system
  • cross-browser testing
  • test with selenium or watir