unit testing TypeScript

Few days ago TypeScript 0.97 was promoted to version 1.0RC which means that there will be no more changes for version 1.0, just bug fixes. At the same time Visual Studio 2013 Update 2 RC was announced with full TypeScript support out of the box, without having to separately download the tools. It is obvious that Microsoft are pushing TypeScript to be a first class citizen in the Visual Studio eco-system. What’s missing? Unit testing! Did they not notice? How could they call it 1.0 without a viable unit testing framework out of the box?

Here comes ReSharper 8.2 (which is not yet released, beta bits available on the JetBrains website). Best new feature – TypeScript unit testing of course!

Here is my setup:

  • Visual Studio 2013 Update 2 (RC)
  • ReSharper 8.2 (Beta)
  • PhantomJS (from PhantomJS.org) installed and configured
  • QUnit definition file – qunit.d.ts (from DefinitelyTyped)

Create a new HTML TypeScript Application project in Visual Studio and delete index.html, app.ts and app.css files (like to start clean).

Create a folder “libs” and put qunit.d.ts there.

Create a folder “tests” and put a file helloWorld.ts like this:

///<reference path="../libs/qunit.d.ts"/>

test("hello world test", ()=>
{
    ok(true, "hello world test");
});

The test icon appears in front of the test method. Run the test to make sure all is configured correctly.

Now create a folder “app” and put a file MyClass.ts in it:

module MyModule
{
    export class MyClass
    {
        private x: number;

        constructor(x: number)
        {
            this.x = x;
        }

        getX(): number
        {
            return this.x;
        }
    }
}

Finally create a test class MyClass.Tests for that class in folder “tests”:

///<reference path="../libs/qunit.d.ts"/>
///<reference path="../app/MyClass.ts"/>

module MyModule.Tests
{
    test("my test", ()=>
    {
        // arrange
        var myClass = new MyModule.MyClass(5);

        // act
        var result = myClass.getX();

        // assert 
        equal(result, 5, "result is 5");
    });
}

Magic! Love it or hate it ReSharper saves the day (again)…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s