Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 920
Thomas Avatar asked Nov 17 '14 16:11

Thomas


People also ask

Can Mocha run TypeScript?

TS-Mocha has one only dependency - ts-node, which is used as a TypeScript runtime to execute tests that can import and run imported TypeScript source files as well. It is a thin wrapper that run node process with mocha and set up ts-node environment to handle .

How do I run a test file in TypeScript?

For TypeScript, unit tests are run against the generated JavaScript code. In most TypeScript scenarios, you can debug a unit test by setting a breakpoint in TypeScript code, right-clicking a test in Test Explorer, and choosing Debug.


2 Answers

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.

like image 99
jpierson Avatar answered Sep 24 '22 01:09

jpierson


Don't use this answer. typescript-require is unmaintained, and ts-node is its replacement. Leaving this answer here for posterity.

Found it. The typescript module is actually like a "main" function; it runs the compiler as soon as the module is loaded. Not very nice design.

I poked at Mocha's acceptance tests, which show how to use a custom compiler for foo files. They wire it up via the require.extensions mechanism. I was halfway through writing a module that just calls tsc on the command line when I realized that somebody must have done this before. So it's very simple:

$ npm install typescript-require --save-dev $ mocha --compilers ts:typescript-require 
like image 23
Thomas Avatar answered Sep 23 '22 01:09

Thomas