Taking JavaScript and .NET to the cloud

Menu

Month: July 2014

Introduction

As applications grow in complexity, being able to run automated tests becomes more and more important. In this post, I will go through the basics of writing and running some tests using TypeScript, along with the help of Mocha and Chai. Although this environment can be used to run on node.js and the browser, the focus today will be on the node.js scenario.

Notice how we make our assertions. Chai allows for the standard TDD-style assert, but it also allows the use of BDD styles, which can be more expressive and understandable, especially to those that aren’t concerned with the specifics of the underlying implementation.

Run the tests

After we successfully compile the code, we just need to run the following command:

$ mocha

Doing so will run all the tests that Mocha can find:

Now, let’s make a test fail. We’ll grab the second test and make an expectation that 2+4 would not equal 6:

Conclusion

Today we were able to setup a test environment for TypeScript code, using Mocha as a test runner, along with the BDD-style syntax provided by Chai. This provides a great approach to testing code that resides in node.js applications.

I was out of town over the weekend, so this is going to be a bit of a filler-post. Nonetheless, I wanted to share some links that may be of interest if you want some more information on TypeScript and tools:

Introduction

In previous posts, I have described how definition files can be retrieved via the Definitely Typed website, which leads you to their GitHub repository. This is all well and good if we need to retrieve a small number of definition files, but it can be a hassle if we want to get several definition files.

Automating definition file retrieval

Thankfully, there is a node package that helps retrieve definition files in a more automated way, So let’s go ahead and install this package, known as tsd:

$ npm install -g tsd

Querying definition files

Now that we have tsd installed, we can run queries to see if we can find definition files:

Installing definition files

Let’s go ahead and give it a shot with a definition file. To install the definition file for, say, mongoose, we run the command:

$ tsd query mongoose --action install

If it all goes well we should get the following:

By default, you will find the definition file in typings/mongoose/mongoose.d.ts.

Tracking all installed definition files

We can take this all a step further and create a tsd.json file to track what definitions we have installed. If this route is chosen, it is worth removing all previously installed definition files and proceed in the following manner: