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.
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.