Simple TypeScript setup to debug Mocha tests from VS Code
Anton Kosyakov
Posted on January 6, 2019
ts-node is a convenient tool to run TypeScript code without compilation. In Theia project it enables us to debug any Mocha spec TS file in one click from VS Code or Gitpod. It worked quite well for a long time and provided fast turnarounds.
Over time, the codebase grew and ts-node had to interpreter more and more code to run even a single file. Besides slowness, ts-node evaluates not exactly in the same way how TypeScript compiles. For instance, it ignores some properties from tsconfig leading to missing types.
We started looking for a TypeScript setup to run and debug tests without ts-node. Generally, removing dependencies to ts-node was quite straightforward. We got immediate benefits like an instant startup of tests, fewer npm packages to install and so on.
The missing part was to preserve fast turnarounds of tests execution for a single spec file from VS Code. One should be able to put a breakpoint in TS source code and debug it with one click. After changes, it was possible only with generated JS code.
I had started by reproducing the issue with a minimal setup:
- only TypeScript and Mocha installed;
-
watch npm script compiles TS code with
tsc -w
; - and test script runs all tests with
mocha lib/**/*.spec.js
.
After that, I focused on getting the right launch configuration to debug tests from a single TS file. The issue boiled down to explaining VS Code which generated JS file to run for the currently opened TS file. Here variable substitution came very handy. Particularly, fileBasenameNoExtension
variable provides a name of the currently opened file without an extension. For instance, if you open src/repo.spec.ts
file then it resolves to repo.spec
.
In the end, Mocha Tests configuration emerged. It executes tests from all files matching **/${fileBasenameNoExtension}.js
. In the case with repo.spec.ts
that are tests from files matching ../repo.spec.js
.
You can try it out with VS Code or from your browser with Gitpod (requires OAuth with GitHub):
Posted on January 6, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.