Taking JavaScript and .NET to the cloud

Menu

Server-Side Testing with Mocha, Chai and TypeScript

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.

Post navigation

4 thoughts on “Server-Side Testing with Mocha, Chai and TypeScript”

Nice post Dino. I like it a lot, and it helped me to start writing some TypeScript code and tests. In your post, I think there is a step missing.

According to the post, one can write test code in TypeScript, and just after that, simply run tests with mocha. Maybe I’m wrong, but I needed to compile (or transpile) the TypeScript code into JavaScript code in order to be able to run the tests with mocha.

Thanks for the feedback! Indeed, we do need to transpile the TypeScript code. We can use tools such as grunt or gulp to perform this step when modifications are made. Does Visual Studio transpile on save? I am curious to know more about this issue.