JavaScript Unit Testing with Visual Studio

JavaScript Unit Testing with Visual Studio

Mark Michaelis walks you through the Visual Studio tooling and project setup you’ll need to get the most out of your JavaScript unit testing.

As I detailed in my recent article “A TypeScript Primer,” I, like many developers, have a love/hate relationship with JavaScript. I love JavaScript because of its ubiquity; from iPhone to Android to Windows Phone, JavaScript just works. From iOS to UNIX to Windows, JavaScript continues to just work. (Admittedly, there are some idiosyncrasies, but for the most part — at least from a language perspective — it just works.)

Unfortunately, JavaScript is lacking in its ability to verify intent. It does what you tell it to do — not necessarily what you want it to do. (If you figure out the secret for getting a computer to consistently do what you want rather than what you tell it, please let me know! I would like to partner with you on a business idea or two.) Table 1has a summary of JavaScript’s good and bad:

Good Bad
Ubiquity No inherent OO
Closures Script (not compiled)
Dynamic at runtime Lacking type safety
Ramp-up is trivial Dynamic at runtime
Vendor independence Modularization/Organization/Namespaces
Frameworks are vibrant Limited IntelliSense capabilities

Table 1. JavaScript, the Good and the Bad

Advertisement

 

Of all these characteristics, it’s JavaScript’s lack of type safety coupled with not having a compiler fail in the capacity to verify intent. That is, of course, if you don’t have unit tests. Unit tests can compensate for the lack of type safety. And unlike with .NET, where unit tests focus mainly on functional verification (since the compiler eliminated the majority of typos), unit tests in JavaScript do both. In summary, JavaScript unit testing is all the more critical because it’s responsible to not only verify functionality, but also to verify syntax and language semantics.

In this article, I’m going to focus on the Visual Studio tooling and project setup requirements needed to get the most out of your JavaScript unit testing.

Tooling
The two most popular Visual Studio integrated tools for JavaScript unit testing are ReSharperand Chutzpah (a Yiddish word about having the audacity to say things as they are — good or bad). Chutzpah is an open source Visual Studio extension and JavaScript test runner written by Matthew Manela. ReSharper is the well-known JetBrains tool, famous for its C# and JavaScript refactoring capabilities.

Both tools are Visual Studio extensions, so installing either into Visual Studio is nothing more than clicking the Tools->Extensions and Updates… menu and searching for “JavaScript Unit Testing” or simply “Chutzpah” or “ReSharper.”

At the core of most JavaScript unit testing lies a headless browser, PHATOMJS.EXE. When this browser launches, it hosts HTML that in turn references your JavaScript files. In addition to the JavaScript files that you supply from your Web project (and the frameworks like JQuery that you reference as part of your production code), JavaScript unit testing generally relies on a unit testing framework. The two primary unit testing frameworks, both of which are open source, areQUnit and Jasmine. Both are well suited for the task of unit testing but each brings a slightly different style to the unit test. QUnit follows the traditional unit-testing style test format, while Jasmine is a behavioral-driven design (BDD) testing framework.

QUnit
As stated on the QUnit Web site, “QUnit is a powerful, easy-to-use JavaScript unit testing framework. It’s used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code, including itself!” Code Listing 1provides a sample QUnit test file.

Code Listing 1: A Sample QUnit Series of Tests 

/// <reference path="QUnit.js" />
/// <reference path="../../intellitect.sharepoint.web/scripts/SampleRestService.js" />
 
var restService = null;
module("SampleRestService.getToken()", {
  setup: function () {
    restService = new SampleRestService("http://IntelliTect.com/Blog");
  },
  teardown: function () {
    restService = null;
  }
});
  test("Provide valid credentials", function () {
    var token = restService.getToken("Inigo.Montoya", "Ykmfptd!");
    equal(token, "ecy8b081wh6owf8o", 
	"The token value returned was not as expected.");
  });
  test("Prevent empty string for the name", function () {
    raises(function() {
      var token = restService.getToken("", "Ykmfptd!");
    }, "Unexpectedly, no error was raised given a blank name.");
  });
  test("Prevent empty null for the password", function () {
    raises(function () {
      var token = restService.getToken("Inigo.Montoya", null);
    }, "Unexpectedly, no error was raised given a null password.");
  });
 
 
