43

Before ask this question, I checked similar topics and tried typical solutions.

I know what the frequent cause is "module": "ESXXXX" in TypeScript configuration. In my case, I have error

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for D:\IntelliJ IDEA\XXXXXX\node_modules\tsconfig-paths\src\__tests__\config-loader.test.ts

in both "module": "ESnext" and "module": "CommonJS" cases.

One of typical solution is usage of ts-node/esm. First, this feature is experimental. Next, it just replace one error with another:

(node:24788) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

× ERROR: CustomError: Cannot find module 'D:\IntelliJ IDEA\XXXXX\node_modules\tsconfig-paths\register' imported from D:\IntelliJ IDEA\XXXXX\node_modules\mocha\lib\nodejs\esm-utils.js

Versions

  • mocha: 9.2.1
  • ts-node: 10.7.0

Mocha config

extension:
  - ts

spec: "**/*.test.ts"

require:

  - ts-node/register
  - tsconfig-paths/register

loader: ts-node/esm # Tried with and without

4
  • 1
    I'm working on this same issue. Looks like the issue here: github.com/node-fetch/node-fetch/issues/1279 Commented Mar 15, 2022 at 23:31
  • @CraigFisher, Thank you for listening of the voice of us, Mocha users. Would you please to write the cause in answer? I'll give you the reputation points. Commented Mar 16, 2022 at 10:01
  • 1
    What a nightmare. I was getting this because had one new package that was ESM, but the test run wasn't telling me that was the cause at all. I was only getting this really generic error. So also check if you have any only ESM modules. If you can avoid them, I guess do so as it's a whole world of hurt. Commented Jan 20, 2023 at 9:20
  • I gave up and switched to using vitest, it works pretty well
    – Porlune
    Commented Aug 1 at 11:38

10 Answers 10

26

i'm using same configuration like yours but it only work when i downgrade to ts-node@9, and then i tried this option in my .mocharc.json and now it's working as i expected

{
  "extensions": ["ts"],
  "spec": ["**/*.spec.*"],
  "node-option": [
    "experimental-specifier-resolution=node",
    "loader=ts-node/esm"
  ]
}
1
  • Downgrading ts-node to @9 helped me as well, even despite I have a different setup: mocha -r ts-node/register -r tsconfig-paths/register tests/startup.ts tests/**/*.test.ts. It's absolutely strange since I have a few repositories, and in one of them ts-node@10 went fine. Might be a dependency clash. In this repo where I needed @9, I'm using typia.io for dynamic types validation. Commented Jun 21, 2023 at 11:58
12

I had the same error and it worked for me to set the NODE_OPTIONS env var to specify the loader:

NODE_OPTIONS="--loader ts-node/esm" mocha

Taken from here: https://typestrong.org/ts-node/docs/imports#native-ecmascript-modules

It might also help to upgrade to the latest version of ts-node 10.8.0

3
  • 1
    This should be the accepted answer. More info: github.com/nicolo-ribaudo/jest-light-runner/pull/50
    – Alec Mev
    Commented Aug 3, 2022 at 23:20
  • For me, this just triggers an additional error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension "" Commented May 1, 2023 at 23:36
  • Why not put that option in a mocharc file as @martiendt recommends? wfm Commented Jun 12, 2023 at 14:51
11

This absolutely misleading error with mocha/ts-node may happen in case any of your dependencies are ES6 modules (!), but your TypeScript target is not. For instance, when having a package [email protected] installed:

✗ npm run test      

> @[email protected] test
> mocha -r ts-node/register tests/**/*.test.ts


TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /.../tests/index.test.ts
...

And now downgrading to npm i got@11, which still provides CommonJS exports:

npm run test

> @[email protected] test
> mocha -r ts-node/register tests/**/*.test.ts

// All right

So a "quick fix" for this annoying error might be to downgrade a certain package you have just upgraded (typically, a major version). This is related to got, node-fetch, and other packages that decide to publish ES6 only code.

Otherwise, you have to update your entire test suite. I don't know any "ultimate" fix for the mocha+ts-node setup for this problem. Some other test suites like vitest or playwright work well with ES6 deps out of the box, and in some projects I personally started to use "transpile-then-test" approach rather than testing directly on TypeScript sources with runtime ts-node.

