Wednesday, February 11, 2015

Using QUnit with Visual Studio

QUnit Overview

QUnit is a JavaScript unit testing framework similar to MS Test or NUnit.  In order for QUnit to work, you need a reference to QUnit.js and also a QUnit.css file.

Given the following JavaScript:

function ExtractNumbers(text) {
    if (!text)
        return text;
    return text.replace( /\D+/g, '');

Here is a corresponding QUnit test:

QUnit.test( "ExtractNumbers", function( assert ) {
  assert.equal( ExtractNumbers("Logan 5, Francis 7"), "57", "Passed!" );

I have created a JSFiddle to demonstrate:

Using QUnit with Visual Studio and MS Test

Follow these steps to create a QUnit project with Visual Studio:
1.  Create a blank web project (not a class library like you would do for MS Test or NUnit)
2.  Create a similar folder structure for the JavaScript files you wish to test.
3.  Add the JavaScript files as links in your project
4.  Add a NuGet package reference to QUnit
5.  Under Tools -> Extensions and updates, Visual Studio Gallery.  Search and Install Chutzpah Test Adapter for the Test Explorer which is a JavaScript test runner for Visual Studio.  Also install Chutzpah Test Runner Context Menu Extension.  Chutzpah works with QUnit, Jasmine, and Mocha testing frameworks.
6.  Add a JavaScript file that will be used for the tests.  Add a reference at the top to the JavaScript file you wish to test by simply dragging and dropping the file to the top.  Here is an example:

/// <reference path="../../UI/Scripts/Common.js" />

QUnit.test("ExtractNumbers", function (assert) {
    assert.equal(ExtractNumbers("Logan 5, Francis 7"), "57", "Passed!");


Using QUnit with Resharper

Follow the same steps above for Resharper except Chutzpah is not required for Resharper.  Resharper works out of the box with QUnit and Jasmine to run JavaScript tests.

No comments:

Post a Comment