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?
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/**/*
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!
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With