Mocha/Chai with TypeScript
Tags: tutorial, typescript, javascript, webdev
Published: 2020-04-15 19:00:00

# Introduction

I wanted to create some tests for [tsParticles](https://github.com/matteobruni/tsparticles) (leave a star if you want 🌟, it's free 👀), and I didn't know anything about them.

{% github matteobruni/tsparticles %}

I started searching and I found some informations about *Mocha* and *Chai* for writing tests in *Javascript* and in *TypeScript* but I had to read multiple articles at once because they were incomplete.

If you need to unit test your TypeScript code you're in the right place.

Let's start!

# Requirements

Before starting writing tests we need some libraries added to our project.

I will use *npm* but you can use *yarn* too (obvious, thanks).

```shell
npm install chai mocha ts-node @types/chai @types/mocha --save-dev
```

Once the installation is complete we are almost ready.

Add a `test` key to your *package.json* `scripts`, like this

```json
"test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha -r ts-node/register 'tests/**/*.ts'"
```

This will set the right flag for module, *if you have commonjs already you can skip everything until `mocha`*, for `ts-node` that supports only *commonjs* modules then it runs tests using `mocha`.

This is a bit outdated, check out the updated article for a simpler installation.

{% link https://dev.to/matteobruni/mochachai-with-typescript-2023-update-281f %}

I prefer using a *tests* folder than some *.test.ts* files. This will require an `exclude` key in your *tsconfig* (if you have one, obviously).

This is a sample taken from my config

```json
"exclude": [
  "./tests/",
  "./node_modules/",
  "./dist/"
],
```

Once everything is set we can start writing tests.

# Tests

Writing a test with `chai` is really easy, I started writing almost immediately.

Let's see a sample, it's faster than all words I can write.

```typescript
import { Options } from '../src/Classes/Options/Options'; // this will be your custom import
import { expect } from 'chai';

describe('Options tests', () => { // the tests container
	it('checking default options', () => { // the single test
		const options = new Options(); // this will be your class

                /* detect retina */
		expect(options.detectRetina).to.be.false; // Do I need to explain anything? It's like writing in English!

		/* fps limit */
		expect(options.fpsLimit).to.equal(30); // As I said 3 lines above

        expect(options.interactivity.modes.emitters).to.be.empty; // emitters property is an array and for this test must be empty, this syntax works with strings too
		expect(options.particles.color).to.be.an("object").to.have.property("value").to.equal("#fff"); // this is a little more complex, but still really clear
    });
});
```

You can see the simplicity of the syntax, `chai` is a really simple test writing library.

If you want to start writing your own tests that's all you need. Super easy.

If you want to read every function available in `chai` you can find all of them [here](https://www.chaijs.com/api/bdd/).

# Running Tests

Once the test is completed we can try it with the command we prepared at the beginning

```shell
npm test
```

and if you did everything right the output will be something like this

```shell
> tsparticles@1.13.0-alpha.0 test /path/to/your/project/
> env TS_NODE_COMPILER_OPTIONS='{"module": "commonjs" }' mocha -r ts-node/register 'tests/**/*.ts'



  Options tests
    ✓ checking default options
    ✓ check default preset options


  2 passing (16ms)
```

If something is not working you'll get a message like this

```shell
> tsparticles@1.13.0-alpha.0 test /path/to/your/project/
> env TS_NODE_COMPILER_OPTIONS='{"module": "commonjs" }' mocha -r ts-node/register 'tests/**/*.ts'



  Options tests
    1) checking default options
    ✓ check default preset options


  1 passing (48ms)
  1 failing

  1) Options tests
       checking default options:
     AssertionError: expected undefined not to be undefined
      at Context.<anonymous> (tests/Options.ts:19:45)
      at processImmediate (internal/timers.js:456:21)



npm ERR! Test failed.  See above for more details.

```

An error blocking any future command, so you can run the tests before the build script, like this

```json
"build": "npm test && tsc",
```

and with the command below you can now test and build

```shell
npm run build
```

If the tests will pass the build will proceed as expected, otherwise the tests failing will stops the process.

If you want to see my configuration you can find everything [here](https://github.com/matteobruni/tsparticles).

Happy Testing 😏