Testing TypeScript with Mocha and Chai

Share on facebook
Share on twitter
Share on linkedin


I am a huge fan of TDD, already wrote a couple of articles in this topic. In one of my recent projects I used Angular as a fronted framework. Usually I use Jasmine for testing in JavaScript (you can find the related article here). Jasmine should also work with TypeScript, but at that time, I got some issues while setting it up, so I looked for another testing framework to work with.

I found Mocha as a good solution used together with Chai assertion library. Let’s see how to set up the testing environment for TypeScript.


As a fist step we install the required packages with npm: mocha, chai, ts-node, and type definitions for both libraries:

Create the first test

Create a simple function for testing:

Let’s create our first test case, and assert that out function works as expected. Obviously in real TDD we should write the test first and the function afterwards, but for demonstration purposes it should be ok.

Run the tests

For running the test, we’ll add a script in the package.json, register ts-node to run mocha and set up the path where the tests can be found, in this example it would be under tests directory:

We can now run the tests with npm:

If everything goes well the test should run and you should see in the console output that it passes.


It is a matter of taste which testing library you choose, the most important thing is to have as many tests as possible, they help us create maintainable and stable applications which is desired in software development.

Subscribe to our newsletter

Be first to read new helpful post

Share this post with your friends

Share on linkedin
Share on xing
Share on twitter
Share on facebook
composer Blog Title Image

10 Tips for PHP Composer

  1. Add the composer.lock and the composer.json to Git.

Composer install will install all the packages you have defined in your composer.lock file.

Changing enum column in Laravel migration

Changing enum type columns is currently not supported in Laravel, and if you try to run something like:

You are about to get following

Leave a Reply

3 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
2 Comment authors
Omar SalemoRyan McGowan Recent comment authors
newest oldest most voted
Notify of

[…] We are having issues running th test so we take another look here: https://42coders.com/testing-typescript-with-mocha-and-chai/ […]

Ryan McGowan
Ryan McGowan

I can’t get Mocha/Chai working on a create-react-app in typescript for some reason.

npx create-react-app my-app –typescript
cd my-app
npm install chai mocha ts-node @types/chai @types/mocha –save-dev

// Follow instructions on this blog

SyntaxError: Unexpected token at { import { expect } from ‘chai’;

Omar Salemo
Omar Salemo

very useful
thank you!