module("SampleRestService.downloadFile()")
  test("Throw an exception if file does not exist.", function () {
    raises(function () {
      var restService =
        new SampleRestService("http://IntelliTect.com/Blog", 
		"Inigo.Montoya", null);
      var file = restService.downloadFile("Bog.us");
    }, "Unexpectedly, no error was raised given an invalid file.");
  });

As one would expect, QUnit supports the standard unit testing constructs, including grouping tests into constructs (using module), pre- and post-test execution steps (setup/teardown members), and a variety of assertions: ok, equal, notEqual, strictEqual, notStrictEqual, deepEqual, notDeepEqual, raises. Essentially, the structure mimics that of a developer unit-testing library.

Jasmine
Although very similar, Jasmine’s BDD-based API involves defining a Spec — a grouping of tests or conditions to verify. The spec places each test into a context or scenario and comprises a suit of tests (see Code Listing 2).

Code Listing 2: Jasmine Unit Testing Sample 

/// <reference path="Jasmine.js" />
/// <reference path="../../intellitect.sharepoint.web/scripts/SampleRestService.js" />
 
var restService = null;
describe("SampleRestService.getToken()", function () {
  var restService = null;
  beforeEach(function () {
    restService = new SampleRestService("http://IntelliTect.com/Blog");
  });
  afterEach(function () {
    restService = null;
  });
  it("Provide valid credentials", function () {
    var token = restService.getToken("Inigo.Montoya", "Ykmfptd!");
    expect(token).toBe("ecy8b081wh6owf8o");
  });
  it("Prevent empty string for the name", function () {
    var emptyUserNameExpression = function () {
      var token = restService.getToken("", "Ykmfptd!");
    };
    expect(emptyUserNameExpression).toThrow();
  });
  it("Prevent empty null for the password", function () {
    var nullPasswordExpression = function () {
      var token = restService.getToken("Inigo.Montoya", null);
    };
    expect(nullPasswordExpression).toThrow();
  });
 
});
 
describe("SampleRestService.downloadFile()", function() {
  it("Throw an exception if file does not exist.", function () {
    var fileDoesNotExistExpression = function () {
      var restService =
        new SampleRestService(
		"http://IntelliTect.com/Blog", "Inigo.Montoya", null);
      var file = restService.downloadFile("Bog.us");
    };
    expect(fileDoesNotExistExpression).toThrow();
  });
});

In Jasmine, each test is identified by the it() function; and, like QUnit, tests can be grouped together by context using the describe function in Jasmine. In fact, the describe() functions can be nested to create a hierarchical grouping of tests. The assertions in Jasmine are all functions available from the expect() function return, and include verifications like toBe(), toEqual(), toMatch(), toBeUndefined(), toContain(), toThrow() and so on. Prefixing any of these calls with a not() call asserts the opposite. Jasmine provides specialized mock, fake and spies (verification that functions are called) functionality.

Under the Covers
As mentioned earlier, under the covers, JavaScript unit testing generally relies on a headless browser called PhantomJS.exe, along with a series of HTML files that reference your JavaScript. However, rather than manually creating these HTML files (although you certainly can), Chutzpah generates them for you based on the JS files within your test project. Furthermore, Chutzpah then determines all the tests within your project (whether QUnit or JUnit) and loads them into the Visual Studio Test Explorer Windows (see Figure 1).

[Click on image for larger view.]Figure 1. Visual Studio Test Explorer Window.

Chutzpah also supports a command-line execution via the chutzpah.console.exe executable. (Unfortunately, you might find that using chutzpah.console.exe is required if using Visual Studio 2013 in combination with Windows 8.X and some NVidia drivers.) Additionally, this command-line test runner can be leveraged on your build server even when the Chutzpah extension is not installed (using the TFS Build Service, for example).

