Skip to content

TypeScript

Newer versions of Node.js can run TypeScript files directly via native type stripping. On modern versions of Node, type stripping is stable and enabled by default. For older versions of Node, use the --experimental-strip-types flag. This feature has not been backported to Node 20.

State202224
Experimentaln/a22.624.0
Stablen/a22.1824.3

You also need --extension ts so Mocha discovers .ts files when scanning directories (the default extensions are .js, .cjs, .mjs).

Note that this does not perform type-checking, it only strips types to allow you to easily run your tests. We recommend using another tool to get the benefits of type-checking.

You can run Mocha against ts files matching your spec pattern either by specifying --extension:

Terminal window
mocha --extension ts

Or in a configuration file such as .mocharc.js:

export default {
extension: ["js", "ts"],
spec: "test/**/*.ts",
};

Add --node-option experimental-strip-types:

Terminal window
mocha --node-option experimental-strip-types --extension ts

Or in .mocharc.js:

export default {
"node-option": ["strip-types"]
"extension": ["js", "ts"]
"spec": ["test/**/*.ts"]
}

The example below uses ESM import syntax. It is a minimal working example that does not include everything for IDE support. For IDE integration, see the mocha-examples TypeScript package.

Given a source file src/add.ts:

export function add(a: number, b: number) {
return a + b;
}

And a test file src/add.test.ts:

import assert from "node:assert/strict";
import { add } from "./add.ts";
describe("add", function () {
it("should add two numbers", function () {
assert.strictEqual(add(1, 2), 3);
});
});

Run with:

Terminal window
npx mocha --extension ts src/add.test.ts

For setups that require TypeScript features beyond type stripping (such as enum, namespace, or path aliases), you can use a register-style loader like tsx via --require:

Terminal window
mocha --require ts-node/register --extension ts

See the mocha-examples TypeScript package for complete working examples with different configurations.