Unit Testing JavaScript methods that contain jQuery ajax calls


Unit test a JavaScript method which contains a $.ajax() call. Using QUnit.


This was supposed to be a simple task, and if I didn’t have a few (now) obvious faults in my JavaScript code, it would have been completed more quickly. I have gone through several answering my own StackOverflow questions on the next day here’s the one in question for the curious ones.

I will hide behind the excuse of it being the early days of the new year and still finding my coding groove after almost two weeks on holiday…

So in this post I’ll summarise the two approaches I came out with in the end. It’s two because neither worked for me first time, and in my attempt to solve the first discovered the second. In the end resolving both. I won’t bother going into much detail about QUnit, as there are many posts out there about it; here, and here and here and official documentation here, and other interesting things to do with it.

As a quick aside we use the NuGet package NQUnit.NUnit to help us integrate QUnit into our Visual Studio projects.

Basic Approach

Solution 1 – basic way as is shown on this StackOverflow answer

// Arrange
    var options,
        jsonText = '{"id": "123", "fieldName": "fbs", "data": "fbs-text"}',

// Set up to 'capture' the ajax call (this forms the mock)
$.ajax = function (param) {
    options = param;

// Act - call the method which is 'under test'
/* ... */

// Call the success (or failure) method to complete the mock of handling of the 'response'

// Assert - verify state of system is as expected
/* ... */

Alternate Approach MockJax

Solution 2 – using the MockJax library with a great walk-through on how to use it here.

There are several advantages in using MockJax, that can be summarised as just having more control over mocking the ajax portion of the method under test, including but not limited to; timeouts, introducing latency, returning HTTP status codes.

After having included MockJax in your project, the solution 1 code gets replaced with 1 method call to $.mockjax() and looks like this.

// Arrange 
    var jsonText = '{"id": "123", "fieldName": "fbs", "data": "fbs-text"}';

// The call to mockjax replaces the need to overwrite the jQuery ajax() method
    url: '/Your/Regular/Action',
    dataType: 'json',
    contentType: 'application/json',
    responseText: jsonText

// Act - call the method which is 'under test'
/* ... */

//perform test assert state of system is as expected
/* ... */


Full QUnit test code is up as a Gist.

Find a working copy of the code here in it’s simplest form: jsfiddle.net/NickJosevski/9ZZmc/4/

Visual Studio Team Test 2010 – Vic.NET Session

Last night I attended the August Victoria.NET user group meeting and it was a good session and it’s timing was great marker to wrap up my sudo-holiday and get me blogging again.

The first topic was about Visual Studio Team Test 2010 presented by Anthony Borton which is a preview of his Aus Tech.Ed 2009 presentation, see Anthony’s blog post.

The second topic was to be Team System Database Edition in Visual Studio 2010 but was called off after the presenter had their flight delayed out of Adelaide.

Back to Team Test 2010, which has some great features in particular features to assist with being able to reproduce issues (bugs) raised by testers. The most impressive was the ability to easily record tests, parameterise and repeat. An example is to launch your application executable perform a few steps, and using a simple control selection tool select a control (i.e. textbox) and use that in the test’s Assert action. In conjunction with the macro recording ability to generate automated user interface tests, when a test fails all the environment details are easily submitted as part of the bug report – operating system version, current memory usage, event log dump, screen shot, extra description fields, and a video recording of the test machines screen. Yes a video recording, to catch the actions of the tester who isn’t sure what exactly they did.

The next impressive feature was it’s virtualisation integration (“Lab Management”), assistance in managing both the environments and the snapshot’ing of state for a given test. Making it possible to go back a significant duration back in time to re-create an issue (conditional on snap-shot retention policy).

In summary Team Test 2010 has some very nice features to greatly assist; recreating issues, reusing tests, reporting bugs.

Additional notes I took away from the presentation:

  • There are some 64-bit issues with 2010 beta’s in particular making use of MCE for video recording.
  • The potential for SP1 of 2010 to include integration with Microsoft Expression Encoder to resolve and improve issues with MCE.
  • Take another look at the “Architecture” edition on Visual Studio 2010, as it has had major overhauls to it’s feeble 2008 feature set.

There was also a give-away of a copy of Visual Studio 2008 and a 12 months MDSN subscription, going to a winner who attended a Queensland user group meeting, congratulations to him.

The next meeting hasn’t been scheduled yet but stay tuned to the victoriadotnet site.