Centric connect.engage.succeed

Running AngularJS 2.0 unit tests in Visual Studio

Geschreven door Renzo Veldkamp - 15 april 2016

Renzo Veldkamp
Have you ever wondered how to run JavaScript unit tests in Visual Studio? Or would you like to know how to test your AngularJS component class using unit tests in Visual Studio?

When looking for a test runner, you will soon come across open source products like Karma and Node.js. These tools both involve a lot of command line code that may make you reluctant to even start writing JavaScript unit tests. This article will show you that there is no need for that: there is a great Visual Studio extension available that enables you to run unit tests without writing a single line of command line code.

The object under test

For the sake of simplicity, let's use a straightforward calculator application. It is an AngularJS 2.0 application (because AngularJS is such a nice framework for building your front-end functionality) with a simple interface that lets you enter numeric operands (the keys '0' to '9') and the operators add (+), subtract (-), multiply (*) and divide (/).

The object under test is the 'calculator' component class that performs the calculation functions, as shown underneath. As well as the calculation functions, the class provides properties for the last results of each of the supported operations.

"use strict";

function Calculator() {
    this.lastAdditionResult = 0;

    this.lastSubtractionResult = 0;

    this.lastMultiplicationResult = 0;

    this.lastDivisionResult = 0;

    this.add = function (op1, op2) {
        var result = op1 + op2;
        this.lastAdditionResult = result;
        return result;
    }

    this.subtract = function (op1, op2) {
        var result = op1 - op2;
        this.lastSubtractionResult = result;
        return result;
    }

    this.multiply = function (op1, op2) {
        var result = op1 * op2;
        this.lastMultiplicationResult = result;
        return result;
    }

    this.divide = function (op1, op2) {
        var result = op1 / op2;
        this.lastDivisionResult = result;
        return result;
    }
}

Choosing the test runner

If you start looking for a test runner for AngularJS unit tests, you will most likely come across Karma. The Karma server runs in Node.js. If Node.js hasn't been installed on your computer yet, you'll have to do that first. This does take a fair bit of command line code, but if you have no problems with that, you will discover that Karma is a good test runner.

If you like to use Visual Studio (Test Explorer), a great extension is available: "Chutzpah Test Adapter for the Text Explorer". It was written by Matthew Manela (http://matthewmanela.com) and is available under the Apache licence. (Chutzpah means audacity, by the way.)

If you search for "Chutzpah Test Adapter for the Text Explorer", it will show up in the Visual Studio Extension Manager:

Visual Studio Extension Manager Chutzpah

Choose Download to start downloading this extension and click Install to accept the licence terms and conditions and start the installation:

Download And Installl Chutzpah

Once the installation is complete, you will need to restart Visual Studio.

Calculator unit tests

The final decision you should make is which unit testing framework to use. I recommend Jasmine (http://jasmine.github.io) for AngularJS applications. However, this is not the only framework you can use: the Chutzpah extension also supports QUnit and Mocha. Jasmine is available as a NuGet package: search for ‘jasmine’:

NuGet Jasmine

Select the project and click Install. Next, click OK in the Preview dialog:

NuGet Preview Install Jasmine

Some of the unit tests (or specs as Jasmine calls them) that we would like to run are shown below.

/// <reference path="../js/Calculator.js" />

"use strict";

describe("addition tests", function () {
    var componentClassToTest;

    beforeEach(function () { // test setup
        if (!componentClassToTest) {
            componentClassToTest = new Calculator();
        }
    });

    it("Add 1 to 2 should result in 3", function () {
        var addition = componentClassToTest.add(1, 2);

        expect(addition).toEqual(3);
    });

    it("Add 1 to -2 should result in -1", function () {
        var addition = componentClassToTest.add(1, -2);

        expect(addition).toEqual(-1);
    });

    it("Add b to 1 should result in error thrown", function () {
        var addition = function () {
            componentClassToTest.add(b, 1); // b is undefined, so throw an exception
        }

        expect(addition).toThrow();
    });

    // this test will fail
    it("Add 'b' to 1 should result in error thrown", function () {
        var addition = componentClassToTest.add('b', 1);

        expect(addition).toThrow();
    });

    afterEach(function () { // test cleanup
        componentClassToTest = null;
    });
});

This is not an extensive test set, but it is enough to show Chutzpah at work. The files containing specs may be included in your (main) project, or in a separate unit test project that includes both C# unit tests and Jasmin specs. Feel free to send me any suggestions for improvement!

Running and debugging tests

Once the Chutzpah extension has been installed and your Jasmine specs have been written, open the Test Explorer window. If your solution hasn't been built yet, it may show (C#) unit tests that are already present. Simply build your solution and Bob’s your uncle.

Your Jasmine specs are shown in the window and can be organised in the same way as ordinary unit tests using playlists. If you run the tests using Test Explorer, the results will look like this:

Test Explorer Addition Tests

Debugging is also supported:

Test Explorer Debug Tests

Maintenance

If you add any extra specs later, they won’t show up in Test Explorer until the project has been built. If we want to add a spec for executing a division by zero, we need to take the following steps:

Add file for new type of specs

Add File For New Specs

Add extra spec(s)

Test Explorer Extra (Division) Tests

Save file

After saving, the new specs will show up in the Test Explorer window, ready to be run.

Conclusion

As you can see, there is no command line code involved and it's easy! Whether your unit tests have been written using Jasmine, QUnit or Mocha, they integrate really nicely into Visual Studio with this great extension. Just get started and enjoy it!

We'll show you more of the calculator app in new blog posts later on.

By the way, did I mention that AngularJS is a great framework?! :-)

About Renzo
Craft Expert Renzo Veldkamp is part of the .NET team within Craft, the development programme for IT professionals (powered by Centric). If you would like to follow his blog, sign up for Craft updates.

Tags:.NET

     
Reacties
  • http://HockeyBias.com
    Charlie@HockeyBias.com
    19 april 2016
    Very cool! Thanks for sharing.

    I have been using Visual Studio Code recently to explore something new, but I have been a .NET/Visual Studio developer for years.

    I am not a fan of a lot of the command line interaction of the Angular 2 world, but I am slowly getting used to it.

    This looks like a nice alternative.
  • Centric
    Renzo Veldkamp
    20 april 2016
    Good to hear that you like the post!
  • Simone
    05 september 2016
    And the great thing is: it also works without AngularJs ;-)
Schrijf een reactie
  • Captcha image
  • Verzenden