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

使用Mocha进行TypeScript单元测试时遭遇「Cannot use import statement outside a module」错误

解决Mocha + TypeScript 中 "Cannot use import statement outside a module" 错误

问题根源

你的项目存在两个核心冲突:

  1. package.json 中设置了 "type": "module"(启用ES模块),但 tsconfig.json 里 compilerOptions.module 配置为 commonjs(编译为CommonJS模块),模块系统不统一。
  2. Mocha 没有被配置为使用 ts-node 处理 TypeScript 文件,导致直接尝试解析TS文件中的ES语法,引发报错。

解决方案步骤

1. 统一模块系统

首先移除 package.json 中的 "type": "module" 字段,因为你的TypeScript配置是编译为CommonJS,保持配置一致:

{
  "name": "unittest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  // 移除这一行:"type": "module",
  "scripts": {
    "test": "mocha",
    "build": "rm -rf dist && tsc"
  },
  // ... 其他配置不变
}

2. 配置Mocha使用ts-node处理TypeScript

修改 package.json 中的 mocha 配置,指定用 ts-node/register 来转译TypeScript文件,同时调整测试文件匹配规则(只加载.spec.ts测试文件,避免误加载源文件):

{
  // ... 其他配置
  "mocha": {
    "check-leaks": true,
    "globals": ["crypto"],
    "recursive": true,
    "require": ["ts-node/register"], // 新增该行,让Mocha用ts-node处理TS文件
    "spec": ["./*.spec.ts"] // 仅匹配测试文件
  }
}

你也可以直接修改scripts.test命令,显式指定ts-node:

"scripts": {
  "test": "mocha -r ts-node/register ./*.spec.ts",
  "build": "rm -rf dist && tsc"
}

3. 验证修复

运行 npm test,此时Mocha会通过ts-node正确转译TypeScript测试文件,执行你的测试用例。


额外检查点

  • 确认 ts-node 和 typescript 已正确安装(你的devDependencies中已包含,无需额外安装)。
  • 如果后续需要切换为ES模块,需调整 tsconfig.json 的 module 为 ESNext,同时Mocha命令需要添加 --experimental-specifier-resolution=node 参数,并且保留 package.json 的 "type": "module",但这种配置复杂度较高,入门阶段推荐先使用CommonJS保持简单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 03:09:08