To Unit Test Javascript with QUnit in Visual Studio

While Visual Studio (2013) is an excellent IDE, it lacks good native support for modern web development. Today, we will see how to unit test Javascript using Chutzpah and QUnit:

1) Install the Chutzpah Visual Studio Extension

In Visual Studio, go to Tools -> Extensions and Updates. 

In Visual Studio, go to Tools -> Extensions and Updates. 

Search Online for "Chutzpah" and install both the Test Adapter and Context Menu Extensions.

Search Online for "Chutzpah" and install both the Test Adapter and Context Menu Extensions.

2) Create a new ASP.NET Web Application (Empty) Project

On the next screen, choose "Empty"

On the next screen, choose "Empty"

3) Add a new Javascript file called calc.js with some simple logic in it:

//The functionality to test
function add( a, b ) {
    return a + b;
};

4) Add a second Javascript file called calcTests.js. At the top of the file, add a reference to the calc.js file so Visual Studio can locate the code-under-test like so:

/// <reference path="{path}" />
/// replace {path} with the path to your calc.js

5) Add test cases by using the "test" function defined by QUnit

/// <reference path="d:\vsprojects\JsUnitTests\JsUnitTests\calc.js" />

test( "Adding 0 and 0", function () {
    var result = add( 0, 0 );
    equal( result, 0, "should equal 0" );
} );

test( "Adding 4 and 5", function () {
    var result = add( 4, 5 );
    equal( result, 9, "should equal 9" );
} );

6) Run the Unit Tests from the Test Explorer by clicking "Run All"

If the Test Explorer is not visible, you can show it again from the Main Menu by going to Test -&gt; Windows -&gt; Test Explorer

If the Test Explorer is not visible, you can show it again from the Main Menu by going to Test -> Windows -> Test Explorer

In future posts, we will repeat this exercise with Jasmine and Mocha, two other popular Javascript unit testing frameworks. Luckily, the excellent Chutzpah extension works with all three.