Search code examples
node.jstypescriptmocha.js

How to run Mocha tests written in TypeScript?


Setup: I have a Node project (pure Node, no browser bits) written in TypeScript. I can use the TypeScript compiler (tsc) from the typescript module to compile the code. So far so good.

However, I want to write tests using Mocha, and that's where I'm having trouble. I tried --compilers ts:typescript, but I keep getting errors like:

error TS5023: Unknown compiler option 'compilers'.

It looks like the command line to mocha ends up being passed to tsc, which is obviously not good.


Solution

  • For anybody who has tried and had problems with typescript-require you may want to try ts-node.

    $ npm install -g ts-node
    $ mocha --require ts-node/register src/**/*.spec.ts
    

    It also appears that there has been some ongoing discussion about deprecating typescript-require in favor of ts-node.