Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine mocha, Typescript (and watch)

I've created a project where I want to use mocha to test my Typescript code. If I do this:

mocha ts/test --compilers ts:typescript-require

After I make a change, it will fail with a message like:

error TS2307: Cannot find module 'mocha'.

This is strange because if I just run tsc everything is fine (I have all my type definitions and I'm using a tsconfig.json file). I also installed typescript-require for mocha.

But each time I run the command after that, it works?!? But if I put mocha in watch mode:

mocha -w ts/test --compilers ts:typescript-require

Then it works the first time through but fails after that. Ugh! Any suggestions on how to get a robust setup involving mocha and Typescript so that I can test and watch?

like image 967
Michael Tiller Avatar asked Oct 07 '15 15:10

Michael Tiller


3 Answers

For me I had to add a prefix like **/

mocha -r ts-node/register "test/**/*.ts" --watch --watch-files **/*

And for multiple specific folders/files:

mocha -r ts-node/register "test/**/*.ts" --watch --watch-files src/**/*,test/**/*

like image 61
Ido Avatar answered Oct 22 '22 17:10

Ido


I wrote ts-node after running into a similar use-case (https://github.com/TypeStrong/ts-node). I needed to run tests with different test runners and compiling to a different directory doesn't cut it because I also like inlining the test fixtures. It's been expanded into feature complete node runtime for TypeScript (including a CLI with a cool little .type command feature). There's an example in the README for executing it with Mocha.

It's all in-memory right now, but eventually it will be expanded with additional flags to make it reasonable for production usage (E.g. no runtime overhead, just compilation startup). Let me know how it goes for you!

like image 31
blakeembrey Avatar answered Oct 22 '22 15:10

blakeembrey


this command watch typescript test changes and fire them (ts-node should be installed):

"scripts": {
"watch": "mocha -r ts-node/register test/*Test.ts  --watch --watch-extensions ts"
}
like image 41
Alex Cumarav Avatar answered Oct 22 '22 17:10

Alex Cumarav