Combine mocha, Typescript (and watch)

2019-05-29 02:41发布

问题:

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?

回答1:

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!



回答2:

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"
}