ts-mocha is a lightweight wrapper around the Mocha testing framework, designed to simplify the execution of TypeScript test files. It integrates with `ts-node` to compile TypeScript on the fly, eliminating the need for a separate compilation step prior to running tests. The package is currently at version 11.1.0 and maintains an active release cadence, frequently updating to support newer versions of Mocha, ts-node, and TypeScript itself. Its primary differentiator is the 'zero-config' approach to getting TypeScript tests running with Mocha, abstracting away complex `ts-node` and `tsconfig-paths` configurations. It also offers specific TypeScript-centric features like optional type-checking during test runs and path mapping resolution, which are crucial for larger TypeScript projects.
npm install ts-mochaVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates installing ts-mocha and its peer dependencies, creating a basic TypeScript test file using Mocha and Chai, and then running the tests from the command line, including an example with path mapping.
Ensure `ts-node` is installed as a direct `devDependency`: `npm install -D ts-node`.
If you utilize path mapping in your `tsconfig.json`, install `tsconfig-paths` as a `devDependency`: `npm install -D tsconfig-paths`. Additionally, remember to enable it with the `--paths` flag during CLI execution.
To enable full type checking during tests, use the `--type-check` flag with the ts-mocha CLI: `ts-mocha --type-check test/**/*.spec.ts`.
Install `tsconfig-paths` (`npm i -D tsconfig-paths`) and pass the `--paths` flag to the ts-mocha CLI: `ts-mocha --paths test/**/*.spec.ts`.
When using watch mode, always include `--watch-files` with a glob pattern matching your TypeScript source and test files: `ts-mocha -w --watch-files '**/*.ts' test/**/*.spec.ts`.
Install ts-node as a development dependency: `npm install -D ts-node`.
Install `tsconfig-paths` (`npm install -D tsconfig-paths`) and ensure you pass the `--paths` flag to the ts-mocha CLI: `ts-mocha --paths test/**/*.spec.ts`.
Ensure `mocha` and `ts-node` meet the peer dependency requirements of your `ts-mocha` version. Update these packages if necessary (`npm update mocha ts-node`). Clean `node_modules` and reinstall: `rm -rf node_modules && npm install`.