Unit testing of typescript in visual studio (mocha + chai)


 

You will need following things to do unit test on typescript:

  • Mocha: Its a testing framework, which will help us identify unit tests in Test explorer of VS
  • Chai: Chai is the assertion library which works well with 'mocha'
  • NodeJs tools for Visual Studio: This tool is needed to create NodeJs project in Visual studio.

* I am using Visual Studio 2015 and assuming you have NodeJs environment setup on your machine

To begin, open Visual Studio and add a 'Blank Node.js Web Application' project.



Then add 'TypeScript Mocha Unit Test file' file into the project. (say UnitTest1.ts)




Get 'mocha' definitely typed file from the following location:
and include it in your project at:



 Project
 |
 |_Scripts
 |
 |__typings
 |
 |___mocha (folder)
 |
 |____mocha.d.ts



 
Similarly, add 'chai' definitely typed file from this link
and include in your project under 'Scripts/typings/chai' folder.

Now its time to include the assertion library 'chai' into your project. Right click 'npm' node (which is like references in usual VS projects) and say 'Install new npm packages'.



It will include'chai' package into your project. Verify that your 'package.json' file has been updated with 'chai' module:


"devDependencies": {
    "chai": "^3.4.1"
  }



Other options to include it in your project is by opening the command prompt 'as administrator', go to your project's location and type the following:


npm install --save-dev chai

After this, verify your 'package.json' file is being updated, if not? update it manually as shown above. In VS project, under 'npm' > 'dev' node check if 'chai' node is present without any warnings. Sometimes it shows warning, in that case just update the version of 'chai' to '*' in package.json file.


Similarly, include 'promise' package into your project.

Now we are ready to code!!!

Create a type script class for calculator as shown below:

Calculator.ts
--------------
var Promise = require('promise');
export module Calculator {
    export class Calc {
        static Add(a: number, b: number): number {
            return a + b;
        }

        static AddAsync(a: number, b: number): Promise<any>  {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(a + b);
                }, 1000);
            });
        }
    }
}


Here, we have one method which adds and returns the result directly. Other one returns a promise object which in turns returns result in one second. Lets write test for them one by one.

In our UnitTest1.ts file, we will include our calculator module and chai's expect library.

UnitTest1.ts
------------
var calculator = require('./Calculator').Calculator.Calc;

var chai = require('chai') as Chai.ChaiStatic;
var expect = require('chai').expect;
var assert = require('chai').assert;


Then, we are going to add our first test,

UnitTest1.ts
------------
describe("Calculator", () => {
    it("must add two numbers", () => {
        var result = calculator.Add(1, 2);
        expect(result).equal(3);
    });
});

Here, we simple calling the method of calculator, storing the result and comparing it with '3' the expected output.

In Visual Studio, open 'Test Explorer' and you will see our first test is enlisted. Select the test, right click and say 'run'. It should run successfully and test will pass. You should try debug the test and see how it works internally.

Now, unit test for asynchronous method i.e., AddSync.

UnitTest1.ts
------------
describe("Calculator", () => {
    it("must add two numbers", () => {
        var result = calculator.Add(1, 2);
        expect(result).equal(3);
    });

    it("must add two numbers asynchronously", (done) => {
        var promise = calculator.AddAsync(1, 2);
        promise.then((data) => {
            expect(data).equal(3);
            done();
        });
    });
}); 

We are getting the promise object and checking its result in 'then' section/function. Notice that we have called 'done()' method after the 'expect' statement, which we received as an argument in 'it("",(done))' function. It tells the testing framework that test is complete when 'done()' is being called.


Thats how you do unit test of type script modules using Visual Studio, mocha and chai.

I will come back and see if I can add more to this document.

Comments

Popular posts from this blog

Effectively Use "cbt" command to get Google Cloud BigTable Data

Quickly Setup Golang pprof and debugging for Memory Leak

In Short: SLI, SLO and SLA (and Error Budget)