Unit Testing JavaScript with QUnit in Visual Studio
Visual Studio 2013 is an excellent IDE, but it lacks good native support for modern web development. Today, we will see how to unit test JavaScript using Chutzpah and QUnit:
- Install the Chutzpah Visual Studio Extension
Create a new ASP.NET Web Application (Empty) Project
Add a new JavaScript file called "calc.js" with some simple logic to test:
//The functionality to test
function add( a, b ) {
return a + b;
};
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
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");
});
Run the Unit Tests from the Test Explorer by clicking "Run All"
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.