typescriptmocha.jstypescript-execute

How to run mocha with the tsx TypeScript runner


I'm using the tsx command (similar to ts-node) to run all my TypeScript code.

How can I use tsx to run my Mocha test suite?


Solution

  • Add the following "node-option" key to your .mocharc.json, or to the "mocha" section in your package.json:

    {
      "node-option": ["import=tsx"]
    }
    

    This causes Mocha to run as if you had run it with node --import=tsx, or NODE_OPTIONS="--import=tsx" mocha.

    Note that this requires at Node 18.18.0 or newer. On older Node versions (at least 14.18.0 seems to be required), use the --loader option instead:

    {
      "node-option": ["loader=tsx"]
    }