A simple jQuery Qunit-based JavaScript Unit Test Project Template | John V. Petersen


: 3

UPDATE: I just updated the template. You can download it here.

Next week, I’m giving a talk on JavaScript Unit Testing at Codestock. I think this is my 5th year. Always a great show and am looking forward to seeing everyone in Knoxville, TN. The talk is going to be divided into 3 parts: 1 – recognizing and implementing testable JavaScript code, 2 – JavaScript Unit Testing fundamentals and 3 – Visual Studio integration. It is the 3rd part that I want to discuss right now. I’ve just uploaded a new JavaScript unit test project template to the Visual Studio Gallery.


There is a need for a simple unit test project that is devoted to JavaScript unit testing. For this template, I chose the jQuery QUnit project. To make full use of the template, you will also need the Chutzpah JavaScript Unit Test Runner installed. Chutzpah integrates your JavaScript Unit tests.

Once the extension is installed, the add-in will be available:

(Yes, I know the project type reads as Visual C#… When I created the template, I decided to start with a class library project – like any other unit test project. I could have hosted this in a Windows Store JavaScript project – but that would have left folks out that have not upgraded to Windows 8 yet. )


To get up and running, I added a simple Hello World QUnit JavaScript unit test. The following example shows the template in action:

Consider the following solution structure:


This solution has 3 projects: ASP.NET MVC, MVC Unit Test and a JavaScript Unit Test Project. To illustrate how to put your web project’s js code under test, I created a myFunctionTests.js file –  which corresponds to the myFunctions.js file in the UnitTesting.Web MVC Project. Here is the code for myFunction.js:

var myFunctions = (function () {
    var _functions = {};

    _functions.add = function (items) {
        var total = 0;
        for (var i in items)
            total += items[i];
        return total;

    return _functions;

A very simple function that takes an array of numbers and adds them together. Here’s the test in the JavaScript Unit Test Project:
(Take note of how to reference the js file that hosts the function under test.)

/// <reference path="../../../unittesting.web/scripts/myfunctions.js" />

test("My Function Add Test", function () {
    var result = myFunctions.add([1, 2, 3]);
    var expected = 6;

    ok(result == expected, "Result: " + result  + ", expected: " + expected);

In addition, there is also a standard unit test project which was added when the MVC project was created. The following figure shows the Visual Studio Test Explorer running all of our tests (in my Test Explorer settings, I’ve opted to organize the tests by project):


If I was to alter the test by changing the expected value to 5 and saved the file, the affected tests will run again. The following figure shows our unit test in a failed state: