During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows:
➜ typescript-project yarn test
yarn run v1.22.17
warning package.json: No license field
$ mocha --require ts-node/register test/**/**
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/xiaoqiangjiang/source/reddwarf/demo/typescript-project/test/stack.ts
at new NodeError (node:internal/errors:371:5)
at Object.file: (node:internal/modules/esm/get_format:72:15)
...
To replicate this issue, I created a minimal project structure. Below is the package.json
configuration of the TypeScript project:
{
"type": "module",
"devDependencies": {
"@types/chai": "^4.3.0",
"@types/mocha": "^9.1.0",
...
},
"scripts": {
"test": "mocha --require ts-node/register test/**/**"
}
}
The test file content is as follows:
import { expect } from 'chai';
describe('Stack', () => {
it('can be initialized without an initializer', () => {
});
});
Furthermore, here is the tsconfig.json
configuration used in the project:
{
"compilerOptions": {
"esModuleInterop": true,
...
}
}
Upon running the yarn test
command, the error persists. However, removing the
"type": "module",
line resolves the issue. It seems that mocha does not fully support projects with a module type. Is there a way to make mocha work seamlessly with a module-based project structure?