How to setup mocha in typescript ES Module

Install dependencies

npm

npm install -D mocha chai ts-mocha typescript ts-node

.mocharc.json for typescript ESM project

{
  "extension": [
    "ts"
  ],
  "node-option": [
    "experimental-specifier-resolution=node",
    "loader=ts-node/esm.mjs"
  ],
  "spec": [
    "test/**/*.spec.ts"
  ]
}

"test/**/*.spec.ts" is pattern all test files

"node-option" is node cli arguments

ensure type module in package.json

{
  "type": "module"
}

Make sample test

create file test/basic.spec.ts with below codes

import assert from 'assert';

describe('My function', function () {
  it('should test', function () {
    assert.equal(1, 2);
  });
});

How to test

mocha test all patterns from .mocharc.json

mocha

mocha testing bulk files

ts-mocha test/*.spec.ts

mocha testing single file

ts-mocha test/basic.spec.ts

mocha test reporting to html

mocha --reporter doc > reports/report.html

Result Screenshots

Using ts-mocha