7
  • 1
    This was quite useful. I actually had to travel back 4 major versions on serialize-error to find one, that did work. Then the vNext of this NPM stated, that ESM was required. Enabling ESM however, causes many other new errors for me. While I am still stuck, you provided enough "more" context to understand it. Thanks!
    – Samuel
    Commented Jan 21 at 15:04
  • Did you manage to find a work-around for the issue in the end? I have this exact same issue but would preferably apply the new major version rather than sticking to v4 of chai
    – Daniel
    Commented Feb 22 at 19:05
  • 1
    Hi @Daniel! As I explain in the post, I moved my repos to a transpile-then-test approach, where you don't need ts-node/register at runtime. For instance, in my setup in most service-level repos on TypeScript, I use "build": "tsc && tsc-alias" in package.json, which outputs the "build" directory, which includes both .js files and transpiled .test.js files (most of my repos have related tests next to source files). Then, you don't need any ts-node/register or whatever to run your tests, just use "test": "mocha ./build/**/*.test.js" and it will run all tests in the build directory. Commented Feb 28 at 13:02
  • That was my issue as well, I had upgraded chai to version 5 which only supports ESM modules: github.com/chaijs/chai/releases/tag/v5.0.0. Reverting to version 4 fixed it Commented May 15 at 14:31
  • Sounds reasonable! Thank you for the more detailed explanation.
    – Daniel
    Commented May 25 at 7:52
7
+50

Do you have a tsconfig.json. That solution could help here:

{
  "compilerOptions": {
    "esModuleInterop": true,
  }
}

Here is an interesting thread about it with an alternative solution. In that case, the tsconfig has an include that looks like this:

"include": [
    "./**/*.ts"
]

One of these two options should work, but let me know. Not sure what your config looks like.

3
  • 6
    Thank you for the answer. I am sorry, but "esModuleInterop": true did not help (I had this option initially). Also tried "include": [ "Source/**/*" ]. Commented Mar 19, 2022 at 1:57
  • Can you post your config and your import statements?
    – Nice-Guy
    Commented Mar 20, 2022 at 2:54
  • for what did this answer gain the bounty, if it was not the solution to the problem?
    – scipper
    Commented Mar 15 at 10:23
5

Maybe its quite late, but get rid of ts-node use tsx

  • Install tsx, put it in dev dependencies
  • you can remove ts-node from package file
  • modify your test script to
  "test": "mocha --timeout 10000 --import=tsx src/__tests__/**/*.test.ts --exit",

Note: we are getting rid of ts-node

  • Under is tsconfig changes
    "target": "ES2020", 
    "module": "commonjs" 

Note: I am using node v20.11.1

4

I added "type": "module" in package.json and did npx tsx file.ts instead of using ts-node file.ts and it worked.

4

This is a bit late to the party, but I just upgraded my Chai assertion library to an ESM only package and ran into this issue. The problem occurred for me when my typescript files imported Chai. ts-node would rewrite those typescript files to use require('chai') which would throw the error described in this question. For Chai specifically I was able to globally require chai in my mocharc file and then remove the problematic imports from my test files written in typescript.

.mocharc.json Now looks like this for me with "chai/register-expect.js" added to the require array. They have other register-*.js files for should and expect too.

{
  "extension": ["js", "ts"],
  "spec": "test/**/*",
  "require": ["chai/register-expect.js", "ts-node/register"]
}
`
3
  • 2
    I updated a bunch of dependencies and I thought that mocha or ts-node upgrades were the reason my mocha tests were complaining that ".ts" extension is unknown. However, upgrading libs one-by-one showed the place where everything breaks - chai update from 4.3.6 to 5.0.0. Since I'm not an expert neither in js nor in npm, I just left the library at the old version... if you have more details and context, I would gladly follow your instructions and update chai.
    – frangulyan
    Commented Jan 6 at 21:58
  • Typescript/javascript world is such a mess, I have no idea what means ESM or commonjs modules, their compatibility and the whole history behind.
    – frangulyan
    Commented Jan 6 at 22:08
  • 1
    Downgrading chai to 4.3.6 worked for me as well.
    – sambecker
    Commented May 1 at 15:43
2

May be it is too late a bit, but may be help someone:

For me the cause was "too new" url-join depenendency.

So this can happen even if your package.json do not have type: "module" or such, but you have a dependency with type set to module as url-join latest, here error goes.

Mentioned here: https://github.com/piotrwitek/ts-mocha/issues/70#issuecomment-1027582584

0

ts-node/register would do the trick.

Node developers: Add this to your package.json file

"scripts": {"test": "mocha --parallel -r ts-node/register /path/to/test.ts"}
0

If your package.json is set to "type": "module" try the following (taken from https://github.com/mochajs/mocha-examples/issues/47)

tsconfig.json

{
    "compilerOptions": {
        "module": "esnext",
        "moduleResolution": "node",
    }
}

.mocharc.json

{
    "node-option": [
        "experimental-specifier-resolution=node",
        "loader=ts-node/esm"
    ]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.