You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS项目用Mocha和Chai测试时出现.ts文件扩展名未知错误

NestJS项目Mocha测试报错:未知.ts文件扩展名

问题场景

按以下步骤操作后运行测试报错:

  • 全局安装NestJS CLI:npm i -g @nestjs/cli
  • 创建项目:nest new project-name
  • 安装测试依赖:npm install --save-dev mocha chai @types/mocha @types/chai
  • 配置package.json、tsconfig.json、.mocharc.json,编写CalculatorService及测试文件test/calculator.service.spec.ts
  • 执行npm test时,运行的命令为:
project-name@0.0.1 test
cross-env TS_NODE_COMPILER_OPTIONS='{"module": "commonjs" }' mocha -r ts-node/register 'test/**/*.ts'

随即抛出错误:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: 未知的文件扩展名 ".ts",路径为 /var/www/html/project-name/test/calculator.service.spec.ts

错误堆栈信息:

at new NodeError (node:internal/errors:399:5)
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:99:9)
at defaultGetFormat (node:internal/modules/esm/get_format:139:38)
at ESMLoader.defaultLoad (node:internal/modules/esm/load:83:20)
at ESMLoader.load (node:internal/modules/esm/loader:342:43)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:207:22)
at new ModuleJob (node:internal/modules/esm/module_job:63:26)
at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:231:17)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:184:34)

修复方案

这个问题源于Node.js的ESM模块加载器无法识别.ts文件,且ts-node配置与项目模块模式不兼容,以下是几种可行的修复方式:

方案1:切换项目为CommonJS模块模式

在package.json中添加或修改type字段:

{
  "type": "commonjs"
}

这样Node会默认使用CommonJS加载器,ts-node的register加载器就能正常处理.ts文件。

方案2:适配ESM模式配置

如果需要保留项目的ESM模式(package.json中type为module),修改测试脚本和Mocha配置:

  1. 更新package.json的test脚本:
{
  "scripts": {
    "test": "cross-env TS_NODE_COMPILER_OPTIONS='{\"module\": \"ESNext\"}' mocha -r ts-node/esm 'test/**/*.ts'"
  }
}
  1. 在.mocharc.json中添加ESM相关配置:
{
  "node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm"]
}

方案3:统一tsconfig.json模块配置

确保tsconfig.json的module字段与测试时的配置一致,比如设置为CommonJS:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES2020",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

方案4:使用ts-mocha简化配置

安装ts-mocha替代原生mocha+ts-node,它会自动处理TypeScript加载:

npm install --save-dev ts-mocha

修改test脚本:

{
  "scripts": {
    "test": "ts-mocha 'test/**/*.ts'"
  }
}

内容的提问来源于stack exchange,提问作者Vishal Kamal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 23:20:07