4

I adapted a project to use Mocha, and I ran into a bizarre error that took me a while to diagnose.

> npm run test

TypeError: Unknown file extension ".ts" for C:\code\mocha-example\packages\typescript\test\index.spec.ts`
... stack ... 
at Object.exports.handler (C:\code\mocha-example\packages\typescript\node_modules\mocha\lib\cli\run.js:374:5)

I reviewed a lot of questions about this error which suggested changing the typescript compiler options, none of that worked, neither did changing the "type":"module" or any of the other suggestions.

So, I built up a minimal reproduction from the mocha example:

https://github.com/mochajs/mocha-examples/tree/master/packages/typescript

Turns out, call "fetch" from "node-fetch" as follows causes the issue:

import fetch from "node-fetch";
const foo = async () => {
    return fetch("http://www.example.com");
};
export default function (incomingText: string) {
    return `${incomingText}-static`;
}

The function foo isn't executed by the test, but it still causes the error. It also doesn't error if I don't reference fetch in any way, even just a console.log(fetch) is enough.

Here's the test as-is from the example, just for reference.

import { equal } from "assert";
import index from "./";

describe("Typescript usage suite", () => {
  it("should be able to execute a test", () => {
    equal(true, true);
  });
  it("should return expected string", () => {
    equal(index("incoming"), "incoming-static");
  });
});

I added both "node-fetch" and "@types/node-fetch" to the local repo. Having the types doesn't make a difference. I have no idea how just referencing fetch caused that error.

  • It seems that your example folder is part of a larger repo, with a package.json in mocha_examples and another one in mocha_examples/packages/typescript. Have you run `npm install` in the inner folder? – GOTO 0 Dec 03 '21 at 05:51
  • 1
    Yes. Sorry if it wasn't clear. The example folder builds/and tests pass no problem until the node-fetch dependency is added to the inner project, and the "fetch" command is referenced. – Jeremy Hughes Dec 03 '21 at 12:30

2 Answers2

1

For anybody facing same issue: node-fetch starting with v3 is ESM only, a lot of things broke. You can always

npm i node-fetch@2

to use a version that works with mocha and typescript.

godraadam
  • 11
  • 1
0

I have faced the same issue and found a solution. Since node-fetch doesn't support esm from v3, you need to use node-fetch-cjs instead. You can see details here.