使用 Typescript 运行 mocha 会抛出: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: 未知文件扩展名“.ts”

ang*_*ala 6 mocha.js node.js typescript

我正在尝试使用 Typescript 和Mocha编写一些测试。

根据其文档,我最终得到了以下设置:

包.json

{
//...
  "scripts": {
    "test": "mocha",
  },
//...
}
Run Code Online (Sandbox Code Playgroud)

.mocharc.json

{
  "extension": ["test.ts"],
  "spec": "tests/*.test.ts",
  "require": "ts-node/register",
  "recursive": true
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
    "compilerOptions": {
        "outDir": "dist",
        "module": "commonjs",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": false,
        "strict": true,
        "esModuleInterop": true,
        "isolatedModules": true,
    },
    "files": [
        "src/main/main.ts",
    ],
}
Run Code Online (Sandbox Code Playgroud)

运行npm test会抛出以下错误:TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for [...]/tests/task.test.ts

这是我唯一的测试,为了完整性,它一直有效,直到我导入一个单独的.ts文件( ):../src/core/task

任务.test.ts

import { assert } from 'chai';
import { Task } from '../src/core/task';

describe('Task', () => {
    it('Task Run', () => {
        const task = new Task({
            title: "My Title",
            command: "echo hello",
            path: "."
        });
        
        task.run();
    })
});
Run Code Online (Sandbox Code Playgroud)

我根据其他一些答案尝试了我的配置的几种排列,但ts-mocha没有成功。

mar*_*ndt 6

我在 ts-node@9 中工作之前遇到了同样的问题,但在 ts-node@10 中没有,然后我尝试了此配置以.mocharc.json使其按预期工作

{
  "extensions": ["ts"],
  "spec": ["**/*.spec.*"],
  "node-option": [
    "experimental-specifier-resolution=node",
    "loader=ts-node/esm"
  ]
}
Run Code Online (Sandbox Code Playgroud)