Significantly Improve Code Quality
As mentioned earlier, JavaScript unit testing is even more critical than .NET unit testing because of the fact that there is no compiler. However, it isn’t that hard to get started. Furthermore, although it may seem a little time-consuming when you start, those disciplined enough to stick with it will quickly discover that, in fact, unit testing their JavaScript even for just a short while is faster than re-launching the browser and navigating to a particular page (perhaps reclogging in, for example) — significantly faster in the long run. Furthermore, it has the advantages that the tests can be checked in and executed as part of the build process. Therefore, delay no further. Get started with your JavaScript unit testing today and experience one of the most significant ways to improve your code quality in a single practice.

About the Author

Mark Michaelis (http://IntelliTect.com/Mark) is the founder of IntelliTect and serves as the Chief Technical Architect and Trainer. Since 1996, he has been a Microsoft MVP for C#, Visual Studio Team System, and the Windows SDK and in 2007 he was recognized as a Microsoft Regional Director. He also serves on several Microsoft software design review teams, including C#, the Connected Systems Division, and VSTS. Mark speaks at developer conferences and has written numerous articles and books – Essential C# 5.0 is his most recent. Mark holds a Bachelor of Arts in Philosophy from the University of Illinois and a Masters in Computer Science from the Illinois Institute of Technology. When not bonding with his computer, Mark is busy with his family or training for another triathlon (having completed the Ironman in 2008). Mark lives in Spokane, Washington, with his wife Elisabeth and three children, Benjamin, Hanna and Abigail.

Visual Studio Installer

Microsoft Re-Installs Visual Studio Installer

The installer was removed after Visual Studio 2010, and led to an outcry among developers.

Microsoft has brought back a much-missed bit of functionality from Visual Studio 2010 and put it back in Visual Studio 2013: Visual Studio Installer projects.

Tony Goodhew, a program manager on the Visual Studio Platform Team, blogged about the update, calling it “one of the topmost voted on suggestions on User Voice for Visual Studio.” User Voice is a feedback Web site for developers, where they vote on the top requests made for Visual Studio improvements. Visual Studio Installer got 6,174 votes. The majority of requests get fewer than 100 votes, and it’s rare for a suggestion to garner more than 1,000.

The new version is called Visual Studio Installer Projects Extension, and is available in preview mode, downloadable from the Visual Studio Gallery. It provides the same functionality as the Installer in Visual Studio 2010, according to Microsoft.

Visual Studio still provides a third-party installation manager, Flexera’s InstallShield Limited Edition (ISLE). Goodhew noted that ISLE adds additional capabilities not found in Microsoft’s Installer, including “TFS and MSBuild integration, support for creating new web sites and ISO 19770-2 Tagging support.”

An open source set of tools for Windows installations is also available: WiX, which recently moved its source code to GitHub. The latest version, released last November, is 3.8.

There was a lot of discontent among developers with Microsoft’s original decision to remove the Visual Studio Installer template. The announcement of the course reversal drew mostly praise from the comments following the blog. A developer named Daniel Smith, for instance, said “That warm fuzzy feeling inside when you know you’ve done right by your customers is priceless.  It’s a bit like the dude who demoed the return of the start menu at the BUILD conference – you could almost feel his internal tears of joy when the audience stood up and applauded, confirming that it was the right thing to do.”

Advertisement

 

Not everyone was as cheerful. “Scott” said: “Well, the good news is that you listened. The not so good news is that it took two years. And you closed the ironically named “UserVoice” vote on the topic. And you persist in trying to present the Installshield Hobbled Edition as something that we should be grateful for. So we’re glad at this step, but the whole episode has been handled poorly.”

About the Author

Keith Ward is the editor in chief of Visual Studio Magazine.

Windows Phone

Windows Phone Dev Center Upgraded for Universal Apps

The redesigned Web site focuses on Windows Phone 8.1 conversions.

Microsoft has updated its Windows Phone Dev Centerfor the new era of universal Windows apps, since those apps can now cross the Windows Phone boundary and move into the world of Windows 8.1 and Xbox.

The changes to the Dev Center were announced in ablog post by Microsoft’s Keith Senzel, who said the rollout of the new Web site has started, and will have updates throughout the week.

The Dev Center has undergone a redesign, to better service developers building new universal Windows apps or converting previous programs to the universal model. New features include:

  • Windows Phone 8.1 package submissions. This can be done via Silverlight, updated with new features in the Windows Phone 8.1 SDK, or the Windows Runtime, which allows the app to be used across the multiple Windows platforms.
  • Existing Windows Phone apps that are pre-8.1 will be automatically upgraded to the latest edition, without the developer needing to do anything.
  • Platform targeting allows apps to be set to the appropriate Windows Phone version; for example, 8.1 apps will only be offered to Windows Phone 8.1 devices.
  • Reduced certification times. Microsoft claims that app certification has been chopped from days to hours (in most cases).

The Dev Center is a clearinghouse for Windows Phone development. Its development aids include downloadable tools like the Windows Phone SDK, Windows Phone 8.1 development tools and Windows Phone 8.1 emulators; video instruction and interviews related to Windows Phone app development (which are mostly links to Channel 9 content); code samples; links to the Windows Phone Dev Center app, which analyzes apps and provides feedback; and links to the Windows Phone Preview for Developers, released earlier this week.

Senzel also previewed some upcoming Dev Center features. They include promotional app pricing with specific start and end dates; pre-submission validation checks to smooth the certification process; and the ability to define whether an app requires a touch-enabled device.

About the Author

Keith Ward is the editor in chief of Visual Studio Magazine.

Visual Studio 2013

Some Visual Studio 2013 Update 2 Installs Crashing

The problem appears to be related to the location of the setup executable.

Some users have had problems when trying to install Visual Studio 2013 Update 2. For those users, Microsoft has come up with a workaround.

The issue, according to a blog posting by Microsoft’s Heath Stewart, crops up when the install fails with the warning “Setup Failed!” It further indicates that the hash value is wrong.

Stewart recommends saving the program (VS2013.2.exe) to a “different location and running setup again.” Microsoft believes the problem may be related to the location of the setup executable already containing an offline layout. That’s the only way the Visual Studio team has been able to replicate the problem.

“An example of when we see this problem is when, say, the VS2013.2 RC setup executable is downloaded to a folder with an existing layout for CTP1,” Stewart writes.

If the workaround doesn’t solve the problem, Stewart recommends filing a bug report, so that Microsoft can determine if there are other possible causes of the issue.

Visual Studio 2013 Update 2 is at the Community Technology Preview (CTP) 2 stage currently. The final version of Update 2 is expected sometime this spring.

About the Author

Keith Ward is the editor in chief of Visual Studio Magazine.

Update .NET Framework

Microsoft Updates .NET Framework to 4.5.2

Better debugging, support for Async are among the highlights.

Microsoft’s released a new version of the .NET Framework that includes updates for ASP.NET, high-resolution displays and better profiling, among the enhancements.

The .NET Fundamentals Team announced the .NET Framework 4.5.2 on its blog yesterday, calling it a “highly compatible, in-place update to the.NET Framework 4, 4.5 and 4.5.1.”

Some of the most significant improvements concern ASP.NET. A set of new APIs have been released, including HttpResponse.AddOnSendingHeaders  and HttpResponseBase.AddOnSendingHeaders methods. These methods should be superior to PreSendRequestHeaders and PreSendRequestContent events, according to Microsoft.

A boost to Async comes with the HostingEnvironment.QueueBackgroundWorkItem method, for scheduling lightweight background work items. “ASP.NET tracks these items and prevents IIS from abruptly terminating the worker process until all background work items have completed,” the blog states.

Visual Studio developers working with high-resolution screens will like the ability to add responsive design-like functionality. Called “High DPI setting,” it’s an opt-in feature that scales up numerous Windows Forms controls properly. One example from the blog is a ToolStipComboBox control showing a red error glyph. The glyph is nearly impossible to see at high resolution without High DPI. With it, though, it’s clear.

Other updates include:

  • Distributed transactions enhancement that should help in building high-traffic scenarios.
  • New profiling APIs that are less susceptible to unexpected shutdowns.
  • Better activity tracing support that “enables out-of-process, Event Tracing for Windows (ETW)-based activity tracing for a larger surface area,” which should be a boon for app performance management vendors.
  • Debugging improvements.
  • New workflow features.
Advertisement

A number of packages are available for the .NET Framework 4.5.2, including Web and Offline installers, language packs and a Developer Pack for targeting both the 4.5.2 Framework and 4.5.2 runtime.

The .NET Framework was last updated to version 4.5.1 in October 2013. The Web installer for the new version is available from the Microsoft Download Center.

About the Author

Keith Ward is the editor in chief of Visual Studio Magazine.

 

Big Companies Partnership

Two Big Data Companies Form Partnership

Cloudera and MongoDB also announce the MongoDB Connector for Hadoop.

Developers are increasingly focusing on Big Data development, and Hadoop is one of the most popular technologies for the .NET crowd.

That tent just got a little bigger, as Cloudera Inc. and MongoDB Inc. announced a strategic partnership to integrate their Big Data technologies.

Cloudera is one of the main players in the Big Data space, with a popular Hadoop distribution and accompanying bundled packages for enterprises. MongoDB is billed as the most widely used NoSQL database and is often used in Big Data analytics.

Details of the partnership were scant, though the companies said they had the lofty goal to “transform how organizations approach Big Data.”

One immediate aspect of the partnership was the certification of the MongoDB Connector for Hadoop to be used with Cloudera Enterprise 5, the company’s latest package that bundles the Cloudera Distribution Including Apache Hadoop (CDH) with a subscription to Cloudera Manager, a Hadoop administration tool, and technical support.

“Certifying MongoDB’s Connector for Hadoop on Cloudera Enterprise 5 was our first step to help our joint customers,” Kelly Stirman, director of product at MongoDB, said in an interview. “Resources are being invested even further to match our companies’ joint vision, including building a tighter integration of the next version of the MongoDB Connector for Hadoop.”

The companies said no further news on the partnership will be forthcoming until the June 24 kick-off of the MongoDB World conference in New York.

The MongoDB Connector for Hadoop plug-in lets developers more easily use MongoDB as an input source or output destination for processing Big Data with the open source Hadoop framework. The connector obviates the need to use custom code or cumbersome import/export scripts to move data around. It takes advantage of multi-core parallelism, has full integration with the Hadoop and Java Virtual Machine (JVM) ecosystems, is compatible with Amazon Elastic MapReduce, and can use local filesystems, Hadoop Distributed File System (HDFS), or S3 to read and write backup files, MongoDB said in a Webinar last year.

“The connector presents MongoDB as a Hadoop-compatible file system allowing a MapReduce job to read from MongoDB directly without first copying it to HDFS, thereby eliminating the need to move terabytes of data across the network,” MongoDB said last year when the connector was updated. “MapReduce jobs can pass queries as filters, so avoiding the need to scan entire collections, and can also take advantage of MongoDB’s rich indexing capabilities including geospatial, text-search, array, compound and sparse indexes.”

Beyond the connector, the companies hinted at more to come regarding the collaboration. “More than a simple technology integration, the partnership brings the two companies’ leadership to bear in enabling enterprises to fundamentally rethink how data can be shared and put to work across the enterprise,” they said in a statement. “The combination of Cloudera Enterprise and MongoDB will enable customers to easily develop, operate and manage Big Data infrastructure that powers modern applications.”

The announcement was the latest in a string regarding MongoDB, which earlier this month released a major upgrade of its database. Last week, Microsoft announced new high-memory MongoDB instances were available in its Microsoft Azure cloud platform.

About the Author

David Ramel is an editor and writer for 1105 Media.