Posts Tagged ‘jquery’

Having Jasmine tests results in TeamCity via node.js (on windows) invoked from powershell

September 26th, 2011 2 comments

I test my javascript code via jasmine on a windows machine. I primarily write jquery-plugin-style code. Now I need to get this onto CI. A colleague I worked with took my test strategy in jasmine and wrote a library to run it very quickly on node.js. There are other places showing how to integrate with TeamCity and Jasmine with JsTestDriver or Qunit and also the documentation on how to easily integrate service messages with TeamCity.

One caveat: I am not wanting to test cross-browser functionality. Therefore, I don’t need or want a browser or the associated slowness and the brittleness of cross-process orchestration. (Note: I have tried to stabilise these types of tests using NUnit and MSTest runners invoking selenium and/or watin – it gets unstable quickly and there is too much wiring up.)

So this approach is simple and blindly fast thanks to Andrew McKenzie’s jasmine-node-dom which is an extension of jasmine-dom. He wrote his for linux and his example is with Jenkins so I have forked a version for windows which has a node.exe binary which is available form node.js.

Anyway, this blog covers the powershell script to invoke the jasmine-node-dom and publish it to TeamCity.

Here’s the script:

build.ps1 (or directly in TeamCity)

	$node_dir = "node-jasmine-dom\bin"	

	& "$node_dir\node.exe" "$node_dir\jasmine-dom" `   
				--config tests.yaml `
				--format junit `
				--output javascript-results.xml 

	write-host "##teamcity[importData type='junit' path='javascript-results.xml']"    

An explanation if it isn’t obvious. First let’s start with files that are needed. I have the windows node-jasmine-dom installed in its own directory. I then call node.exe with jasmine-dom. That should just work all out-of-the-box. I then tell it where the manifest is that knows about the tests (tests.yaml – see below for example) and then I give it the results file. jasmine-node-dom is great because it reads the SpecRunner.html and reconstructs the DOM enough that the tests are valid.

Finally, I tell teamcity to read the results out of junit. This is very easy and I recommend that you find out what else you need to do.


	    name: Example test one
	    runner: ./tests/SpecRunner.html

This yaml file points to the Jasmine runner.

Other points:

* All my jasmine tests are invoked from their own SpecRunner.html file by convention
* I will write a script that will automatically generate the yaml file
* I always put all my powershell scripts into psake scripts (then they can be run by the dev or the build machine)
* my code isn’t quite filed as above

Summary Instructions:

# download jasmine-node-dom and install in tools\ directory
# add new Task to build scripts (I use psake)
# add a new test.yaml manifest (or build one each time)
# Add new jasmine tests via SpecRunner.html with your javascript
# Ensure that the build script is run via a build step in a configuration from TeamCity
# Now you can inspect the Tests in TeamCity

Categories: Uncategorized Tags: , , , , ,

Sharepoint & TDD: Getting started advice

July 1st, 2011 4 comments

I have a couple of people asking lately about starting on SharePoint. They’ve asked about how to move forward with unit and integration testing and stability. No one wants to go down the mocking route (typemock, pex and moles) and quite rightly. So here’s my road map:

The foundations: Hello World scripted and deployable without the GUI

  1. Get a Hello World SharePoint “app” – something that is packageable and deployable as a WSP
  2. Restructure the folders of the code away from the Microsoft project structure so that the root folder has src/, tools/, lib/ and scripts/ folders. All source and tests are in src/ folder. This lays the foundation for a layered code base. The layout looks like this sample application
  3. Make the compilation, packaging, installation (and configuration) all scripted. Learn to use psake for your build scripts and powershell more generally (particularly against the SharePoint 2010 API). The goal here is that devs can build and deploy through the command line. As such, so too can the build server. I have a suggestion here that still stands but I need to blog on improvements. Most notably, not splitting out tasks but rather keeping them in the same (because -docs works best). Rather than get reuse at the task level do it as functions (or cmdlets). Also, I am now moving away from the mix with msbuild that I blogged here and am moving them into powershell. There is no real advantage other than less files and reduced mix of techniques (and lib inclusions).
  4. Create a build server and link this build and deployment to it. I have been using TFS and TeamCity. I recommend TeamCity but TFS will suffice. If you haven’t created Build Definitions in TFS Workflow allow days-to-weeks to learn it. In the end, but only in the end, it is simple. Becareful with TFS, the paradigm here is that build server does tasks that devs don’t. It looks a nice approach. I don’t recommend it and there is nothing here by design that makes this inevitable. In TFS, you are going to need to build two build definitions: SharePointBuild.xaml and SharePointDeploy.xaml. The build is a compile, package and test. The deploy simply deploys to an environment – Dev, Test, Pre-prod and Prod. The challenge here is to work out a method for deploying into environments. In the end, I wrote a simple self-host windows workflow (xamlx) that did the deploying. Again, I haven’t had time to blog the sample. Alternatively, you can use psexec. The key is that for a SharePoint deployment you must be running on the local box and the most configurations have a specific service account for perms. So I run a service for deployment that runs under that service account.

Now that you can reliably and repeatably test and deploy, you are ready to write code!

Walking Skeleton

Next is to start writing code based on a layered strategy. What we have found is that we need to do two important things: (1) always keep our tests running on the build server and (2) attend to keeping the tests running quickly. This is difficult in SharePoint because a lot of code relates to integration and system tests (as defined by test automation pyramid). We find that integration tests that require setup/teardown of a site/features get brittle and slow very quickly. In this case, reduce setup and teardown in the the system tests. However, I am also had a case where the integration test showed that a redesigned object (that facaded SharePoint) would give better testability for little extra work.

  1. Create 6 more projects based on a DDD structure (Domain, Infrastructure, Application, Tests.Unit, Tests.Integration & Tests.System). Also rename your SharePoint project to UI-[Your App], this avoids naming conflicts on a SharePoint installation. We want to create a port-and-adapters application around SharePoint. For example, we can wrap property bags with repository pattern. This means that we create domain models (in Domain) and return them with repositories (in Infrastructure) and can test with integration tests.
  2. System tests: I have used StoryQ with the team to write tests because it allows for a setup/teardown and then multiple test scenario. I could use SpecFlow or nBehave just as easily.
  3. Integration tests: these are written classical TDD style.
  4. Unit tests: these are written also classical TDD/BDD style
  5. Javascript tests: we write all javascript code using a jQuery plugin style (aka Object Literal) – in this case, we use JSSpec (but I would now use Jasmine) – we put all tests in Tests.Unit but the actual javascript is still in the UI-SharePoint project. You will need two sorts of tests: Example for exploratory testing and Specs for the jasmine specs. I haven’t blogged about this and need to but is based on my work for writing jQuery plugins with tests.
  6. Deployment tests: these are tests that run once that application is deployed. You can go to an ATOM feed which returns the results of a series of tests that run against the current system. For example, we have the standard set with tells us the binary versions and which migrations (see below) have been applied. Others check whether a certain wsp has been deployed, different endpoints are listening, etc. I haven’t blogged this code and mean to – this has been great for testers to see if the current system is running as expected. We also get the build server to pass/fail a build based on these results.

We don’t use Pex and Moles. We use exploratory testings to ensure that something actually works on the page

Other bits you’ll need to sort out

  • Migrations: if you have manual configurations for each environment then you’ll want to script/automate this. Otherwise, you aren’t going to be one-click deployments. Furthermore, you’ll need to assume that each environment is in a different state/version. We use migratordotnet with a SharePoint adapter that I wrote – it is here for SharePoint 2010 – there is also a powershell runner in the source to adapt – you’ll need to download the source and compile. Migrations as an approach works extremely well for feature activation and publishing.
  • Application Configuration: we use domain models for configuration and then instantiate via an infrastructure factory – certain configs require SharePoint knowledge
  • Logging: you’ll need to sort of that Service Locator because in tests you’ll swap it out for Console.Logger
  • WebParts: can’t be in a strongly typed binary (we found we needed another project!)
  • Extension Methods to Wrap SharePoint API: we also found that we wrapped a lot of SharePoint material with extension methods

Other advice: stay simple

For SharePoint developers not used to object oriented programming, I would stay simple. In this case, I wouldn’t create code with abstractions that allowed you to unit test like this. I found in the end the complexity and testability outweighed the simplicity and maintainability.

Microsoft itself has recommended the Repository Pattern to facade the SharePoint API (sorry I can’t for the life of me find the link). This has been effective. It is so effective we have found that we can facade most SharePoint calls in two ways: a repository that returns/works with a domain concept or a Configurator (which has the single public method Process()).Anymore than that it was really working against the grain. All cool, very possible but not very desirable for a team which rotates people.


August 1st, 2010 No comments

Notes from a jQuery session

Structure of session:

  • Jump into an example
  • Build some new functionality
  • Come back and see the major concepts
  • Look at what is actually needed to treat javascript as a first-class citizen
  • Different testing libraries

Quick why a library in javascript?

  • cross-browser abstraction (dynduo circa 1998 was still hard!)
  • jQuery, MooTools, Extjs, Prototype, GWT, YUI, Dojo, …
  • I want to work with DOM with some UI abstractions – with a little general purpose
  • simple HTML traversing, event handling
  • also functional, inline style
  • I want plugin type architecture

Story plugin demo

  • Viewer of StoryQ results
  • StoryQ produces XML, this widget gives the XML a pretty viewer

A screenshot and demo

What would your acceptance criteria be? What do you think some of the behaviours of this page are?


eg should display the PROJECT at the top with the number of tests


think in terms of themes: data, display, events

The tests … what does the application do?

  • run the tests and see the categories
  • data loading: xml
  • display: traversing xml and creating html
  • events: click handlers

Let’s build some new functionality!

Goal: add “Expand All | Contract All | Toggle” functionality to the page


  • The user should be able to expand, collapse or toggle the tree


* should show “Expand All | Contract All | Toggle”
* should show all results when clicking expand all
* should show only top class when clicked contract all
* should toggle between all and one when clicking on toggle

Coding: Add acceptance

Add Display specs

Add Event specs

Return back to completing the Acceptance

Major aspects we covered

HTML traversing

  • I want to program akin to how I look at the page
  • I may look for: an element, a style, some content or a relationship
  • then perform an action
$(‘div > p:first’)
  • another item
  • “)

    Event handling

    • I want to look at page and add event at that point
    • I want to load data (ie xml or json)
    alert(“div clicked”)
    $(‘div’).bind(‘drag’, function(){
    $.get(‘result.xml’, function(xml){
    $(“user”, xml).each(function(){
  • “).text($(this).text() .appendTo(“#mylist”))

    Functional style

    • almost everything in jQuery are JQuery objects
    • that returns an object
    • every method can call a jQuery object
    • that means you can chain
    • plus I want it to be short code

    .addClass((idx == 4) ? ‘scenario’ : ”)
    .text($(this).attr(‘Prefix’) + ‘ ‘ + $(this).attr(‘Text’))
    .append($(‘‘).text(“a child piece of text”)
    .click(function(){ $(this).addClass(‘click’)}))

    Plugin architecture

    • drop in a widget (including my own)
    • then combine, extend
    • help understand customisation
    • basically just work

    url: ‘/update’,
    data: name,
    type: ‘put’,
    success: function(xml){
    $(‘#flash’).text(“successful update”).addClass(‘success’)

    With power and simplicity … comes responsibility

    • the need to follow conventions
      – plugins return an array
      – plugins accept parameters but have clear defaults
      – respect namespace
    • the need for structure
      – test data
      – min & pack
      – releases
    • the need to avoid mundane, time consuming tasks
      – downloading jquery latest
      – download jQuery UI
      – building and releasing packages
    • needs tests
      – I use jsspec

    Sounds like real software development?

    Treat javascript as a first-class citizen

    Give your plugin a directory structure:


    Generate your plugin boilerplate code

    jQuery Plugin Generator
    * gem install jquery-plugin-generator

    (function($) {
    $.jquery.test = {
    VERSION: “0.0.1″,
    defaults: {
    key: ‘value’

    jquery.test: function(settings) {
    settings = $.extend({}, $.jquery.test.defaults, settings);
    return this.each( function(){
    self = this;
    // your plugin


    Use a build tool to do the … ah … building

    rake acceptance # Run acceptance test in browser
    rake bundles:tm # Install TextMate bundles from SVN for jQuery and…
    rake clean # Remove any temporary products.
    rake clobber # Remove any generated file.
    rake clobber_compile # Remove compile products
    rake clobber_package # Remove package products
    rake compile # Build all the packages
    rake example # Show example
    rake first_time # First time run to demonstrate that pages are wor…
    rake jquery:add # Add latest jquery core, ui and themes to lib
    rake jquery:add_core # Add latest jQuery to library
    rake jquery:add_themes # Add all themes to libary
    rake jquery:add_ui # Add latest jQueryUI (without theme) to library
    rake jquery:add_version # Add specific version of jQuery library: see with…
    rake jquery:packages # List all packages for core and ui
    rake jquery:packages_core # List versions of released packages
    rake jquery:packages_ui # List versions of released packages
    rake jquery:versions # List all versions for core and ui
    rake jquery:versions_core # List jQuery packages available
    rake jquery:versions_ui # List jQuery UI packages available
    rake merge # Merge js files into one
    rake pack # Compress js files to min
    rake package # Build all the packages
    rake recompile # Force a rebuild of the package files
    rake repackage # Force a rebuild of the package files
    rake show # Show all browser examples and tests
    rake specs # Run spec tests in browser

    Testing … acceptance and specs

    • specs: BDD style – DOM traversing and events
    • acceptance: tasks on the GUI with the packaged version (minified or packed)
    • these both server as good documentation as well
    • plus, you have demo page baked in!

    Compiling and packaging

    • Compiling javascript … hhh? … yes, if you minify or pack your code
    • gzip compression with caching and header control is probably easier though
    • packed code is HARD to debug if it doesn’t work

    Now you are ready for some development

    Different ways to test Javascript

    Understanding JavaScript Testing

    • testing for cross-browser issues – so this is useful if you are building javascript frameworks
    • Unit – QUnit, JsUnit, FireUnit,
    • Behvaiour – Screw.Unit, JSSpec, YUITest,
    • Functional with browser launching – Selenium (IDE & RC & HQ), Watir/n, JSTestDriver, WebDriver
    • Server-side: Crosscheck, env.js, blueridge
    • Distributed: Selenium Grid, TestSwarm


    jQuery CheatSheet

    • slide 48: great explanation of DOM manipulation – append, prepend, after, bfore, wrap, replace …
  • 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 )
            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")

    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;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">
        test("Check the xml to object conversion without showing the tree", function() {
          expect( 5 )
                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")
     &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>

    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;
    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;
    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(){

    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';
        jQuery(function() {
              url: '../../xml/results-01.xml', 
              success: null, 
              load: function(feed) {
                data = feed;
    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 = {};
            url: 'data/results-01.xml', 
            load: '',
            success: function(feed) {
              target = feed
      'should return an object': function() {
      'should not be a function': function() {
        value_of(typeof target).should_not_be(typeof Function )
      'should have a version': function(){
      'should have items': function(){
      'should have the same value as the reference object in data/results-01.js': function(){

    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;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 = {};
              url: 'data/results-01.xml', 
              load: '',
              success: function(feed) {
                target = feed
        'should return an object': function() {
        'should not be a function': function() {
          value_of(typeof target).should_not_be(typeof Function )
        'should have a version': function(){
        'should have items': function(){
        'should have the same value as the reference object in data/results-01.js': function(){
          &lt;div style="display:none;">&lt;p>A&lt;/p>&lt;p>B&lt;/p>&lt;/div>

    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:
        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() {
          url: '../../xml/results-01.xml', 
          success: function(feed) {
            data = feed;
    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:


    • 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

    JQuery vs XSLT as REST client for XML resource in the browser

    October 2nd, 2008 1 comment

    This work is to try and help through thinking about XML results through REST in a browser. If we are going to view the results (in a browser) what are the options that treat the results as a GET resource?

    Here are the sample files.

    • Parsing XML files is a no brainer to display in HTML
    • I’d probably avoid using the browser’s xslt engine though – so xslt through javascript is simplified
    • JQuery is central to the real presentation functionality
    • I’d start with option 2 personally and then add XPath as needed to target information and then if this display got more complex add in XSLT
    • You can get there either through (1) XSLT, (2) JQuery itself or (3) JQuery + XSLT + XPath – you really should be familiar with them all anyway
    Here’s a couple of main options:
    1. XML + XSLT/XPath -> HTML + JQuery => Display
    2. HTML + JQuery ++XML => Display
    3. HTML + JQuery +XSLT ++XML => Display
    4. Flex (+ HTML) ++XML => Display
    I have looked at the first two. And that is what I will try and explain. I suspect the other two options are also good. I do have a concern that in using the XSLT parser within a JS plugin it is perhaps delegating too much work to JS (maintenance of enough functionality will probably become an issue). Also beyond that I was looking at is the hyperlinking of resources (my hunch is that JS or Flex will be the way to load and traverse hyperlinked resources)

    I think that the major concern:

    • is a separation of concerns
    • keeping a resource as data that can be asked for and can ask for a service to act on it

    Separation of concerns:

    1. The XML needs to have a life of its own as a resource
    2. The client needs to be able to act on the resource
    3. The client needs to be in control of all of this and don’t want logic to be hiding at the server
    4. On the client, I want to keep separate layout from content from skin
    5. For development, I wouldn’t mind some intellisense; I want good debugging help

    Some findings:

    • One thing to note is that for both approaches I bind a data source to a control. Here I read in XML and load it into an object and then bind this object to the control which then appends the table to the DOM object. This control can also be bound to an html table. In this case, you put a table into the DOM and then the control transforms the table. The later seemed to me to be a server-side solution rather than a late-binding to a resource.
    • I also did a sample XSLT of creating table in HTML from the results (results-as-html-table.xsl). The code was too long for me! I have include that file in the source for reference.

      Option One: XML + XSLT

      This was my initial reaction as the way forward for this solution. Personally, I like XSLT and its declarative nature. But, in practice, I still find it a little slow to programme (I really do forget the syntax and have to relearn it each time – particularly if you start to heavily use namespaces).
    • The xslt on a browser has to have a reference to an xsl in the XML - this really isn’t that good as there is only one view per xml (although if you were working outside of the browser this need not be a problem)
    • XML in many ways does act on itself because it puts an XSLT across it (although limited to one)
    • It was harder to debug the JS in the xslt mode and generally took longer to working in XSLT
    • The key thing to remember is that the target platform is HTML/JS and XSLT is good for transformations from one structure to another. The problem is that while XHTML is XML we are really in a programming mode rather than a transformation mode. I think that the part that is best for the tranformation via XPath is taking the results and combining the bits of information together (that is this case would be in a cell).
    • I had add extra code to late-bind the data into the control as it wasn’t designed to be used in this way (you could rewrite the component to reduce code though)
    In summary, as the transformations got larger, this might still work well. You will need to write a number of xsl files to allow for good modularisation (see DocBook if you have any doubt on this one). In doing, so you can keep alot of the javascript/JQuery work invisible to the main transformations. But I find that really if isn’t great for debugging so I write the JS in another context and then import it back in to the XSL file.

    Option Two: HTML + JQuery ++XML

    Having looked at the XSLT work, I was in the land of JQuery and was finding it hard to get good, flowing code from the HTML/JS perspective. So while what I want to see needs to be parsed declaratively, the way to display and have interactions with it needs to be procedural code.

    Note: I had to patch the flexigrid component to allow transforming data from an XML to JSON source. It assumes that the resource gotten is the object presented.

    • The HTML/JS using an html container was quicker and cleaner to write. I was easier to use code samples to then customise and extend.
    • The browser’s debugging tools such as Firebug played a little more nicely in terms of error handling
    • Honestly, this approach took not more than a third of the time
    • JQuery gives me iterators and finders that makes my code not look dissimilar to the declarative XSLT (I would also be able to use XPath if I really wanted)
    • To keep it clean I will tend to use expected modularisation in Javascript (objects/functions)
    • I’m not convinced that the end result is necessarily any cleaner though
    • I will be able to put unit tests around it though
    • the HTML file is itself a resource


    • I only need to load the xml once
    • both use the same libraries
    • both need to be improved to do a DTD (xsd) check?
    • the REST approach requires that the client transforms the XML to a format that can be bound to the control

      Where to?

    • I probably stick with the HTML approach
    • I’d keep extending the JQuery plugin approach which allows for nice configuration of views
    • I can use either the each iterators with find in JS or use XPath to work out what data I want to (re)present
    • I would probably add another layer of abstraction between the model object and the data source – at the moment what required from the data source and format of the binding object are combined. A factory would easily create that separation – but was too much for this example
    • Alternatively, I would extend the column model so that you can use XPath configuration of data rather than need the pre processing callback in the first instance
    • go and look at options 3 and 4 above at some stage (3 is likely to end up as the alternative above)

      Appendix A: Reference Formats of JSON data format for server

      { page: 1, total: 239, rows: [ {id:'ZW',cell:['ZW','ZIMBABWE','Zimbabwe','ZWE','716']}, }
    Categories: Uncategorized Tags: , ,